# HG changeset patch # User bharadwaj # Date 1459885175 14400 # Node ID eda408d4f253d782c376d5ee9626d91c72e6b40e # Parent 64f6ae06310e7b669911a39525f7a6eb6db59f9e# Parent 33688f44fb2a8928c4a659bfaafdfbf10eb16421 Merge diff -r 64f6ae06310e -r eda408d4f253 .hgtags --- a/.hgtags Tue Apr 05 10:34:05 2016 -0700 +++ b/.hgtags Tue Apr 05 15:39:35 2016 -0400 @@ -354,3 +354,4 @@ c870cb782aca71093d2584376f27f0cfbfec0e3a jdk-9+109 4a95f4b1bd8bfce85dc02a593896749feab96c34 jdk-9+110 a6614ff7bf09da74be1d0ef3d9755090d244697a jdk-9+111 +7359994942f8d8e723b584d66a3a92c2e9e95e5c jdk-9+112 diff -r 64f6ae06310e -r eda408d4f253 .hgtags-top-repo --- a/.hgtags-top-repo Tue Apr 05 10:34:05 2016 -0700 +++ b/.hgtags-top-repo Tue Apr 05 15:39:35 2016 -0400 @@ -354,3 +354,4 @@ 1787bdaabb2b6f4193406e25a50cb0419ea8e8f3 jdk-9+109 925be13b3740d07a5958ccb5ab3c0ae1baba7055 jdk-9+110 f900d5afd9c83a0df8f36161c27c5e4c86a66f4c jdk-9+111 +03543a758cd5890f2266e4b9678378a925dde22a jdk-9+112 diff -r 64f6ae06310e -r eda408d4f253 common/conf/jib-profiles.js --- a/common/conf/jib-profiles.js Tue Apr 05 10:34:05 2016 -0700 +++ b/common/conf/jib-profiles.js Tue Apr 05 15:39:35 2016 -0400 @@ -241,8 +241,7 @@ target_os: "linux", target_cpu: "x64", dependencies: concat(common.dependencies, "devkit"), - configure_args: common.configure_args, - configure_args: concat(common.configure_args, "--with-zlib=system"), + configure_args: concat(common.configure_args, "--with-zlib=system"), make_args: common.make_args }, @@ -251,8 +250,8 @@ target_cpu: "x86", build_cpu: "x64", dependencies: concat(common.dependencies, "devkit"), - configure_args: concat(common.configure_args, common.configure_args_32bit), - configure_args: concat(common.configure_args, "--with-zlib=system"), + configure_args: concat(common.configure_args, common.configure_args_32bit, + "--with-zlib=system"), make_args: common.make_args }, @@ -260,8 +259,7 @@ target_os: "macosx", target_cpu: "x64", dependencies: concat(common.dependencies, "devkit"), - configure_args: common.configure_args, - configure_args: concat(common.configure_args, "--with-zlib=system"), + configure_args: concat(common.configure_args, "--with-zlib=system"), make_args: common.make_args }, @@ -269,8 +267,7 @@ target_os: "solaris", target_cpu: "x64", dependencies: concat(common.dependencies, "devkit", "cups"), - configure_args: common.configure_args, - configure_args: concat(common.configure_args, "--with-zlib=system"), + configure_args: concat(common.configure_args, "--with-zlib=system"), make_args: common.make_args }, @@ -278,8 +275,7 @@ target_os: "solaris", target_cpu: "sparcv9", dependencies: concat(common.dependencies, "devkit", "cups"), - configure_args: common.configure_args, - configure_args: concat(common.configure_args, "--with-zlib=system"), + configure_args: concat(common.configure_args, "--with-zlib=system"), make_args: common.make_args }, diff -r 64f6ae06310e -r eda408d4f253 corba/.hgtags --- a/corba/.hgtags Tue Apr 05 10:34:05 2016 -0700 +++ b/corba/.hgtags Tue Apr 05 15:39:35 2016 -0400 @@ -354,3 +354,4 @@ b75afa17aefe480c23c616a6a2497063312f7189 jdk-9+109 9666775734fb6028ee86df9972626b3667b6a318 jdk-9+110 2bb92dd44275679edb29fdbffc3b7cbebc9a6bf0 jdk-9+111 +780d0620add32bf545471cf65038c9ac6d9c036d jdk-9+112 diff -r 64f6ae06310e -r eda408d4f253 hotspot/.hgtags --- a/hotspot/.hgtags Tue Apr 05 10:34:05 2016 -0700 +++ b/hotspot/.hgtags Tue Apr 05 15:39:35 2016 -0400 @@ -514,3 +514,4 @@ 7e7e50ac4faf19899fc811569e32cfa478759ebb jdk-9+109 2f5d1578b24060ea06bd1f340a124db95d1475b2 jdk-9+110 c558850fac5750d8ca98a45180121980f57cdd28 jdk-9+111 +76582e8dc9e6374e4f99ab797c8d364b6e9449b4 jdk-9+112 diff -r 64f6ae06310e -r eda408d4f253 hotspot/src/share/vm/classfile/vmSymbols.hpp --- a/hotspot/src/share/vm/classfile/vmSymbols.hpp Tue Apr 05 10:34:05 2016 -0700 +++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp Tue Apr 05 15:39:35 2016 -0400 @@ -656,7 +656,7 @@ \ /* JVMTI/java.lang.instrument support and VM Attach mechanism */ \ template(jdk_internal_module_Modules, "jdk/internal/module/Modules") \ - template(sun_misc_VMSupport, "sun/misc/VMSupport") \ + template(jdk_internal_vm_VMSupport, "jdk/internal/vm/VMSupport") \ template(transformedByAgent_name, "transformedByAgent") \ template(transformedByAgent_signature, "(Ljava/lang/reflect/Module;)V") \ template(appendToClassPathForInstrumentation_name, "appendToClassPathForInstrumentation") \ diff -r 64f6ae06310e -r eda408d4f253 hotspot/src/share/vm/services/attachListener.cpp --- a/hotspot/src/share/vm/services/attachListener.cpp Tue Apr 05 10:34:05 2016 -0700 +++ b/hotspot/src/share/vm/services/attachListener.cpp Tue Apr 05 15:39:35 2016 -0400 @@ -43,7 +43,7 @@ // Implementation of "properties" command. // -// Invokes sun.misc.VMSupport.serializePropertiesToByteArray to serialize +// Invokes VMSupport.serializePropertiesToByteArray to serialize // the system properties into a byte array. static Klass* load_and_initialize_klass(Symbol* sh, TRAPS) { @@ -59,8 +59,8 @@ Thread* THREAD = Thread::current(); HandleMark hm; - // load sun.misc.VMSupport - Symbol* klass = vmSymbols::sun_misc_VMSupport(); + // load VMSupport + Symbol* klass = vmSymbols::jdk_internal_vm_VMSupport(); Klass* k = load_and_initialize_klass(klass, THREAD); if (HAS_PENDING_EXCEPTION) { java_lang_Throwable::print(PENDING_EXCEPTION, out); diff -r 64f6ae06310e -r eda408d4f253 hotspot/src/share/vm/services/diagnosticCommand.cpp --- a/hotspot/src/share/vm/services/diagnosticCommand.cpp Tue Apr 05 10:34:05 2016 -0700 +++ b/hotspot/src/share/vm/services/diagnosticCommand.cpp Tue Apr 05 15:39:35 2016 -0400 @@ -316,8 +316,8 @@ } void PrintSystemPropertiesDCmd::execute(DCmdSource source, TRAPS) { - // load sun.misc.VMSupport - Symbol* klass = vmSymbols::sun_misc_VMSupport(); + // load VMSupport + Symbol* klass = vmSymbols::jdk_internal_vm_VMSupport(); Klass* k = SystemDictionary::resolve_or_fail(klass, true, CHECK); instanceKlassHandle ik (THREAD, k); if (ik->should_be_initialized()) { diff -r 64f6ae06310e -r eda408d4f253 hotspot/test/compiler/gcbarriers/PreserveFPRegistersTest.java --- a/hotspot/test/compiler/gcbarriers/PreserveFPRegistersTest.java Tue Apr 05 10:34:05 2016 -0700 +++ b/hotspot/test/compiler/gcbarriers/PreserveFPRegistersTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -25,6 +25,7 @@ /** * @test * @bug 8148175 + * @ignore 8153194 * @run main/othervm/timeout=300 -Xbatch -Xmx128m PreserveFPRegistersTest */ public class PreserveFPRegistersTest { diff -r 64f6ae06310e -r eda408d4f253 hotspot/test/gc/metaspace/TestMetaspacePerfCounters.java --- a/hotspot/test/gc/metaspace/TestMetaspacePerfCounters.java Tue Apr 05 10:34:05 2016 -0700 +++ b/hotspot/test/gc/metaspace/TestMetaspacePerfCounters.java Tue Apr 05 15:39:35 2016 -0400 @@ -37,6 +37,7 @@ * java.compiler * java.management * jdk.jvmstat/sun.jvmstat.monitor + * @ignore 8151460 * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UseSerialGC TestMetaspacePerfCounters * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UseParallelGC -XX:+UseParallelOldGC TestMetaspacePerfCounters * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UseG1GC TestMetaspacePerfCounters diff -r 64f6ae06310e -r eda408d4f253 hotspot/test/gc/metaspace/TestPerfCountersAndMemoryPools.java --- a/hotspot/test/gc/metaspace/TestPerfCountersAndMemoryPools.java Tue Apr 05 10:34:05 2016 -0700 +++ b/hotspot/test/gc/metaspace/TestPerfCountersAndMemoryPools.java Tue Apr 05 15:39:35 2016 -0400 @@ -36,6 +36,7 @@ * @modules java.base/sun.misc * java.management * jdk.jvmstat/sun.jvmstat.monitor + * @ignore 8151460 * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseCompressedOops -XX:-UseCompressedKlassPointers -XX:+UseSerialGC -XX:+UsePerfData -Xint TestPerfCountersAndMemoryPools * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UseCompressedOops -XX:+UseCompressedKlassPointers -XX:+UseSerialGC -XX:+UsePerfData -Xint TestPerfCountersAndMemoryPools */ diff -r 64f6ae06310e -r eda408d4f253 jaxp/.hgtags --- a/jaxp/.hgtags Tue Apr 05 10:34:05 2016 -0700 +++ b/jaxp/.hgtags Tue Apr 05 15:39:35 2016 -0400 @@ -354,3 +354,4 @@ 24e247ee1fffaa625d480b2a4eef2d3a8a59f5cb jdk-9+109 1c1bb661d35b846dc04931bd5f687a0348f80345 jdk-9+110 27a3d65e1580386d060e0aa3a68ab52c1a9ab568 jdk-9+111 +36326537f929d20cc5885b93939f90c0efcc4681 jdk-9+112 diff -r 64f6ae06310e -r eda408d4f253 jaxp/test/ProblemList.txt --- a/jaxp/test/ProblemList.txt Tue Apr 05 10:34:05 2016 -0700 +++ b/jaxp/test/ProblemList.txt Tue Apr 05 15:39:35 2016 -0400 @@ -23,4 +23,6 @@ # ########################################################################### -# No jaxp tests are on the problem list. +# 8147431 +javax/xml/jaxp/isolatedjdk/catalog/PropertiesTest.sh generic-all + diff -r 64f6ae06310e -r eda408d4f253 jaxp/test/javax/xml/jaxp/isolatedjdk/catalog/PropertiesTest.sh --- a/jaxp/test/javax/xml/jaxp/isolatedjdk/catalog/PropertiesTest.sh Tue Apr 05 10:34:05 2016 -0700 +++ b/jaxp/test/javax/xml/jaxp/isolatedjdk/catalog/PropertiesTest.sh Tue Apr 05 15:39:35 2016 -0400 @@ -25,6 +25,7 @@ # @bug 8077931 # @summary This case tests if the properties FILES, DEFER, PREFER, RESOLVE in # jaxp.properties and system properties could be used. +# @key intermittent # @library ../../libs/ # @build catalog.CatalogTestUtils # @build PropertiesTest diff -r 64f6ae06310e -r eda408d4f253 jaxws/.hgtags --- a/jaxws/.hgtags Tue Apr 05 10:34:05 2016 -0700 +++ b/jaxws/.hgtags Tue Apr 05 15:39:35 2016 -0400 @@ -357,3 +357,4 @@ 4b0697e4ce8940b1599af274ff02296d7f59aded jdk-9+109 0db939c930f332dfa275cedfc7cf223ff1221ea4 jdk-9+110 4d5296e0920afe7ef8d4db1939b76f0d407a3812 jdk-9+111 +21274e7937bae291658d68143aca0e3ee9296db0 jdk-9+112 diff -r 64f6ae06310e -r eda408d4f253 jdk/.hgignore --- a/jdk/.hgignore Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/.hgignore Tue Apr 05 15:39:35 2016 -0400 @@ -7,3 +7,5 @@ ^make/netbeans/.*/dist/ ^.hgtip .DS_Store +.*/JTreport/.* +.*/JTwork/.* diff -r 64f6ae06310e -r eda408d4f253 jdk/.hgtags --- a/jdk/.hgtags Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/.hgtags Tue Apr 05 15:39:35 2016 -0400 @@ -354,3 +354,4 @@ 1c7bad0798900fe58f4db01ae7ffdc84f5baee8c jdk-9+109 9417e1bcded6af5532c3b26235437ab227758877 jdk-9+110 b2a69d66dc65ad1d3aeb3bd362cf5bb0deba040e jdk-9+111 +1565a0efe6f0ca411a6df277df1e069431c60988 jdk-9+112 diff -r 64f6ae06310e -r eda408d4f253 jdk/make/gendata/GendataBreakIterator.gmk --- a/jdk/make/gendata/GendataBreakIterator.gmk Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/make/gendata/GendataBreakIterator.gmk Tue Apr 05 15:39:35 2016 -0400 @@ -63,11 +63,9 @@ ifeq ($(BOOT_JDK_MODULAR), true) BREAK_ITERATOR_BOOTCLASSPATH := -Xpatch:$(BREAK_ITERATOR_CLASSES) \ - -XaddExports:$(subst $(SPACE),$(COMMA),$(strip \ - java.base/sun.text=ALL-UNNAMED \ - java.base/sun.text.resources=ALL-UNNAMED \ - jdk.localedata/sun.text.resources.ext=ALL-UNNAMED \ - )) + -XaddExports:java.base/sun.text=ALL-UNNAMED \ + -XaddExports:java.base/sun.text.resources=ALL-UNNAMED \ + -XaddExports:jdk.localedata/sun.text.resources.ext=ALL-UNNAMED else BREAK_ITERATOR_BOOTCLASSPATH := -Xbootclasspath/p:$(call PathList, \ $(BREAK_ITERATOR_CLASSES)/java.base \ diff -r 64f6ae06310e -r eda408d4f253 jdk/make/gensrc/Gensrc-java.base.gmk --- a/jdk/make/gensrc/Gensrc-java.base.gmk Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/make/gensrc/Gensrc-java.base.gmk Tue Apr 05 15:39:35 2016 -0400 @@ -55,7 +55,6 @@ # copied to zh_HK locale. $(eval $(call SetupCopy-zh_HK,COPY_ZH_HK, \ $(addprefix $(JDK_TOPDIR)/src/java.base/share/classes/, \ - sun/misc/resources/Messages_zh_TW.java \ sun/security/util/AuthResources_zh_TW.java \ sun/security/util/Resources_zh_TW.java))) diff -r 64f6ae06310e -r eda408d4f253 jdk/make/gensrc/GensrcModuleLoaderMap.gmk diff -r 64f6ae06310e -r eda408d4f253 jdk/make/netbeans/client_sanity/README --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/make/netbeans/client_sanity/README Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,15 @@ +This NetBeans project corresponds to client sanity test suite in jdk/test/sanity/client. + +It simplifies working on the suite in NetBeans. + +It also includes the following custom tasks: + +prepare-bundle creates dist/sanity.zip containing standalone bundle of the suite + +run-jemmy-browser runs Jemmy browser for the ButtonDemo (hardcoded in build.xml file) + The tool allows to explore the UI hierarchy. + +There is no task to run tests using JTReg. Please refer to corresponding README file +in the client sanity test suite folder on how to run the tests. + +Contact alexander.kouznetsov@oracle.com in case of issues. \ No newline at end of file diff -r 64f6ae06310e -r eda408d4f253 jdk/make/netbeans/client_sanity/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/make/netbeans/client_sanity/build.xml Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,94 @@ + + + + + + + + + + + Builds, tests, and runs the project SanityTests. + + + + + + + + + + + + + + + + + + + + + diff -r 64f6ae06310e -r eda408d4f253 jdk/make/netbeans/client_sanity/manifest.mf --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/make/netbeans/client_sanity/manifest.mf Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +X-COMMENT: Main-Class will be added automatically by build + diff -r 64f6ae06310e -r eda408d4f253 jdk/make/netbeans/client_sanity/nbproject/build-impl.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/make/netbeans/client_sanity/nbproject/build-impl.xml Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1429 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.src3.dir + Must set src.src4.dir + Must set src.src2.dir + Must set src.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + No tests executed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + Must select one file in the IDE or set profile.class + This target only works when run from inside the NetBeans IDE. + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + Must select some files in the IDE or set test.includes + + + + + Must select one file in the IDE or set run.class + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + Must select some files in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + Must select one file in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff -r 64f6ae06310e -r eda408d4f253 jdk/make/netbeans/client_sanity/nbproject/genfiles.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/make/netbeans/client_sanity/nbproject/genfiles.properties Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,8 @@ +build.xml.data.CRC32=0f9d9977 +build.xml.script.CRC32=f902e8b8 +build.xml.stylesheet.CRC32=8064a381@1.75.2.48 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=55414227 +nbproject/build-impl.xml.script.CRC32=c12f9d04 +nbproject/build-impl.xml.stylesheet.CRC32=05530350@1.79.1.48 diff -r 64f6ae06310e -r eda408d4f253 jdk/make/netbeans/client_sanity/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/make/netbeans/client_sanity/nbproject/project.properties Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,79 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=SanityTests +application.vendor=akouznet +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# Files in build.classes.dir which should be excluded from distribution jar +dist.archive.excludes= +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/SanityTests.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes=*.cfg +includes=** +jar.compress=false +javac.classpath=\ + ${libs.testng.classpath} +# Space-separated list of extra javac options +javac.compilerargs=-Xmaxwarns 9999 -Xlint:all -Xlint:-serial +javac.deprecation=false +javac.external.vm=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.8 +javac.target=1.8 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +main.class= +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=false +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project. +# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. +# To set system properties for unit tests define test-sys-prop.name=value: +run.jvmargs=-ea +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.src.dir=..\\..\\..\\test\\sanity\\client\\SwingSet\\src +src.src2.dir=..\\..\\..\\test\\sanity\\client\\lib\\SwingSet3\\src +src.src3.dir=..\\..\\..\\test\\sanity\\client\\lib\\jemmy\\src +src.src4.dir=..\\..\\..\\test\\sanity\\client\\lib\\Jemmy2Ext\\src diff -r 64f6ae06310e -r eda408d4f253 jdk/make/netbeans/client_sanity/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/make/netbeans/client_sanity/nbproject/project.xml Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,17 @@ + + + org.netbeans.modules.java.j2seproject + + + SanityTests + + + + + + + + + + + diff -r 64f6ae06310e -r eda408d4f253 jdk/make/rmic/RmicCommon.gmk --- a/jdk/make/rmic/RmicCommon.gmk Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/make/rmic/RmicCommon.gmk Tue Apr 05 15:39:35 2016 -0400 @@ -31,7 +31,13 @@ ########################################################################################## -RMIC := $(JAVA) $(INTERIM_OVERRIDE_MODULES_ARGS) sun.rmi.rmic.Main +ifeq ($(BOOT_JDK_MODULAR), true) + RMIC_MAIN_CLASS := -m jdk.rmic/sun.rmi.rmic.Main +else + RMIC_MAIN_CLASS := sun.rmi.rmic.Main +endif + +RMIC := $(JAVA) $(INTERIM_OVERRIDE_MODULES_ARGS) $(RMIC_MAIN_CLASS) CLASSES_DIR := $(JDK_OUTPUTDIR)/modules # NOTE: If the smart javac dependency management is reintroduced, these classes risk diff -r 64f6ae06310e -r eda408d4f253 jdk/make/src/classes/build/tools/module/GenModuleInfoSource.java --- a/jdk/make/src/classes/build/tools/module/GenModuleInfoSource.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/make/src/classes/build/tools/module/GenModuleInfoSource.java Tue Apr 05 15:39:35 2016 -0400 @@ -25,25 +25,27 @@ package build.tools.module; import java.io.BufferedWriter; +import java.io.IOException; +import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; +import java.util.stream.Collectors; /** - * A build tool to extend the module-info.java in the source tree - * for platform-specific exports, uses, and provides and write - * to the specified output file. + * A build tool to extend the module-info.java in the source tree for + * platform-specific exports, uses, and provides and write to the specified + * output file. Injecting platform-specific requires is not supported. * - * GenModulesList build tool currently generates the modules.list from - * the module-info.java from the source tree that will be used for - * the make target and dependences. - * - * The build currently invokes gensrc-$MODULE.gmk after modules.list - * is generated. Hence, platform-specific requires is not supported. + * The extra exports, uses, provides can be specified in module-info.java.extra + * files and GenModuleInfoSource will be invoked for each module that has + * module-info.java.extra in the source directory. */ public class GenModuleInfoSource { private final static String USAGE = @@ -57,17 +59,32 @@ public static void main(String... args) throws Exception { Path outfile = null; Path moduleInfoJava = null; - Map> options = new HashMap<>(); + GenModuleInfoSource genModuleInfo = new GenModuleInfoSource(); // validate input arguments for (int i = 0; i < args.length; i++){ String option = args[i]; if (option.startsWith("-")) { String arg = args[++i]; - if (option.equals("-exports") || - option.equals("-uses") || - option.equals("-provides")) { - options.computeIfAbsent(option, _k -> new HashSet<>()).add(arg); + if (option.equals("-exports")) { + int index = arg.indexOf('/'); + if (index > 0) { + String pn = arg.substring(0, index); + String mn = arg.substring(index + 1, arg.length()); + genModuleInfo.exportTo(pn, mn); + } else { + genModuleInfo.export(arg); + } + } else if (option.equals("-uses")) { + genModuleInfo.use(arg); + } else if (option.equals("-provides")) { + int index = arg.indexOf('/'); + if (index <= 0) { + throw new IllegalArgumentException("invalid -provide argument: " + arg); + } + String service = arg.substring(0, index); + String impl = arg.substring(index + 1, arg.length()); + genModuleInfo.provide(service, impl); } else if (option.equals("-o")) { outfile = Paths.get(arg); } else { @@ -87,48 +104,145 @@ System.err.println(USAGE); System.exit(-1); } - // read module-info.java - Module.Builder builder = ModuleInfoReader.builder(moduleInfoJava); - augment(builder, options); // generate new module-info.java - Module module = builder.build(); + genModuleInfo.generate(moduleInfoJava, outfile); + } + + private final Set exports = new HashSet<>(); + private final Map> exportsTo = new HashMap<>(); + private final Set uses = new HashSet<>(); + private final Map> provides = new HashMap<>(); + GenModuleInfoSource() { + } + + private void export(String p) { + Objects.requireNonNull(p); + if (exports.contains(p) || exportsTo.containsKey(p)) { + throw new RuntimeException("duplicated exports: " + p); + } + exports.add(p); + } + private void exportTo(String p, String mn) { + Objects.requireNonNull(p); + Objects.requireNonNull(mn); + if (exports.contains(p)) { + throw new RuntimeException("unqualified exports already exists: " + p); + } + exportsTo.computeIfAbsent(p, _k -> new HashSet<>()).add(mn); + } + + private void use(String service) { + uses.add(service); + } + + private void provide(String s, String impl) { + provides.computeIfAbsent(s, _k -> new HashSet<>()).add(impl); + } + + private void generate(Path sourcefile, Path outfile) throws IOException { Path parent = outfile.getParent(); if (parent != null) Files.createDirectories(parent); - try (BufferedWriter writer = Files.newBufferedWriter(outfile)) { - writer.write(module.toString()); - } - } + List lines = Files.readAllLines(sourcefile); + try (BufferedWriter bw = Files.newBufferedWriter(outfile); + PrintWriter writer = new PrintWriter(bw)) { + int lineNumber = 0; + for (String l : lines) { + lineNumber++; + String[] s = l.trim().split("\\s+"); + String keyword = s[0].trim(); + int nextIndex = keyword.length(); + String exp = null; + int n = l.length(); + switch (keyword) { + case "exports": + boolean inExportsTo = false; + // assume package name immediately after exports + exp = s[1].trim(); + if (s.length >= 3) { + nextIndex = l.indexOf(exp, nextIndex) + exp.length(); + if (s[2].trim().equals("to")) { + inExportsTo = true; + n = l.indexOf("to", nextIndex) + "to".length(); + } else { + throw new RuntimeException(sourcefile + ", line " + + lineNumber + ", is malformed: " + s[2]); + } + } - private static void augment(Module.Builder builder, Map> options) { - for (String opt : options.keySet()) { - if (opt.equals("-exports")) { - for (String arg : options.get(opt)) { - int index = arg.indexOf('/'); - if (index > 0) { - String pn = arg.substring(0, index); - String mn = arg.substring(index + 1, arg.length()); - builder.exportTo(pn, mn); - } else { - builder.export(arg); - } - } - } else if (opt.equals("-uses")) { - options.get(opt).stream() - .forEach(builder::use); - } else if (opt.equals("-provides")) { - for (String arg : options.get(opt)) { - int index = arg.indexOf('/'); - if (index <= 0) { - throw new IllegalArgumentException("invalid -provide argument: " + arg); - } - String service = arg.substring(0, index); - String impl = arg.substring(index + 1, arg.length()); - builder.provide(service, impl); + // inject the extra targets after "to" + if (inExportsTo) { + writer.println(injectExportTargets(exp, l, n)); + } else { + writer.println(l); + } + break; + case "to": + if (exp == null) { + throw new RuntimeException(sourcefile + ", line " + + lineNumber + ", is malformed"); + } + n = l.indexOf("to", nextIndex) + "to".length(); + writer.println(injectExportTargets(exp, l, n)); + break; + case "}": + doAugments(writer); + // fall through + default: + writer.println(l); + // reset exports + exp = null; } } } } + + private String injectExportTargets(String pn, String exp, int pos) { + Set targets = exportsTo.remove(pn); + if (targets != null) { + StringBuilder sb = new StringBuilder(); + // inject the extra targets after the given pos + sb.append(exp.substring(0, pos)) + .append("\n\t") + .append(targets.stream() + .collect(Collectors.joining(",", "", ","))) + .append(" /* injected */"); + if (pos < exp.length()) { + // print the remaining statement followed "to" + sb.append("\n\t") + .append(exp.substring(pos+1, exp.length())); + } + return sb.toString(); + } else { + return exp; + } + } + + private void doAugments(PrintWriter writer) { + if ((exports.size() + exportsTo.size() + uses.size() + provides.size()) == 0) + return; + + writer.println(" // augmented from module-info.java.extra"); + exports.stream() + .sorted() + .forEach(e -> writer.format(" exports %s;%n", e)); + // remaining injected qualified exports + exportsTo.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .map(e -> String.format(" exports %s to%n%s;", e.getKey(), + e.getValue().stream().sorted() + .map(mn -> String.format(" %s", mn)) + .collect(Collectors.joining(",\n")))) + .forEach(writer::println); + uses.stream().sorted() + .forEach(s -> writer.format(" uses %s;%n", s)); + provides.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .flatMap(e -> e.getValue().stream().sorted() + .map(impl -> String.format(" provides %s with %s;", + e.getKey(), impl))) + .forEach(writer::println); + } } diff -r 64f6ae06310e -r eda408d4f253 jdk/make/src/classes/build/tools/module/Module.java --- a/jdk/make/src/classes/build/tools/module/Module.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,280 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package build.tools.module; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -public class Module { - public static class Dependence implements Comparable { - final String name; - final boolean reexport; - Dependence(String name) { - this(name, false); - } - Dependence(String name, boolean reexport) { - this.name = name; - this.reexport = reexport; - } - - public String name() { - return name; - } - - public boolean reexport(){ - return reexport; - } - - @Override - public int hashCode() { - int hash = 5; - hash = 11 * hash + Objects.hashCode(this.name); - hash = 11 * hash + (this.reexport ? 1 : 0); - return hash; - } - - public boolean equals(Object o) { - Dependence d = (Dependence)o; - return this.name.equals(d.name) && this.reexport == d.reexport; - } - - @Override - public int compareTo(Dependence o) { - int rc = this.name.compareTo(o.name); - return rc != 0 ? rc : Boolean.compare(this.reexport, o.reexport); - } - - @Override - public String toString() { - return String.format("requires %s%s;", - reexport ? "public " : "", name); - } - } - private final String moduleName; - private final Set requires; - private final Map> exports; - private final Set uses; - private final Map> provides; - - private Module(String name, - Set requires, - Map> exports, - Set uses, - Map> provides) { - this.moduleName = name; - this.requires = Collections.unmodifiableSet(requires); - this.exports = Collections.unmodifiableMap(exports); - this.uses = Collections.unmodifiableSet(uses); - this.provides = Collections.unmodifiableMap(provides); - } - - public String name() { - return moduleName; - } - - public Set requires() { - return requires; - } - - public Map> exports() { - return exports; - } - - public Set uses() { - return uses; - } - - public Map> provides() { - return provides; - } - - @Override - public boolean equals(Object ob) { - if (!(ob instanceof Module)) { - return false; - } - Module that = (Module) ob; - return (moduleName.equals(that.moduleName) - && requires.equals(that.requires) - && exports.equals(that.exports)); - } - - @Override - public int hashCode() { - int hc = moduleName.hashCode(); - hc = hc * 43 + requires.hashCode(); - hc = hc * 43 + exports.hashCode(); - return hc; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(String.format("module %s {%n", moduleName)); - requires.stream() - .sorted() - .map(d -> String.format(" requires %s%s;%n", d.reexport ? "public " : "", d.name)) - .forEach(sb::append); - exports.entrySet().stream() - .filter(e -> e.getValue().isEmpty()) - .sorted(Map.Entry.comparingByKey()) - .map(e -> String.format(" exports %s;%n", e.getKey())) - .forEach(sb::append); - exports.entrySet().stream() - .filter(e -> !e.getValue().isEmpty()) - .sorted(Map.Entry.comparingByKey()) - .map(e -> String.format(" exports %s to%n%s;%n", e.getKey(), - e.getValue().stream().sorted() - .map(mn -> String.format(" %s", mn)) - .collect(Collectors.joining(",\n")))) - .forEach(sb::append); - uses.stream().sorted() - .map(s -> String.format(" uses %s;%n", s)) - .forEach(sb::append); - provides.entrySet().stream() - .sorted(Map.Entry.comparingByKey()) - .flatMap(e -> e.getValue().stream().sorted() - .map(impl -> String.format(" provides %s with %s;%n", e.getKey(), impl))) - .forEach(sb::append); - sb.append("}").append("\n"); - return sb.toString(); - } - - /** - * Module Builder - */ - static class Builder { - private String name; - final Set requires = new HashSet<>(); - final Map> exports = new HashMap<>(); - final Set uses = new HashSet<>(); - final Map> provides = new HashMap<>(); - - public Builder() { - } - - public Builder name(String n) { - name = n; - return this; - } - - public Builder require(String d, boolean reexport) { - requires.add(new Dependence(d, reexport)); - return this; - } - - public Builder export(String p) { - Objects.requireNonNull(p); - if (exports.containsKey(p)) { - throw new RuntimeException(name + " already exports " + p + - " " + exports.get(p)); - } - return exportTo(p, Collections.emptySet()); - } - - public Builder exportTo(String p, String mn) { - Objects.requireNonNull(p); - Objects.requireNonNull(mn); - Set ms = exports.get(p); - if (ms != null && ms.isEmpty()) { - throw new RuntimeException(name + " already has unqualified exports " + p); - } - exports.computeIfAbsent(p, _k -> new HashSet<>()).add(mn); - return this; - } - - public Builder exportTo(String p, Set ms) { - Objects.requireNonNull(p); - Objects.requireNonNull(ms); - if (exports.containsKey(p)) { - throw new RuntimeException(name + " already exports " + p + - " " + exports.get(p)); - } - exports.put(p, new HashSet<>(ms)); - return this; - } - - public Builder use(String cn) { - uses.add(cn); - return this; - } - - public Builder provide(String s, String impl) { - provides.computeIfAbsent(s, _k -> new HashSet<>()).add(impl); - return this; - } - - public Builder merge(Module m1, Module m2) { - if (!m1.name().equals(m2.name())) { - throw new IllegalArgumentException(m1.name() + " != " + m2.name()); - } - name = m1.name(); - // ## reexports - requires.addAll(m1.requires()); - requires.addAll(m2.requires()); - Stream.concat(m1.exports().keySet().stream(), m2.exports().keySet().stream()) - .distinct() - .forEach(pn -> { - Set s1 = m2.exports().get(pn); - Set s2 = m2.exports().get(pn); - if (s1 == null || s2 == null) { - exportTo(pn, s1 != null ? s1 : s2); - } else if (s1.isEmpty() || s2.isEmpty()) { - // unqualified exports - export(pn); - } else { - exportTo(pn, Stream.concat(s1.stream(), s2.stream()) - .collect(Collectors.toSet())); - } - }); - uses.addAll(m1.uses()); - uses.addAll(m2.uses()); - m1.provides().keySet().stream() - .forEach(s -> m1.provides().get(s).stream() - .forEach(impl -> provide(s, impl))); - m2.provides().keySet().stream() - .forEach(s -> m2.provides().get(s).stream() - .forEach(impl -> provide(s, impl))); - return this; - } - - public Module build() { - Module m = new Module(name, requires, exports, uses, provides); - return m; - } - - @Override - public String toString() { - return name != null ? name : "Unknown"; - } - } -} diff -r 64f6ae06310e -r eda408d4f253 jdk/make/src/classes/build/tools/module/ModuleInfoReader.java --- a/jdk/make/src/classes/build/tools/module/ModuleInfoReader.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,357 +0,0 @@ -/* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package build.tools.module; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.function.Supplier; -import java.util.regex.Pattern; -import java.util.stream.Stream; - -import build.tools.module.Module.Builder; - -/** - * Source reader of module-info.java - */ -public class ModuleInfoReader { - private final Path sourcefile; - private final Builder builder; - private ModuleInfoReader(Path file) { - this.sourcefile = file; - this.builder = new Builder(); - } - - public static Builder builder(Path file) throws IOException { - ModuleInfoReader reader = new ModuleInfoReader(file); - reader.readFile(); - return reader.builder; - } - - /** - * Reads the source file. - */ - void readFile() throws IOException { - List lines = Files.readAllLines(sourcefile); - boolean done = false; - int lineNumber = 0; - boolean inBlockComment = false; - boolean inRequires = false; - boolean reexports = false; - boolean inProvides = false; - boolean inWith = false; - String serviceIntf = null; - String providerClass = null; - boolean inUses = false; - boolean inExports = false; - boolean inExportsTo = false; - String qualifiedExports = null; - Counter counter = new Counter(); - - for (String line : lines) { - lineNumber++; - if (inBlockComment) { - int c = line.indexOf("*/"); - if (c >= 0) { - line = line.substring(c + 2, line.length()); - inBlockComment = false; - } else { - // skip lines until end of comment block - continue; - } - } - inBlockComment = beginBlockComment(line); - - line = trimComment(line).trim(); - // ignore empty lines - if (line.length() == 0) { - continue; - } - String values; - if (inRequires || inExports | inUses | (inWith && providerClass == null)) { - values = line; - } else { - String[] s = line.split("\\s+"); - String keyword = s[0].trim(); - int nextIndex = keyword.length(); - switch (keyword) { - case "module": - if (s.length != 3 || !s[2].trim().equals("{")) { - throw new RuntimeException(sourcefile + ", line " + - lineNumber + ", is malformed"); - } - builder.name(s[1].trim()); - continue; // next line - case "requires": - inRequires = true; - counter.numRequires++; - if (s.length >= 2) { - String ss = s[1].trim(); - if (ss.equals("public")) { - nextIndex = line.indexOf(ss) + ss.length(); - reexports = true; - } - } - break; - case "exports": - inExports = true; - inExportsTo = false; - counter.numExports++; - qualifiedExports = null; - if (s.length >= 3) { - qualifiedExports = s[1].trim(); - nextIndex = line.indexOf(qualifiedExports, nextIndex) - + qualifiedExports.length(); - if (s[2].trim().equals("to")) { - inExportsTo = true; - nextIndex = line.indexOf("to", nextIndex) + "to".length(); - } else { - throw new RuntimeException(sourcefile + ", line " + - lineNumber + ", is malformed: " + s[2]); - } - } - break; - case "to": - if (!inExports || qualifiedExports == null) { - throw new RuntimeException(sourcefile + ", line " + - lineNumber + ", is malformed"); - } - inExportsTo = true; - break; - case "uses": - inUses = true; - counter.numUses++; - break; - case "provides": - inProvides = true; - inWith = false; - counter.numProvides++; - serviceIntf = null; - providerClass = null; - if (s.length >= 2) { - serviceIntf = s[1].trim(); - nextIndex = line.indexOf(serviceIntf) + serviceIntf.length(); - } - if (s.length >= 3) { - if (s[2].trim().equals("with")) { - inWith = true; - nextIndex = line.indexOf("with") + "with".length(); - } else { - throw new RuntimeException(sourcefile + ", line " + - lineNumber + ", is malformed: " + s[2]); - } - } - break; - case "with": - if (!inProvides || serviceIntf == null) { - throw new RuntimeException(sourcefile + ", line " + - lineNumber + ", is malformed"); - } - inWith = true; - nextIndex = line.indexOf("with") + "with".length(); - break; - case "}": - counter.validate(builder); - done = true; - continue; // next line - default: - throw new RuntimeException(sourcefile + ", \"" + - keyword + "\" on line " + - lineNumber + ", is not recognized"); - } - values = line.substring(nextIndex, line.length()).trim(); - } - - int len = values.length(); - if (len == 0) { - continue; // next line - } - char lastchar = values.charAt(len - 1); - if (lastchar != ',' && lastchar != ';') { - throw new RuntimeException(sourcefile + ", line " + - lineNumber + ", is malformed:" + - " ',' or ';' is missing."); - } - - values = values.substring(0, len - 1).trim(); - // parse the values specified for a keyword specified - for (String s : values.split(",")) { - s = s.trim(); - if (s.length() > 0) { - if (inRequires) { - if (builder.requires.contains(s)) { - throw new RuntimeException(sourcefile + ", line " - + lineNumber + " duplicated requires: \"" + s + "\""); - } - builder.require(s, reexports); - } else if (inExports) { - if (!inExportsTo && qualifiedExports == null) { - builder.export(s); - } else { - builder.exportTo(qualifiedExports, s); - } - } else if (inUses) { - builder.use(s); - } else if (inProvides) { - if (!inWith) { - serviceIntf = s; - } else { - providerClass = s; - builder.provide(serviceIntf, providerClass); - } - } - } - } - if (lastchar == ';') { - inRequires = false; - reexports = false; - inExports = false; - inExportsTo = false; - inProvides = false; - inWith = false; - inUses = false; - } - } - - if (inBlockComment) { - throw new RuntimeException(sourcefile + ", line " + - lineNumber + ", missing \"*/\" to end a block comment"); - } - if (!done) { - throw new RuntimeException(sourcefile + ", line " + - lineNumber + ", missing \"}\" to end module definition" + - " for \"" + builder + "\""); - } - return; - } - - // the naming convention for the module names without dashes - private static final Pattern CLASS_NAME_PATTERN = Pattern.compile("[\\w\\.\\*_$/]+"); - private static boolean beginBlockComment(String line) { - int pos = 0; - while (pos >= 0 && pos < line.length()) { - int c = line.indexOf("/*", pos); - if (c < 0) { - return false; - } - - if (c > 0 && !Character.isWhitespace(line.charAt(c - 1))) { - return false; - } - - int c1 = line.indexOf("//", pos); - if (c1 >= 0 && c1 < c) { - return false; - } - - int c2 = line.indexOf("*/", c + 2); - if (c2 < 0) { - return true; - } - pos = c + 2; - } - return false; - } - private static String trimComment(String line) { - StringBuilder sb = new StringBuilder(); - - int pos = 0; - while (pos >= 0 && pos < line.length()) { - int c1 = line.indexOf("//", pos); - if (c1 > 0 && !Character.isWhitespace(line.charAt(c1 - 1))) { - // not a comment - c1 = -1; - } - - int c2 = line.indexOf("/*", pos); - if (c2 > 0 && !Character.isWhitespace(line.charAt(c2 - 1))) { - // not a comment - c2 = -1; - } - - int c = line.length(); - int n = line.length(); - if (c1 >= 0 || c2 >= 0) { - if (c1 >= 0) { - c = c1; - } - if (c2 >= 0 && c2 < c) { - c = c2; - } - int c3 = line.indexOf("*/", c2 + 2); - if (c == c2 && c3 > c2) { - n = c3 + 2; - } - } - if (c > 0) { - if (sb.length() > 0) { - // add a whitespace if multiple comments on one line - sb.append(" "); - } - sb.append(line.substring(pos, c)); - } - pos = n; - } - return sb.toString(); - } - - - static class Counter { - int numRequires; - int numExports; - int numUses; - int numProvides; - - void validate(Builder builder) { - assertEquals("requires", numRequires, builder.requires.size(), - () -> builder.requires.stream() - .map(Module.Dependence::toString)); - assertEquals("exports", numExports, builder.exports.size(), - () -> builder.exports.entrySet().stream() - .map(e -> "exports " + e.getKey() + " to " + e.getValue())); - assertEquals("uses", numUses, builder.uses.size(), - () -> builder.uses.stream()); - assertEquals("provides", numProvides, - (int)builder.provides.values().stream() - .flatMap(s -> s.stream()) - .count(), - () -> builder.provides.entrySet().stream() - .map(e -> "provides " + e.getKey() + " with " + e.getValue())); - } - - private static void assertEquals(String msg, int expected, int got, - Supplier> supplier) { - if (expected != got){ - System.err.println("ERROR: mismatched " + msg + - " expected: " + expected + " got: " + got ); - supplier.get().sorted() - .forEach(System.err::println); - throw new AssertionError("mismatched " + msg + - " expected: " + expected + " got: " + got + " "); - } - } - } -} diff -r 64f6ae06310e -r eda408d4f253 jdk/make/src/classes/build/tools/module/ModulesXmlReader.java --- a/jdk/make/src/classes/build/tools/module/ModulesXmlReader.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package build.tools.module; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLEventReader; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.events.Attribute; -import javax.xml.stream.events.XMLEvent; -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.HashSet; -import java.util.Set; - -public class ModulesXmlReader { - - private ModulesXmlReader() {} - - public static Set readModules(Path modulesXml) - throws XMLStreamException, IOException - { - Set modules = new HashSet<>(); - try (InputStream in = new BufferedInputStream(Files.newInputStream(modulesXml))) { - Set mods = ModulesXmlReader.load(in); - modules.addAll(mods); - } - return modules; - } - - private static final String MODULES = "modules"; - private static final String MODULE = "module"; - private static final String NAME = "name"; - private static final String DEPEND = "depend"; - private static final String EXPORT = "export"; - private static final String TO = "to"; - private static final QName REEXPORTS = new QName("re-exports"); - private static Set load(InputStream in) - throws XMLStreamException, IOException - { - Set modules = new HashSet<>(); - XMLInputFactory factory = XMLInputFactory.newInstance(); - XMLEventReader stream = factory.createXMLEventReader(in); - Module.Builder mb = null; - String modulename = null; - String pkg = null; - Set permits = new HashSet<>(); - while (stream.hasNext()) { - XMLEvent event = stream.nextEvent(); - if (event.isStartElement()) { - String startTag = event.asStartElement().getName().getLocalPart(); - switch (startTag) { - case MODULES: - break; - case MODULE: - if (mb != null) { - throw new RuntimeException("end tag for module is missing"); - } - modulename = getNextTag(stream, NAME); - mb = new Module.Builder(); - mb.name(modulename); - break; - case NAME: - throw new RuntimeException(event.toString()); - case DEPEND: - boolean reexports = false; - Attribute attr = event.asStartElement().getAttributeByName(REEXPORTS); - if (attr != null) { - String value = attr.getValue(); - if (value.equals("true") || value.equals("false")) { - reexports = Boolean.parseBoolean(value); - } else { - throw new RuntimeException("unexpected attribute " + attr.toString()); - } - } - mb.require(getData(stream), reexports); - break; - case EXPORT: - pkg = getNextTag(stream, NAME); - break; - case TO: - permits.add(getData(stream)); - break; - default: - } - } else if (event.isEndElement()) { - String endTag = event.asEndElement().getName().getLocalPart(); - switch (endTag) { - case MODULE: - modules.add(mb.build()); - mb = null; - break; - case EXPORT: - if (pkg == null) { - throw new RuntimeException("export-to is malformed"); - } - mb.exportTo(pkg, permits); - pkg = null; - permits.clear(); - break; - default: - } - } else if (event.isCharacters()) { - String s = event.asCharacters().getData(); - if (!s.trim().isEmpty()) { - throw new RuntimeException("export-to is malformed"); - } - } - } - return modules; - } - - private static String getData(XMLEventReader reader) - throws XMLStreamException - { - XMLEvent e = reader.nextEvent(); - if (e.isCharacters()) - return e.asCharacters().getData(); - - throw new RuntimeException(e.toString()); - } - - private static String getNextTag(XMLEventReader reader, String tag) - throws XMLStreamException - { - XMLEvent e = reader.nextTag(); - if (e.isStartElement()) { - String t = e.asStartElement().getName().getLocalPart(); - if (!tag.equals(t)) { - throw new RuntimeException(e + " expected: " + tag); - } - return getData(reader); - } - throw new RuntimeException("export-to name is missing:" + e); - } -} diff -r 64f6ae06310e -r eda408d4f253 jdk/make/src/classes/build/tools/module/ModulesXmlWriter.java --- a/jdk/make/src/classes/build/tools/module/ModulesXmlWriter.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,176 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package build.tools.module; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLOutputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Collections; -import java.util.Comparator; -import java.util.Map; -import java.util.Set; - -public final class ModulesXmlWriter { - - private ModulesXmlWriter() {} - - public static void writeModules(Set modules, Path path) - throws IOException, XMLStreamException - { - writeXML(modules, path); - } - - private static final String MODULES = "modules"; - private static final String MODULE = "module"; - private static final String NAME = "name"; - private static final String DEPEND = "depend"; - private static final String EXPORT = "export"; - private static final String TO = "to"; - private static final QName REEXPORTS = new QName("re-exports"); - - private static void writeXML(Set modules, Path path) - throws IOException, XMLStreamException - { - XMLOutputFactory xof = XMLOutputFactory.newInstance(); - try (OutputStream out = Files.newOutputStream(path)) { - int depth = 0; - XMLStreamWriter xtw = xof.createXMLStreamWriter(out, "UTF-8"); - xtw.writeStartDocument("utf-8","1.0"); - writeStartElement(xtw, MODULES, depth); - modules.stream() - .sorted(Comparator.comparing(Module::name)) - .forEach(m -> writeModuleElement(xtw, m, depth+1)); - writeEndElement(xtw, depth); - xtw.writeCharacters("\n"); - xtw.writeEndDocument(); - xtw.flush(); - xtw.close(); - } - } - - private static void writeElement(XMLStreamWriter xtw, - String element, - String value, - int depth) { - try { - writeStartElement(xtw, element, depth); - xtw.writeCharacters(value); - xtw.writeEndElement(); - } catch (XMLStreamException e) { - throw new RuntimeException(e); - } - } - - private static void writeDependElement(XMLStreamWriter xtw, - Module.Dependence d, - int depth) { - try { - writeStartElement(xtw, DEPEND, depth); - if (d.reexport) { - xtw.writeAttribute("re-exports", "true"); - } - xtw.writeCharacters(d.name); - xtw.writeEndElement(); - } catch (XMLStreamException e) { - throw new RuntimeException(e); - } - } - - private static void writeExportElement(XMLStreamWriter xtw, - String pkg, - int depth) { - writeExportElement(xtw, pkg, Collections.emptySet(), depth); - } - - private static void writeExportElement(XMLStreamWriter xtw, - String pkg, - Set permits, - int depth) { - try { - writeStartElement(xtw, EXPORT, depth); - writeElement(xtw, NAME, pkg, depth+1); - if (!permits.isEmpty()) { - permits.stream().sorted() - .forEach(m -> writeElement(xtw, TO, m, depth + 1)); - } - writeEndElement(xtw, depth); - } catch (XMLStreamException e) { - throw new RuntimeException(e); - } - } - private static void writeModuleElement(XMLStreamWriter xtw, - Module m, - int depth) { - try { - writeStartElement(xtw, MODULE, depth); - writeElement(xtw, NAME, m.name(), depth+1); - m.requires().stream().sorted(Comparator.comparing(d -> d.name)) - .forEach(d -> writeDependElement(xtw, d, depth+1)); - m.exports().keySet().stream() - .filter(pn -> m.exports().get(pn).isEmpty()) - .sorted() - .forEach(pn -> writeExportElement(xtw, pn, depth+1)); - m.exports().entrySet().stream() - .filter(e -> !e.getValue().isEmpty()) - .sorted(Map.Entry.comparingByKey()) - .forEach(e -> writeExportElement(xtw, e.getKey(), e.getValue(), depth+1)); - writeEndElement(xtw, depth); - } catch (XMLStreamException e) { - throw new RuntimeException(e); - - } - } - - /** Two spaces; the default indentation. */ - public static final String DEFAULT_INDENT = " "; - - /** stack[depth] indicates what's been written into the current scope. */ - private static String[] stack = new String[] { "\n", - "\n" + DEFAULT_INDENT, - "\n" + DEFAULT_INDENT + DEFAULT_INDENT, - "\n" + DEFAULT_INDENT + DEFAULT_INDENT + DEFAULT_INDENT}; - - private static void writeStartElement(XMLStreamWriter xtw, - String name, - int depth) - throws XMLStreamException - { - xtw.writeCharacters(stack[depth]); - xtw.writeStartElement(name); - } - - private static void writeEndElement(XMLStreamWriter xtw, int depth) - throws XMLStreamException - { - xtw.writeCharacters(stack[depth]); - xtw.writeEndElement(); - } -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/java/lang/invoke/BoundMethodHandle.java --- a/jdk/src/java.base/share/classes/java/lang/invoke/BoundMethodHandle.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/java.base/share/classes/java/lang/invoke/BoundMethodHandle.java Tue Apr 05 15:39:35 2016 -0400 @@ -25,6 +25,7 @@ package java.lang.invoke; +import jdk.internal.loader.BootLoader; import jdk.internal.vm.annotation.Stable; import jdk.internal.org.objectweb.asm.ClassWriter; import jdk.internal.org.objectweb.asm.FieldVisitor; @@ -36,6 +37,7 @@ import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.Field; import java.util.Arrays; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; @@ -463,6 +465,7 @@ static final String SPECIES_PREFIX_NAME = "Species_"; static final String SPECIES_PREFIX_PATH = BMH + "$" + SPECIES_PREFIX_NAME; + static final String SPECIES_CLASS_PREFIX = SPECIES_PREFIX_PATH.replace('/', '.'); static final String BMHSPECIES_DATA_EWI_SIG = "(B)" + SPECIES_DATA_SIG; static final String BMHSPECIES_DATA_GFC_SIG = "(" + JLS_SIG + JLC_SIG + ")" + SPECIES_DATA_SIG; @@ -489,7 +492,15 @@ types, new Function>() { @Override public Class apply(String types) { - return generateConcreteBMHClass(types); + String shortTypes = LambdaForm.shortenSignature(types); + String className = SPECIES_CLASS_PREFIX + shortTypes; + Class c = BootLoader.loadClassOrNull(className); + if (c != null) { + return c.asSubclass(BoundMethodHandle.class); + } else { + // Not pregenerated, generate the class + return generateConcreteBMHClass(shortTypes, types); + } } }); } @@ -558,12 +569,49 @@ * @param types the type signature, wherein reference types are erased to 'L' * @return the generated concrete BMH class */ - static Class generateConcreteBMHClass(String types) { - final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); + static Class generateConcreteBMHClass(String shortTypes, + String types) { + final String className = speciesInternalClassName(shortTypes); + byte[] classFile = generateConcreteBMHClassBytes(shortTypes, types, className); + + // load class + InvokerBytecodeGenerator.maybeDump(className, classFile); + Class bmhClass = + UNSAFE.defineClass(className, classFile, 0, classFile.length, + BoundMethodHandle.class.getClassLoader(), null) + .asSubclass(BoundMethodHandle.class); + + return bmhClass; + } + /** + * @implNote this method is used by GenerateBMHClassesPlugin to enable + * ahead-of-time generation of BMH classes at link time. It does + * added validation since this string may be user provided. + */ + static Map.Entry generateConcreteBMHClassBytes( + final String types) { + for (char c : types.toCharArray()) { + if ("LIJFD".indexOf(c) < 0) { + throw new IllegalArgumentException("All characters must " + + "correspond to a basic field type: LIJFD"); + } + } String shortTypes = LambdaForm.shortenSignature(types); - final String className = SPECIES_PREFIX_PATH + shortTypes; + final String className = speciesInternalClassName(shortTypes); + return Map.entry(className, + generateConcreteBMHClassBytes(shortTypes, types, className)); + } + + private static String speciesInternalClassName(String shortTypes) { + return SPECIES_PREFIX_PATH + shortTypes; + } + + static byte[] generateConcreteBMHClassBytes(final String shortTypes, + final String types, final String className) { final String sourceFile = SPECIES_PREFIX_NAME + shortTypes; + + final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); final int NOT_ACC_PUBLIC = 0; // not ACC_PUBLIC cw.visit(V1_6, NOT_ACC_PUBLIC + ACC_FINAL + ACC_SUPER, className, null, BMH, null); cw.visitSource(sourceFile, null); @@ -699,16 +747,7 @@ cw.visitEnd(); - // load class - final byte[] classFile = cw.toByteArray(); - InvokerBytecodeGenerator.maybeDump(className, classFile); - Class bmhClass = - //UNSAFE.defineAnonymousClass(BoundMethodHandle.class, classFile, null).asSubclass(BoundMethodHandle.class); - UNSAFE.defineClass(className, classFile, 0, classFile.length, - BoundMethodHandle.class.getClassLoader(), null) - .asSubclass(BoundMethodHandle.class); - - return bmhClass; + return cw.toByteArray(); } private static int typeLoadOp(char t) { diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java --- a/jdk/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/java.base/share/classes/java/lang/invoke/StringConcatFactory.java Tue Apr 05 15:39:35 2016 -0400 @@ -255,7 +255,6 @@ */ private static final class Recipe { private final List elements; - private final List elementsRev; public Recipe(String src, Object[] constants) { List el = new ArrayList<>(); @@ -294,19 +293,13 @@ el.add(new RecipeElement(acc.toString())); } - elements = new ArrayList<>(el); - Collections.reverse(el); - elementsRev = el; + elements = el; } - public Collection getElements() { + public List getElements() { return elements; } - public Collection getElementsReversed() { - return elementsRev; - } - @Override public boolean equals(Object o) { if (this == o) return true; @@ -1310,7 +1303,9 @@ // Compose append calls. This is done in reverse because the application order is // reverse as well. - for (RecipeElement el : recipe.getElementsReversed()) { + List elements = recipe.getElements(); + for (int i = elements.size() - 1; i >= 0; i--) { + RecipeElement el = elements.get(i); MethodHandle appender; switch (el.getTag()) { case CONST: { diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/java/util/AbstractList.java --- a/jdk/src/java.base/share/classes/java/util/AbstractList.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/java.base/share/classes/java/util/AbstractList.java Tue Apr 05 15:39:35 2016 -0400 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -462,10 +462,9 @@ * @implSpec * This implementation returns a list that subclasses * {@code AbstractList}. The subclass stores, in private fields, the - * offset of the subList within the backing list, the size of the subList - * (which can change over its lifetime), and the expected - * {@code modCount} value of the backing list. There are two variants - * of the subclass, one of which implements {@code RandomAccess}. + * size of the subList (which can change over its lifetime), and the + * expected {@code modCount} value of the backing list. There are two + * variants of the subclass, one of which implements {@code RandomAccess}. * If this list implements {@code RandomAccess} the returned list will * be an instance of the subclass that implements {@code RandomAccess}. * @@ -493,11 +492,22 @@ * {@code (fromIndex > toIndex)} */ public List subList(int fromIndex, int toIndex) { + subListRangeCheck(fromIndex, toIndex, size()); return (this instanceof RandomAccess ? new RandomAccessSubList<>(this, fromIndex, toIndex) : new SubList<>(this, fromIndex, toIndex)); } + static void subListRangeCheck(int fromIndex, int toIndex, int size) { + if (fromIndex < 0) + throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); + if (toIndex > size) + throw new IndexOutOfBoundsException("toIndex = " + toIndex); + if (fromIndex > toIndex) + throw new IllegalArgumentException("fromIndex(" + fromIndex + + ") > toIndex(" + toIndex + ")"); + } + // Comparison and hashing /** @@ -623,174 +633,199 @@ private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size(); } -} + + private static class SubList extends AbstractList { + private final AbstractList root; + private final SubList parent; + private final int offset; + protected int size; -class SubList extends AbstractList { - private final AbstractList l; - private final int offset; - private int size; + /** + * Constructs a sublist of an arbitrary AbstractList, which is + * not a SubList itself. + */ + public SubList(AbstractList root, int fromIndex, int toIndex) { + this.root = root; + this.parent = null; + this.offset = fromIndex; + this.size = toIndex - fromIndex; + this.modCount = root.modCount; + } + + /** + * Constructs a sublist of another SubList. + */ + protected SubList(SubList parent, int fromIndex, int toIndex) { + this.root = parent.root; + this.parent = parent; + this.offset = parent.offset + fromIndex; + this.size = toIndex - fromIndex; + this.modCount = root.modCount; + } + + public E set(int index, E element) { + Objects.checkIndex(index, size); + checkForComodification(); + return root.set(offset + index, element); + } - SubList(AbstractList list, int fromIndex, int toIndex) { - if (fromIndex < 0) - throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); - if (toIndex > list.size()) - throw new IndexOutOfBoundsException("toIndex = " + toIndex); - if (fromIndex > toIndex) - throw new IllegalArgumentException("fromIndex(" + fromIndex + - ") > toIndex(" + toIndex + ")"); - l = list; - offset = fromIndex; - size = toIndex - fromIndex; - this.modCount = l.modCount; - } + public E get(int index) { + Objects.checkIndex(index, size); + checkForComodification(); + return root.get(offset + index); + } + + public int size() { + checkForComodification(); + return size; + } + + public void add(int index, E element) { + rangeCheckForAdd(index); + checkForComodification(); + root.add(offset + index, element); + updateSizeAndModCount(1); + } - public E set(int index, E element) { - rangeCheck(index); - checkForComodification(); - return l.set(index+offset, element); - } + public E remove(int index) { + Objects.checkIndex(index, size); + checkForComodification(); + E result = root.remove(offset + index); + updateSizeAndModCount(-1); + return result; + } + + protected void removeRange(int fromIndex, int toIndex) { + checkForComodification(); + root.removeRange(offset + fromIndex, offset + toIndex); + updateSizeAndModCount(fromIndex - toIndex); + } - public E get(int index) { - rangeCheck(index); - checkForComodification(); - return l.get(index+offset); - } + public boolean addAll(Collection c) { + return addAll(size, c); + } - public int size() { - checkForComodification(); - return size; - } + public boolean addAll(int index, Collection c) { + rangeCheckForAdd(index); + int cSize = c.size(); + if (cSize==0) + return false; + checkForComodification(); + root.addAll(offset + index, c); + updateSizeAndModCount(cSize); + return true; + } - public void add(int index, E element) { - rangeCheckForAdd(index); - checkForComodification(); - l.add(index+offset, element); - this.modCount = l.modCount; - size++; - } + public Iterator iterator() { + return listIterator(); + } + + public ListIterator listIterator(int index) { + checkForComodification(); + rangeCheckForAdd(index); + + return new ListIterator() { + private final ListIterator i = + root.listIterator(offset + index); + + public boolean hasNext() { + return nextIndex() < size; + } - public E remove(int index) { - rangeCheck(index); - checkForComodification(); - E result = l.remove(index+offset); - this.modCount = l.modCount; - size--; - return result; - } + public E next() { + if (hasNext()) + return i.next(); + else + throw new NoSuchElementException(); + } + + public boolean hasPrevious() { + return previousIndex() >= 0; + } + + public E previous() { + if (hasPrevious()) + return i.previous(); + else + throw new NoSuchElementException(); + } + + public int nextIndex() { + return i.nextIndex() - offset; + } + + public int previousIndex() { + return i.previousIndex() - offset; + } - protected void removeRange(int fromIndex, int toIndex) { - checkForComodification(); - l.removeRange(fromIndex+offset, toIndex+offset); - this.modCount = l.modCount; - size -= (toIndex-fromIndex); - } + public void remove() { + i.remove(); + updateSizeAndModCount(-1); + } + + public void set(E e) { + i.set(e); + } - public boolean addAll(Collection c) { - return addAll(size, c); - } + public void add(E e) { + i.add(e); + updateSizeAndModCount(1); + } + }; + } + + public List subList(int fromIndex, int toIndex) { + subListRangeCheck(fromIndex, toIndex, size); + return new SubList<>(this, fromIndex, toIndex); + } - public boolean addAll(int index, Collection c) { - rangeCheckForAdd(index); - int cSize = c.size(); - if (cSize==0) - return false; + private void rangeCheckForAdd(int index) { + if (index < 0 || index > size) + throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); + } + + private String outOfBoundsMsg(int index) { + return "Index: "+index+", Size: "+size; + } - checkForComodification(); - l.addAll(offset+index, c); - this.modCount = l.modCount; - size += cSize; - return true; - } + private void checkForComodification() { + if (root.modCount != this.modCount) + throw new ConcurrentModificationException(); + } - public Iterator iterator() { - return listIterator(); + private void updateSizeAndModCount(int sizeChange) { + SubList slist = this; + do { + slist.size += sizeChange; + slist.modCount = root.modCount; + slist = slist.parent; + } while (slist != null); + } } - public ListIterator listIterator(final int index) { - checkForComodification(); - rangeCheckForAdd(index); - - return new ListIterator() { - private final ListIterator i = l.listIterator(index+offset); - - public boolean hasNext() { - return nextIndex() < size; - } - - public E next() { - if (hasNext()) - return i.next(); - else - throw new NoSuchElementException(); - } + private static class RandomAccessSubList + extends SubList implements RandomAccess { - public boolean hasPrevious() { - return previousIndex() >= 0; - } - - public E previous() { - if (hasPrevious()) - return i.previous(); - else - throw new NoSuchElementException(); - } - - public int nextIndex() { - return i.nextIndex() - offset; - } - - public int previousIndex() { - return i.previousIndex() - offset; - } + /** + * Constructs a sublist of an arbitrary AbstractList, which is + * not a RandomAccessSubList itself. + */ + RandomAccessSubList(AbstractList root, + int fromIndex, int toIndex) { + super(root, fromIndex, toIndex); + } - public void remove() { - i.remove(); - SubList.this.modCount = l.modCount; - size--; - } - - public void set(E e) { - i.set(e); - } - - public void add(E e) { - i.add(e); - SubList.this.modCount = l.modCount; - size++; - } - }; - } + /** + * Constructs a sublist of another RandomAccessSubList. + */ + RandomAccessSubList(RandomAccessSubList parent, + int fromIndex, int toIndex) { + super(parent, fromIndex, toIndex); + } - public List subList(int fromIndex, int toIndex) { - return new SubList<>(this, fromIndex, toIndex); - } - - private void rangeCheck(int index) { - if (index < 0 || index >= size) - throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); - } - - private void rangeCheckForAdd(int index) { - if (index < 0 || index > size) - throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); - } - - private String outOfBoundsMsg(int index) { - return "Index: "+index+", Size: "+size; - } - - private void checkForComodification() { - if (this.modCount != l.modCount) - throw new ConcurrentModificationException(); + public List subList(int fromIndex, int toIndex) { + subListRangeCheck(fromIndex, toIndex, size); + return new RandomAccessSubList<>(this, fromIndex, toIndex); + } } } - -class RandomAccessSubList extends SubList implements RandomAccess { - RandomAccessSubList(AbstractList list, int fromIndex, int toIndex) { - super(list, fromIndex, toIndex); - } - - public List subList(int fromIndex, int toIndex) { - return new RandomAccessSubList<>(this, fromIndex, toIndex); - } -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/java/util/ArrayList.java --- a/jdk/src/java.base/share/classes/java/util/ArrayList.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/java.base/share/classes/java/util/ArrayList.java Tue Apr 05 15:39:35 2016 -0400 @@ -432,8 +432,7 @@ * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { - rangeCheck(index); - + Objects.checkIndex(index, size); return elementData(index); } @@ -447,8 +446,7 @@ * @throws IndexOutOfBoundsException {@inheritDoc} */ public E set(int index, E element) { - rangeCheck(index); - + Objects.checkIndex(index, size); E oldValue = elementData(index); elementData[index] = element; return oldValue; @@ -511,7 +509,7 @@ * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { - rangeCheck(index); + Objects.checkIndex(index, size); modCount++; E oldValue = elementData(index); @@ -680,17 +678,6 @@ } /** - * Checks if the given index is in range. If not, throws an appropriate - * runtime exception. This method does *not* check if the index is - * negative: It is always used immediately prior to an array access, - * which throws an ArrayIndexOutOfBoundsException if index is negative. - */ - private void rangeCheck(int index) { - if (index >= size) - throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); - } - - /** * A version of rangeCheck used by add and addAll. */ private void rangeCheckForAdd(int index) { @@ -854,8 +841,7 @@ * @throws IndexOutOfBoundsException {@inheritDoc} */ public ListIterator listIterator(int index) { - if (index < 0 || index > size) - throw new IndexOutOfBoundsException("Index: "+index); + rangeCheckForAdd(index); return new ListItr(index); } @@ -1042,76 +1028,75 @@ */ public List subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); - return new SubList(this, 0, fromIndex, toIndex); - } - - static void subListRangeCheck(int fromIndex, int toIndex, int size) { - if (fromIndex < 0) - throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); - if (toIndex > size) - throw new IndexOutOfBoundsException("toIndex = " + toIndex); - if (fromIndex > toIndex) - throw new IllegalArgumentException("fromIndex(" + fromIndex + - ") > toIndex(" + toIndex + ")"); + return new SubList<>(this, fromIndex, toIndex); } - private class SubList extends AbstractList implements RandomAccess { - private final AbstractList parent; - private final int parentOffset; + private static class SubList extends AbstractList implements RandomAccess { + private final ArrayList root; + private final SubList parent; private final int offset; - int size; + private int size; - SubList(AbstractList parent, - int offset, int fromIndex, int toIndex) { - this.parent = parent; - this.parentOffset = fromIndex; - this.offset = offset + fromIndex; + /** + * Constructs a sublist of an arbitrary ArrayList. + */ + public SubList(ArrayList root, int fromIndex, int toIndex) { + this.root = root; + this.parent = null; + this.offset = fromIndex; this.size = toIndex - fromIndex; - this.modCount = ArrayList.this.modCount; + this.modCount = root.modCount; } - public E set(int index, E e) { - rangeCheck(index); + /** + * Constructs a sublist of another SubList. + */ + private SubList(SubList parent, int fromIndex, int toIndex) { + this.root = parent.root; + this.parent = parent; + this.offset = parent.offset + fromIndex; + this.size = toIndex - fromIndex; + this.modCount = root.modCount; + } + + public E set(int index, E element) { + Objects.checkIndex(index, size); checkForComodification(); - E oldValue = ArrayList.this.elementData(offset + index); - ArrayList.this.elementData[offset + index] = e; + E oldValue = root.elementData(offset + index); + root.elementData[offset + index] = element; return oldValue; } public E get(int index) { - rangeCheck(index); + Objects.checkIndex(index, size); checkForComodification(); - return ArrayList.this.elementData(offset + index); + return root.elementData(offset + index); } public int size() { checkForComodification(); - return this.size; + return size; } - public void add(int index, E e) { + public void add(int index, E element) { rangeCheckForAdd(index); checkForComodification(); - parent.add(parentOffset + index, e); - this.modCount = parent.modCount; - this.size++; + root.add(offset + index, element); + updateSizeAndModCount(1); } public E remove(int index) { - rangeCheck(index); + Objects.checkIndex(index, size); checkForComodification(); - E result = parent.remove(parentOffset + index); - this.modCount = parent.modCount; - this.size--; + E result = root.remove(offset + index); + updateSizeAndModCount(-1); return result; } protected void removeRange(int fromIndex, int toIndex) { checkForComodification(); - parent.removeRange(parentOffset + fromIndex, - parentOffset + toIndex); - this.modCount = parent.modCount; - this.size -= toIndex - fromIndex; + root.removeRange(offset + fromIndex, offset + toIndex); + updateSizeAndModCount(fromIndex - toIndex); } public boolean addAll(Collection c) { @@ -1123,11 +1108,9 @@ int cSize = c.size(); if (cSize==0) return false; - checkForComodification(); - parent.addAll(parentOffset + index, c); - this.modCount = parent.modCount; - this.size += cSize; + root.addAll(offset + index, c); + updateSizeAndModCount(cSize); return true; } @@ -1135,15 +1118,14 @@ return listIterator(); } - public ListIterator listIterator(final int index) { + public ListIterator listIterator(int index) { checkForComodification(); rangeCheckForAdd(index); - final int offset = this.offset; return new ListIterator() { int cursor = index; int lastRet = -1; - int expectedModCount = ArrayList.this.modCount; + int expectedModCount = root.modCount; public boolean hasNext() { return cursor != SubList.this.size; @@ -1155,7 +1137,7 @@ int i = cursor; if (i >= SubList.this.size) throw new NoSuchElementException(); - Object[] elementData = ArrayList.this.elementData; + Object[] elementData = root.elementData; if (offset + i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; @@ -1172,7 +1154,7 @@ int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); - Object[] elementData = ArrayList.this.elementData; + Object[] elementData = root.elementData; if (offset + i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; @@ -1187,7 +1169,7 @@ if (i >= size) { return; } - final Object[] elementData = ArrayList.this.elementData; + final Object[] elementData = root.elementData; if (offset + i >= elementData.length) { throw new ConcurrentModificationException(); } @@ -1216,7 +1198,7 @@ SubList.this.remove(lastRet); cursor = lastRet; lastRet = -1; - expectedModCount = ArrayList.this.modCount; + expectedModCount = root.modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } @@ -1228,7 +1210,7 @@ checkForComodification(); try { - ArrayList.this.set(offset + lastRet, e); + root.set(offset + lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } @@ -1242,14 +1224,14 @@ SubList.this.add(i, e); cursor = i + 1; lastRet = -1; - expectedModCount = ArrayList.this.modCount; + expectedModCount = root.modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final void checkForComodification() { - if (expectedModCount != ArrayList.this.modCount) + if (root.modCount != expectedModCount) throw new ConcurrentModificationException(); } }; @@ -1257,12 +1239,7 @@ public List subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); - return new SubList(this, offset, fromIndex, toIndex); - } - - private void rangeCheck(int index) { - if (index < 0 || index >= this.size) - throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); + return new SubList<>(this, fromIndex, toIndex); } private void rangeCheckForAdd(int index) { @@ -1275,13 +1252,24 @@ } private void checkForComodification() { - if (ArrayList.this.modCount != this.modCount) + if (root.modCount != modCount) throw new ConcurrentModificationException(); } + private void updateSizeAndModCount(int sizeChange) { + SubList slist = this; + do { + slist.size += sizeChange; + slist.modCount = root.modCount; + slist = slist.parent; + } while (slist != null); + } + public Spliterator spliterator() { checkForComodification(); + // ArrayListSpliterator is not used because late-binding logic + // is different here return new Spliterator<>() { private int index = offset; // current index, modified on advance/split private int fence = -1; // -1 until used; then one past last index @@ -1298,8 +1286,9 @@ public ArrayListSpliterator trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; + // ArrayListSpliterator could be used here as the source is already bound return (lo >= mid) ? null : // divide range in half unless too small - new ArrayListSpliterator<>(ArrayList.this, lo, index = mid, + new ArrayListSpliterator<>(root, lo, index = mid, expectedModCount); } @@ -1308,9 +1297,9 @@ int hi = getFence(), i = index; if (i < hi) { index = i + 1; - @SuppressWarnings("unchecked") E e = (E)elementData[i]; + @SuppressWarnings("unchecked") E e = (E)root.elementData[i]; action.accept(e); - if (ArrayList.this.modCount != expectedModCount) + if (root.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } @@ -1320,7 +1309,7 @@ public void forEachRemaining(Consumer action) { Objects.requireNonNull(action); int i, hi, mc; // hoist accesses and checks from loop - ArrayList lst = ArrayList.this; + ArrayList lst = root; Object[] a; if ((a = lst.elementData) != null) { if ((hi = fence) < 0) { diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/java/util/GregorianCalendar.java --- a/jdk/src/java.base/share/classes/java/util/GregorianCalendar.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/java.base/share/classes/java/util/GregorianCalendar.java Tue Apr 05 15:39:35 2016 -0400 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1189,37 +1189,33 @@ case HOUR: case HOUR_OF_DAY: { - int unit = max + 1; // 12 or 24 hours - int h = internalGet(field); - int nh = (h + amount) % unit; - if (nh < 0) { - nh += unit; + int rolledValue = getRolledValue(internalGet(field), amount, min, max); + int hourOfDay = rolledValue; + if (field == HOUR && internalGet(AM_PM) == PM) { + hourOfDay += 12; } - time += ONE_HOUR * (nh - h); - // The day might have changed, which could happen if - // the daylight saving time transition brings it to - // the next day, although it's very unlikely. But we - // have to make sure not to change the larger fields. + // Create the current date/time value to perform wall-clock-based + // roll. CalendarDate d = calsys.getCalendarDate(time, getZone()); - if (internalGet(DAY_OF_MONTH) != d.getDayOfMonth()) { - d.setDate(internalGet(YEAR), - internalGet(MONTH) + 1, - internalGet(DAY_OF_MONTH)); - if (field == HOUR) { - assert (internalGet(AM_PM) == PM); - d.addHours(+12); // restore PM + d.setHours(hourOfDay); + time = calsys.getTime(d); + + // If we stay on the same wall-clock time, try the next or previous hour. + if (internalGet(HOUR_OF_DAY) == d.getHours()) { + hourOfDay = getRolledValue(rolledValue, amount > 0 ? +1 : -1, min, max); + if (field == HOUR && internalGet(AM_PM) == PM) { + hourOfDay += 12; } + d.setHours(hourOfDay); time = calsys.getTime(d); } - int hourOfDay = d.getHours(); - internalSet(field, hourOfDay % unit); - if (field == HOUR) { - internalSet(HOUR_OF_DAY, hourOfDay); - } else { - internalSet(AM_PM, hourOfDay / 12); - internalSet(HOUR, hourOfDay % 12); - } + // Get the new hourOfDay value which might have changed due to a DST transition. + hourOfDay = d.getHours(); + // Update the hour related fields + internalSet(HOUR_OF_DAY, hourOfDay); + internalSet(AM_PM, hourOfDay / 12); + internalSet(HOUR, hourOfDay % 12); // Time zone offset and/or daylight saving might have changed. int zoneOffset = d.getZoneOffset(); diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/java/util/concurrent/TimeUnit.java --- a/jdk/src/java.base/share/classes/java/util/concurrent/TimeUnit.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/java.base/share/classes/java/util/concurrent/TimeUnit.java Tue Apr 05 15:39:35 2016 -0400 @@ -75,137 +75,94 @@ /** * Time unit representing one thousandth of a microsecond. */ - NANOSECONDS { - public long toNanos(long d) { return d; } - public long toMicros(long d) { return d/(C1/C0); } - public long toMillis(long d) { return d/(C2/C0); } - public long toSeconds(long d) { return d/(C3/C0); } - public long toMinutes(long d) { return d/(C4/C0); } - public long toHours(long d) { return d/(C5/C0); } - public long toDays(long d) { return d/(C6/C0); } - public long convert(long d, TimeUnit u) { return u.toNanos(d); } - int excessNanos(long d, long m) { return (int)(d - (m*C2)); } - }, - + NANOSECONDS(TimeUnit.NANO_SCALE), /** * Time unit representing one thousandth of a millisecond. */ - MICROSECONDS { - public long toNanos(long d) { return x(d, C1/C0, MAX/(C1/C0)); } - public long toMicros(long d) { return d; } - public long toMillis(long d) { return d/(C2/C1); } - public long toSeconds(long d) { return d/(C3/C1); } - public long toMinutes(long d) { return d/(C4/C1); } - public long toHours(long d) { return d/(C5/C1); } - public long toDays(long d) { return d/(C6/C1); } - public long convert(long d, TimeUnit u) { return u.toMicros(d); } - int excessNanos(long d, long m) { return (int)((d*C1) - (m*C2)); } - }, - + MICROSECONDS(TimeUnit.MICRO_SCALE), /** * Time unit representing one thousandth of a second. */ - MILLISECONDS { - public long toNanos(long d) { return x(d, C2/C0, MAX/(C2/C0)); } - public long toMicros(long d) { return x(d, C2/C1, MAX/(C2/C1)); } - public long toMillis(long d) { return d; } - public long toSeconds(long d) { return d/(C3/C2); } - public long toMinutes(long d) { return d/(C4/C2); } - public long toHours(long d) { return d/(C5/C2); } - public long toDays(long d) { return d/(C6/C2); } - public long convert(long d, TimeUnit u) { return u.toMillis(d); } - int excessNanos(long d, long m) { return 0; } - }, - + MILLISECONDS(TimeUnit.MILLI_SCALE), /** * Time unit representing one second. */ - SECONDS { - public long toNanos(long d) { return x(d, C3/C0, MAX/(C3/C0)); } - public long toMicros(long d) { return x(d, C3/C1, MAX/(C3/C1)); } - public long toMillis(long d) { return x(d, C3/C2, MAX/(C3/C2)); } - public long toSeconds(long d) { return d; } - public long toMinutes(long d) { return d/(C4/C3); } - public long toHours(long d) { return d/(C5/C3); } - public long toDays(long d) { return d/(C6/C3); } - public long convert(long d, TimeUnit u) { return u.toSeconds(d); } - int excessNanos(long d, long m) { return 0; } - }, - + SECONDS(TimeUnit.SECOND_SCALE), /** * Time unit representing sixty seconds. * @since 1.6 */ - MINUTES { - public long toNanos(long d) { return x(d, C4/C0, MAX/(C4/C0)); } - public long toMicros(long d) { return x(d, C4/C1, MAX/(C4/C1)); } - public long toMillis(long d) { return x(d, C4/C2, MAX/(C4/C2)); } - public long toSeconds(long d) { return x(d, C4/C3, MAX/(C4/C3)); } - public long toMinutes(long d) { return d; } - public long toHours(long d) { return d/(C5/C4); } - public long toDays(long d) { return d/(C6/C4); } - public long convert(long d, TimeUnit u) { return u.toMinutes(d); } - int excessNanos(long d, long m) { return 0; } - }, - + MINUTES(TimeUnit.MINUTE_SCALE), /** * Time unit representing sixty minutes. * @since 1.6 */ - HOURS { - public long toNanos(long d) { return x(d, C5/C0, MAX/(C5/C0)); } - public long toMicros(long d) { return x(d, C5/C1, MAX/(C5/C1)); } - public long toMillis(long d) { return x(d, C5/C2, MAX/(C5/C2)); } - public long toSeconds(long d) { return x(d, C5/C3, MAX/(C5/C3)); } - public long toMinutes(long d) { return x(d, C5/C4, MAX/(C5/C4)); } - public long toHours(long d) { return d; } - public long toDays(long d) { return d/(C6/C5); } - public long convert(long d, TimeUnit u) { return u.toHours(d); } - int excessNanos(long d, long m) { return 0; } - }, - + HOURS(TimeUnit.HOUR_SCALE), /** * Time unit representing twenty four hours. * @since 1.6 */ - DAYS { - public long toNanos(long d) { return x(d, C6/C0, MAX/(C6/C0)); } - public long toMicros(long d) { return x(d, C6/C1, MAX/(C6/C1)); } - public long toMillis(long d) { return x(d, C6/C2, MAX/(C6/C2)); } - public long toSeconds(long d) { return x(d, C6/C3, MAX/(C6/C3)); } - public long toMinutes(long d) { return x(d, C6/C4, MAX/(C6/C4)); } - public long toHours(long d) { return x(d, C6/C5, MAX/(C6/C5)); } - public long toDays(long d) { return d; } - public long convert(long d, TimeUnit u) { return u.toDays(d); } - int excessNanos(long d, long m) { return 0; } - }; + DAYS(TimeUnit.DAY_SCALE); + + // Scales as constants + private static final long NANO_SCALE = 1L; + private static final long MICRO_SCALE = 1000L * NANO_SCALE; + private static final long MILLI_SCALE = 1000L * MICRO_SCALE; + private static final long SECOND_SCALE = 1000L * MILLI_SCALE; + private static final long MINUTE_SCALE = 60L * SECOND_SCALE; + private static final long HOUR_SCALE = 60L * MINUTE_SCALE; + private static final long DAY_SCALE = 24L * HOUR_SCALE; + + /* + * Instances cache conversion ratios and saturation cutoffs for + * the units up through SECONDS. Other cases compute them, in + * method cvt. + */ - // Handy constants for conversion methods - static final long C0 = 1L; - static final long C1 = C0 * 1000L; - static final long C2 = C1 * 1000L; - static final long C3 = C2 * 1000L; - static final long C4 = C3 * 60L; - static final long C5 = C4 * 60L; - static final long C6 = C5 * 24L; + private final long scale; + private final long maxNanos; + private final long maxMicros; + private final long maxMillis; + private final long maxSecs; + private final long microRatio; + private final int milliRatio; // fits in 32 bits + private final int secRatio; // fits in 32 bits - static final long MAX = Long.MAX_VALUE; + private TimeUnit(long s) { + this.scale = s; + this.maxNanos = Long.MAX_VALUE / s; + long ur = (s >= MICRO_SCALE) ? (s / MICRO_SCALE) : (MICRO_SCALE / s); + this.microRatio = ur; + this.maxMicros = Long.MAX_VALUE / ur; + long mr = (s >= MILLI_SCALE) ? (s / MILLI_SCALE) : (MILLI_SCALE / s); + this.milliRatio = (int)mr; + this.maxMillis = Long.MAX_VALUE / mr; + long sr = (s >= SECOND_SCALE) ? (s / SECOND_SCALE) : (SECOND_SCALE / s); + this.secRatio = (int)sr; + this.maxSecs = Long.MAX_VALUE / sr; + } /** - * Scale d by m, checking for overflow. - * This has a short name to make above code more readable. + * General conversion utility. + * + * @param d duration + * @param dst result unit scale + * @param src source unit scale */ - static long x(long d, long m, long over) { - if (d > +over) return Long.MAX_VALUE; - if (d < -over) return Long.MIN_VALUE; - return d * m; + private static long cvt(long d, long dst, long src) { + long r, m; + if (src == dst) + return d; + else if (src < dst) + return d / (dst / src); + else if (d > (m = Long.MAX_VALUE / (r = src / dst))) + return Long.MAX_VALUE; + else if (d < -m) + return Long.MIN_VALUE; + else + return d * r; } - // To maintain full signature compatibility with 1.5, and to improve the - // clarity of the generated javadoc (see 6287639: Abstract methods in - // enum classes should not be listed as abstract), method convert - // etc. are not declared abstract but otherwise act as abstract methods. - /** * Converts the given time duration in the given unit to this unit. * Conversions from finer to coarser granularities truncate, so @@ -221,11 +178,17 @@ * @param sourceDuration the time duration in the given {@code sourceUnit} * @param sourceUnit the unit of the {@code sourceDuration} argument * @return the converted duration in this unit, - * or {@code Long.MIN_VALUE} if conversion would negatively - * overflow, or {@code Long.MAX_VALUE} if it would positively overflow. + * or {@code Long.MIN_VALUE} if conversion would negatively overflow, + * or {@code Long.MAX_VALUE} if it would positively overflow. */ public long convert(long sourceDuration, TimeUnit sourceUnit) { - throw new AbstractMethodError(); + switch (this) { + case NANOSECONDS: return sourceUnit.toNanos(sourceDuration); + case MICROSECONDS: return sourceUnit.toMicros(sourceDuration); + case MILLISECONDS: return sourceUnit.toMillis(sourceDuration); + case SECONDS: return sourceUnit.toSeconds(sourceDuration); + default: return cvt(sourceDuration, scale, sourceUnit.scale); + } } /** @@ -233,11 +196,19 @@ * {@link #convert(long, TimeUnit) NANOSECONDS.convert(duration, this)}. * @param duration the duration * @return the converted duration, - * or {@code Long.MIN_VALUE} if conversion would negatively - * overflow, or {@code Long.MAX_VALUE} if it would positively overflow. + * or {@code Long.MIN_VALUE} if conversion would negatively overflow, + * or {@code Long.MAX_VALUE} if it would positively overflow. */ public long toNanos(long duration) { - throw new AbstractMethodError(); + long s, m; + if ((s = scale) == NANO_SCALE) + return duration; + else if (duration > (m = maxNanos)) + return Long.MAX_VALUE; + else if (duration < -m) + return Long.MIN_VALUE; + else + return duration * s; } /** @@ -245,11 +216,21 @@ * {@link #convert(long, TimeUnit) MICROSECONDS.convert(duration, this)}. * @param duration the duration * @return the converted duration, - * or {@code Long.MIN_VALUE} if conversion would negatively - * overflow, or {@code Long.MAX_VALUE} if it would positively overflow. + * or {@code Long.MIN_VALUE} if conversion would negatively overflow, + * or {@code Long.MAX_VALUE} if it would positively overflow. */ public long toMicros(long duration) { - throw new AbstractMethodError(); + long s, m; + if ((s = scale) == MICRO_SCALE) + return duration; + else if (s < MICRO_SCALE) + return duration / microRatio; + else if (duration > (m = maxMicros)) + return Long.MAX_VALUE; + else if (duration < -m) + return Long.MIN_VALUE; + else + return duration * microRatio; } /** @@ -257,11 +238,21 @@ * {@link #convert(long, TimeUnit) MILLISECONDS.convert(duration, this)}. * @param duration the duration * @return the converted duration, - * or {@code Long.MIN_VALUE} if conversion would negatively - * overflow, or {@code Long.MAX_VALUE} if it would positively overflow. + * or {@code Long.MIN_VALUE} if conversion would negatively overflow, + * or {@code Long.MAX_VALUE} if it would positively overflow. */ public long toMillis(long duration) { - throw new AbstractMethodError(); + long s, m; + if ((s = scale) == MILLI_SCALE) + return duration; + else if (s < MILLI_SCALE) + return duration / milliRatio; + else if (duration > (m = maxMillis)) + return Long.MAX_VALUE; + else if (duration < -m) + return Long.MIN_VALUE; + else + return duration * milliRatio; } /** @@ -269,11 +260,21 @@ * {@link #convert(long, TimeUnit) SECONDS.convert(duration, this)}. * @param duration the duration * @return the converted duration, - * or {@code Long.MIN_VALUE} if conversion would negatively - * overflow, or {@code Long.MAX_VALUE} if it would positively overflow. + * or {@code Long.MIN_VALUE} if conversion would negatively overflow, + * or {@code Long.MAX_VALUE} if it would positively overflow. */ public long toSeconds(long duration) { - throw new AbstractMethodError(); + long s, m; + if ((s = scale) == SECOND_SCALE) + return duration; + else if (s < SECOND_SCALE) + return duration / secRatio; + else if (duration > (m = maxSecs)) + return Long.MAX_VALUE; + else if (duration < -m) + return Long.MIN_VALUE; + else + return duration * secRatio; } /** @@ -281,12 +282,12 @@ * {@link #convert(long, TimeUnit) MINUTES.convert(duration, this)}. * @param duration the duration * @return the converted duration, - * or {@code Long.MIN_VALUE} if conversion would negatively - * overflow, or {@code Long.MAX_VALUE} if it would positively overflow. + * or {@code Long.MIN_VALUE} if conversion would negatively overflow, + * or {@code Long.MAX_VALUE} if it would positively overflow. * @since 1.6 */ public long toMinutes(long duration) { - throw new AbstractMethodError(); + return cvt(duration, MINUTE_SCALE, scale); } /** @@ -294,12 +295,12 @@ * {@link #convert(long, TimeUnit) HOURS.convert(duration, this)}. * @param duration the duration * @return the converted duration, - * or {@code Long.MIN_VALUE} if conversion would negatively - * overflow, or {@code Long.MAX_VALUE} if it would positively overflow. + * or {@code Long.MIN_VALUE} if conversion would negatively overflow, + * or {@code Long.MAX_VALUE} if it would positively overflow. * @since 1.6 */ public long toHours(long duration) { - throw new AbstractMethodError(); + return cvt(duration, HOUR_SCALE, scale); } /** @@ -310,7 +311,7 @@ * @since 1.6 */ public long toDays(long duration) { - throw new AbstractMethodError(); + return cvt(duration, DAY_SCALE, scale); } /** @@ -320,7 +321,15 @@ * @param m the number of milliseconds * @return the number of nanoseconds */ - abstract int excessNanos(long d, long m); + private int excessNanos(long d, long m) { + long s; + if ((s = scale) == NANO_SCALE) + return (int)(d - (m * MILLI_SCALE)); + else if (s == MICRO_SCALE) + return (int)((d * 1000L) - (m * MILLI_SCALE)); + else + return 0; + } /** * Performs a timed {@link Object#wait(long, int) Object.wait} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/java/util/jar/JarFile.java --- a/jdk/src/java.base/share/classes/java/util/jar/JarFile.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/java.base/share/classes/java/util/jar/JarFile.java Tue Apr 05 15:39:35 2016 -0400 @@ -28,7 +28,6 @@ import java.io.*; import java.lang.ref.SoftReference; import java.net.URL; -import java.security.PrivilegedAction; import java.util.*; import java.util.stream.Stream; import java.util.stream.StreamSupport; @@ -38,11 +37,10 @@ import java.security.AccessController; import java.security.CodeSource; import jdk.internal.misc.SharedSecrets; +import sun.security.action.GetPropertyAction; import sun.security.util.ManifestEntryVerifier; import sun.security.util.SignatureFileVerifier; -import static java.util.jar.Attributes.Name.MULTI_RELEASE; - /** * The {@code JarFile} class is used to read the contents of a jar file * from any file that can be opened with {@code java.io.RandomAccessFile}. @@ -144,8 +142,9 @@ private final int version; private boolean notVersioned; private final boolean runtimeVersioned; + private boolean isMultiRelease; // is jar multi-release? - // indicates if Class-Path attribute present (only valid if hasCheckedSpecialAttributes true) + // indicates if Class-Path attribute present private boolean hasClassPathAttribute; // true if manifest checked for special attributes private volatile boolean hasCheckedSpecialAttributes; @@ -155,24 +154,18 @@ SharedSecrets.setJavaUtilJarAccess(new JavaUtilJarAccessImpl()); BASE_VERSION = 8; // one less than lowest version for versioned entries - RUNTIME_VERSION = AccessController.doPrivileged( - new PrivilegedAction() { - public Integer run() { - Integer v = jdk.Version.current().major(); - Integer i = Integer.getInteger("jdk.util.jar.version", v); - i = i < 0 ? 0 : i; - return i > v ? v : i; - } - } - ); - String multi_release = AccessController.doPrivileged( - new PrivilegedAction() { - public String run() { - return System.getProperty("jdk.util.jar.enableMultiRelease", "true"); - } - } - ); - switch (multi_release) { + int runtimeVersion = jdk.Version.current().major(); + String jarVersion = AccessController.doPrivileged( + new GetPropertyAction("jdk.util.jar.version")); + if (jarVersion != null) { + int jarVer = Integer.parseInt(jarVersion); + runtimeVersion = (jarVer > runtimeVersion) + ? runtimeVersion : Math.max(jarVer, 0); + } + RUNTIME_VERSION = runtimeVersion; + String enableMultiRelease = AccessController.doPrivileged( + new GetPropertyAction("jdk.util.jar.enableMultiRelease", "true")); + switch (enableMultiRelease) { case "true": default: MULTI_RELEASE_ENABLED = true; @@ -353,8 +346,14 @@ Objects.requireNonNull(version); this.verify = verify; // version applies to multi-release jar files, ignored for regular jar files - this.version = MULTI_RELEASE_FORCED ? RUNTIME_VERSION : version.value(); + if (MULTI_RELEASE_FORCED) { + this.version = RUNTIME_VERSION; + version = Release.RUNTIME; + } else { + this.version = version.value(); + } this.runtimeVersioned = version == Release.RUNTIME; + assert runtimeVersionExists(); } @@ -392,35 +391,18 @@ * @since 9 */ public final boolean isMultiRelease() { - // do not call this code in a constructor because some subclasses use - // lazy loading of manifest so it won't be available at construction time - if (MULTI_RELEASE_ENABLED) { - // Doubled-checked locking pattern - Boolean result = isMultiRelease; - if (result == null) { - synchronized (this) { - result = isMultiRelease; - if (result == null) { - Manifest man = null; - try { - man = getManifest(); - } catch (IOException e) { - //Ignored, manifest cannot be read - } - isMultiRelease = result = (man != null) - && man.getMainAttributes().containsKey(MULTI_RELEASE) - ? Boolean.TRUE : Boolean.FALSE; - } - } + if (isMultiRelease) { + return true; + } + if (MULTI_RELEASE_ENABLED && version != BASE_VERSION) { + try { + checkForSpecialAttributes(); + } catch (IOException io) { + isMultiRelease = false; } - return result == Boolean.TRUE; - } else { - return false; } + return isMultiRelease; } - // the following field, isMultiRelease, should only be used in the method - // isMultiRelease(), like a static local - private volatile Boolean isMultiRelease; // is jar multi-release? /** * Returns the jar file manifest, or {@code null} if none. @@ -905,26 +887,44 @@ } // Statics for hand-coded Boyer-Moore search - private static final char[] CLASSPATH_CHARS = {'c','l','a','s','s','-','p','a','t','h'}; - // The bad character shift for "class-path" - private static final int[] CLASSPATH_LASTOCC; - // The good suffix shift for "class-path" - private static final int[] CLASSPATH_OPTOSFT; + private static final byte[] CLASSPATH_CHARS = + {'C','L','A','S','S','-','P','A','T','H', ':', ' '}; + + // The bad character shift for "class-path:" + private static final byte[] CLASSPATH_LASTOCC; + + private static final byte[] MULTIRELEASE_CHARS = + {'M','U','L','T','I','-','R','E','L','E', 'A', 'S', 'E', ':', ' '}; + + // The bad character shift for "multi-release: " + private static final byte[] MULTIRELEASE_LASTOCC; static { - CLASSPATH_LASTOCC = new int[128]; - CLASSPATH_OPTOSFT = new int[10]; - CLASSPATH_LASTOCC[(int)'c'] = 1; - CLASSPATH_LASTOCC[(int)'l'] = 2; - CLASSPATH_LASTOCC[(int)'s'] = 5; - CLASSPATH_LASTOCC[(int)'-'] = 6; - CLASSPATH_LASTOCC[(int)'p'] = 7; - CLASSPATH_LASTOCC[(int)'a'] = 8; - CLASSPATH_LASTOCC[(int)'t'] = 9; - CLASSPATH_LASTOCC[(int)'h'] = 10; - for (int i=0; i<9; i++) - CLASSPATH_OPTOSFT[i] = 10; - CLASSPATH_OPTOSFT[9]=1; + CLASSPATH_LASTOCC = new byte[64]; + CLASSPATH_LASTOCC[(int)'C' - 32] = 1; + CLASSPATH_LASTOCC[(int)'L' - 32] = 2; + CLASSPATH_LASTOCC[(int)'S' - 32] = 5; + CLASSPATH_LASTOCC[(int)'-' - 32] = 6; + CLASSPATH_LASTOCC[(int)'P' - 32] = 7; + CLASSPATH_LASTOCC[(int)'A' - 32] = 8; + CLASSPATH_LASTOCC[(int)'T' - 32] = 9; + CLASSPATH_LASTOCC[(int)'H' - 32] = 10; + CLASSPATH_LASTOCC[(int)':' - 32] = 11; + CLASSPATH_LASTOCC[(int)' ' - 32] = 12; + + MULTIRELEASE_LASTOCC = new byte[64]; + MULTIRELEASE_LASTOCC[(int)'M' - 32] = 1; + MULTIRELEASE_LASTOCC[(int)'U' - 32] = 2; + MULTIRELEASE_LASTOCC[(int)'T' - 32] = 4; + MULTIRELEASE_LASTOCC[(int)'I' - 32] = 5; + MULTIRELEASE_LASTOCC[(int)'-' - 32] = 6; + MULTIRELEASE_LASTOCC[(int)'R' - 32] = 7; + MULTIRELEASE_LASTOCC[(int)'L' - 32] = 9; + MULTIRELEASE_LASTOCC[(int)'A' - 32] = 11; + MULTIRELEASE_LASTOCC[(int)'S' - 32] = 12; + MULTIRELEASE_LASTOCC[(int)'E' - 32] = 13; + MULTIRELEASE_LASTOCC[(int)':' - 32] = 14; + MULTIRELEASE_LASTOCC[(int)' ' - 32] = 15; } private JarEntry getManEntry() { @@ -962,22 +962,33 @@ /** * Returns true if the pattern {@code src} is found in {@code b}. - * The {@code lastOcc} and {@code optoSft} arrays are the precomputed - * bad character and good suffix shifts. + * The {@code lastOcc} array is the precomputed bad character shifts. + * Since there are no repeated substring in our search strings, + * the good suffix shifts can be replaced with a comparison. */ - private boolean match(char[] src, byte[] b, int[] lastOcc, int[] optoSft) { + private boolean match(byte[] src, byte[] b, byte[] lastOcc) { int len = src.length; int last = b.length - len; int i = 0; next: - while (i<=last) { - for (int j=(len-1); j>=0; j--) { - char c = (char) b[i+j]; - c = (((c-'A')|('Z'-c)) >= 0) ? (char)(c + 32) : c; - if (c != src[j]) { - i += Math.max(j + 1 - lastOcc[c&0x7F], optoSft[j]); + while (i <= last) { + for (int j = (len - 1); j >= 0; j--) { + byte c = b[i + j]; + if (c >= ' ' && c <= 'z') { + if (c >= 'a') c -= 32; // Canonicalize + + if (c != src[j]) { + // no match + int goodShift = (j < len - 1) ? len : 1; + int badShift = lastOcc[c - 32]; + i += Math.max(j + 1 - badShift, goodShift); + continue next; + } + } else { + // no match, character not valid for name + i += len; continue next; - } + } } return true; } @@ -986,17 +997,29 @@ /** * On first invocation, check if the JAR file has the Class-Path - * attribute. A no-op on subsequent calls. + * and the Multi-Release attribute. A no-op on subsequent calls. */ private void checkForSpecialAttributes() throws IOException { - if (hasCheckedSpecialAttributes) return; - JarEntry manEntry = getManEntry(); - if (manEntry != null) { - byte[] b = getBytes(manEntry); - if (match(CLASSPATH_CHARS, b, CLASSPATH_LASTOCC, CLASSPATH_OPTOSFT)) - hasClassPathAttribute = true; + if (hasCheckedSpecialAttributes) { + return; } - hasCheckedSpecialAttributes = true; + synchronized (this) { + if (hasCheckedSpecialAttributes) { + return; + } + JarEntry manEntry = getManEntry(); + if (manEntry != null) { + byte[] b = getBytes(manEntry); + hasClassPathAttribute = match(CLASSPATH_CHARS, b, + CLASSPATH_LASTOCC); + // is this a multi-release jar file + if (MULTI_RELEASE_ENABLED && version != BASE_VERSION) { + isMultiRelease = match(MULTIRELEASE_CHARS, b, + MULTIRELEASE_LASTOCC); + } + } + hasCheckedSpecialAttributes = true; + } } private synchronized void ensureInitialization() { diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/java/util/jar/JarInputStream.java --- a/jdk/src/java.base/share/classes/java/util/jar/JarInputStream.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/java.base/share/classes/java/util/jar/JarInputStream.java Tue Apr 05 15:39:35 2016 -0400 @@ -28,7 +28,7 @@ import java.util.zip.*; import java.io.*; import sun.security.util.ManifestEntryVerifier; -import sun.misc.JarIndex; +import jdk.internal.util.jar.JarIndex; /** * The JarInputStream class is used to read the contents of diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/java/util/jar/JarVerifier.java --- a/jdk/src/java.base/share/classes/java/util/jar/JarVerifier.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/java.base/share/classes/java/util/jar/JarVerifier.java Tue Apr 05 15:39:35 2016 -0400 @@ -32,7 +32,7 @@ import java.security.cert.CertificateException; import java.util.zip.ZipEntry; -import sun.misc.JarIndex; +import jdk.internal.util.jar.JarIndex; import sun.security.util.ManifestDigester; import sun.security.util.ManifestEntryVerifier; import sun.security.util.SignatureFileVerifier; diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java --- a/jdk/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java Tue Apr 05 15:39:35 2016 -0400 @@ -65,8 +65,8 @@ import jdk.internal.misc.JavaUtilZipFileAccess; import jdk.internal.misc.SharedSecrets; -import sun.misc.InvalidJarIndexException; -import sun.misc.JarIndex; +import jdk.internal.util.jar.InvalidJarIndexError; +import jdk.internal.util.jar.JarIndex; import sun.net.util.URLUtil; import sun.net.www.ParseUtil; @@ -902,7 +902,7 @@ */ if (!newLoader.validIndex(name)) { /* the mapping is wrong */ - throw new InvalidJarIndexException("Invalid index"); + throw new InvalidJarIndexError("Invalid index"); } } diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/jdk/internal/util/jar/InvalidJarIndexError.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/java.base/share/classes/jdk/internal/util/jar/InvalidJarIndexError.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.internal.util.jar; + +/** + * Thrown if the URLClassLoader finds the INDEX.LIST file of + * a jar file contains incorrect information. + * + * @since 9 + */ + +public class InvalidJarIndexError extends Error { + + static final long serialVersionUID = 0L; + + /** + * Constructs an {@code InvalidJarIndexError} with no detail message. + */ + public InvalidJarIndexError() { + super(); + } + + /** + * Constructs an {@code InvalidJarIndexError} with the specified detail message. + * + * @param s the detail message. + */ + public InvalidJarIndexError(String s) { + super(s); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/jdk/internal/util/jar/JarIndex.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/java.base/share/classes/jdk/internal/util/jar/JarIndex.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,333 @@ +/* + * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.internal.util.jar; + +import java.io.*; +import java.util.*; +import java.util.jar.*; +import java.util.zip.*; + +/** + * This class is used to maintain mappings from packages, classes + * and resources to their enclosing JAR files. Mappings are kept + * at the package level except for class or resource files that + * are located at the root directory. URLClassLoader uses the mapping + * information to determine where to fetch an extension class or + * resource from. + * + * @author Zhenghua Li + * @since 1.3 + */ + +public class JarIndex { + + /** + * The hash map that maintains mappings from + * package/classe/resource to jar file list(s) + */ + private HashMap> indexMap; + + /** + * The hash map that maintains mappings from + * jar file to package/class/resource lists + */ + private HashMap> jarMap; + + /* + * An ordered list of jar file names. + */ + private String[] jarFiles; + + /** + * The index file name. + */ + public static final String INDEX_NAME = "META-INF/INDEX.LIST"; + + /** + * true if, and only if, sun.misc.JarIndex.metaInfFilenames is set to true. + * If true, the names of the files in META-INF, and its subdirectories, will + * be added to the index. Otherwise, just the directory names are added. + */ + private static final boolean metaInfFilenames = + "true".equals(System.getProperty("sun.misc.JarIndex.metaInfFilenames")); + + /** + * Constructs a new, empty jar index. + */ + public JarIndex() { + indexMap = new HashMap<>(); + jarMap = new HashMap<>(); + } + + /** + * Constructs a new index from the specified input stream. + * + * @param is the input stream containing the index data + */ + public JarIndex(InputStream is) throws IOException { + this(); + read(is); + } + + /** + * Constructs a new index for the specified list of jar files. + * + * @param files the list of jar files to construct the index from. + */ + public JarIndex(String[] files) throws IOException { + this(); + this.jarFiles = files; + parseJars(files); + } + + /** + * Returns the jar index, or null if none. + * + * @param jar the JAR file to get the index from. + * @exception IOException if an I/O error has occurred. + */ + public static JarIndex getJarIndex(JarFile jar) throws IOException { + JarIndex index = null; + JarEntry e = jar.getJarEntry(INDEX_NAME); + // if found, then load the index + if (e != null) { + index = new JarIndex(jar.getInputStream(e)); + } + return index; + } + + /** + * Returns the jar files that are defined in this index. + */ + public String[] getJarFiles() { + return jarFiles; + } + + /* + * Add the key, value pair to the hashmap, the value will + * be put in a linked list which is created if necessary. + */ + private void addToList(String key, String value, + HashMap> t) { + LinkedList list = t.get(key); + if (list == null) { + list = new LinkedList<>(); + list.add(value); + t.put(key, list); + } else if (!list.contains(value)) { + list.add(value); + } + } + + /** + * Returns the list of jar files that are mapped to the file. + * + * @param fileName the key of the mapping + */ + public LinkedList get(String fileName) { + LinkedList jarFiles = null; + if ((jarFiles = indexMap.get(fileName)) == null) { + /* try the package name again */ + int pos; + if((pos = fileName.lastIndexOf('/')) != -1) { + jarFiles = indexMap.get(fileName.substring(0, pos)); + } + } + return jarFiles; + } + + /** + * Add the mapping from the specified file to the specified + * jar file. If there were no mapping for the package of the + * specified file before, a new linked list will be created, + * the jar file is added to the list and a new mapping from + * the package to the jar file list is added to the hashmap. + * Otherwise, the jar file will be added to the end of the + * existing list. + * + * @param fileName the file name + * @param jarName the jar file that the file is mapped to + * + */ + public void add(String fileName, String jarName) { + String packageName; + int pos; + if((pos = fileName.lastIndexOf('/')) != -1) { + packageName = fileName.substring(0, pos); + } else { + packageName = fileName; + } + + addMapping(packageName, jarName); + } + + /** + * Same as add(String,String) except that it doesn't strip off from the + * last index of '/'. It just adds the jarItem (filename or package) + * as it is received. + */ + private void addMapping(String jarItem, String jarName) { + // add the mapping to indexMap + addToList(jarItem, jarName, indexMap); + + // add the mapping to jarMap + addToList(jarName, jarItem, jarMap); + } + + /** + * Go through all the jar files and construct the + * index table. + */ + private void parseJars(String[] files) throws IOException { + if (files == null) { + return; + } + + String currentJar = null; + + for (int i = 0; i < files.length; i++) { + currentJar = files[i]; + ZipFile zrf = new ZipFile(currentJar.replace + ('/', File.separatorChar)); + + Enumeration entries = zrf.entries(); + while(entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + String fileName = entry.getName(); + + // Skip the META-INF directory, the index, and manifest. + // Any files in META-INF/ will be indexed explicitly + if (fileName.equals("META-INF/") || + fileName.equals(INDEX_NAME) || + fileName.equals(JarFile.MANIFEST_NAME)) + continue; + + if (!metaInfFilenames || !fileName.startsWith("META-INF/")) { + add(fileName, currentJar); + } else if (!entry.isDirectory()) { + // Add files under META-INF explicitly so that certain + // services, like ServiceLoader, etc, can be located + // with greater accuracy. Directories can be skipped + // since each file will be added explicitly. + addMapping(fileName, currentJar); + } + } + + zrf.close(); + } + } + + /** + * Writes the index to the specified OutputStream + * + * @param out the output stream + * @exception IOException if an I/O error has occurred + */ + public void write(OutputStream out) throws IOException { + BufferedWriter bw = new BufferedWriter + (new OutputStreamWriter(out, "UTF8")); + bw.write("JarIndex-Version: 1.0\n\n"); + + if (jarFiles != null) { + for (int i = 0; i < jarFiles.length; i++) { + /* print out the jar file name */ + String jar = jarFiles[i]; + bw.write(jar + "\n"); + LinkedList jarlist = jarMap.get(jar); + if (jarlist != null) { + Iterator listitr = jarlist.iterator(); + while(listitr.hasNext()) { + bw.write(listitr.next() + "\n"); + } + } + bw.write("\n"); + } + bw.flush(); + } + } + + + /** + * Reads the index from the specified InputStream. + * + * @param is the input stream + * @exception IOException if an I/O error has occurred + */ + public void read(InputStream is) throws IOException { + BufferedReader br = new BufferedReader + (new InputStreamReader(is, "UTF8")); + String line = null; + String currentJar = null; + + /* an ordered list of jar file names */ + Vector jars = new Vector<>(); + + /* read until we see a .jar line */ + while((line = br.readLine()) != null && !line.endsWith(".jar")); + + for(;line != null; line = br.readLine()) { + if (line.length() == 0) + continue; + + if (line.endsWith(".jar")) { + currentJar = line; + jars.add(currentJar); + } else { + String name = line; + addMapping(name, currentJar); + } + } + + jarFiles = jars.toArray(new String[jars.size()]); + } + + /** + * Merges the current index into another index, taking into account + * the relative path of the current index. + * + * @param toIndex The destination index which the current index will + * merge into. + * @param path The relative path of the this index to the destination + * index. + * + */ + public void merge(JarIndex toIndex, String path) { + Iterator>> itr = indexMap.entrySet().iterator(); + while(itr.hasNext()) { + Map.Entry> e = itr.next(); + String packageName = e.getKey(); + LinkedList from_list = e.getValue(); + Iterator listItr = from_list.iterator(); + while(listItr.hasNext()) { + String jarName = listItr.next(); + if (path != null) { + jarName = path.concat(jarName); + } + toIndex.addMapping(packageName, jarName); + } + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/module-info.java --- a/jdk/src/java.base/share/classes/module-info.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/java.base/share/classes/module-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -180,6 +180,8 @@ jdk.jvmstat; exports jdk.internal.ref to java.desktop; + exports jdk.internal.util.jar to + jdk.jartool; exports sun.net to java.httpclient; exports sun.net.dns to diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/sun/misc/InvalidJarIndexException.java --- a/jdk/src/java.base/share/classes/sun/misc/InvalidJarIndexException.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,60 +0,0 @@ -/* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc; - -import java.lang.LinkageError; - -/** - * Thrown if the URLClassLoader finds the INDEX.LIST file of - * a jar file contains incorrect information. - * - * @author Zhenghua Li - * @since 1.3 - */ - -public -class InvalidJarIndexException extends RuntimeException { - - static final long serialVersionUID = -6159797516569680148L; - - /** - * Constructs an InvalidJarIndexException with no - * detail message. - */ - public InvalidJarIndexException() { - super(); - } - - /** - * Constructs an InvalidJarIndexException with the - * specified detail message. - * - * @param s the detail message. - */ - public InvalidJarIndexException(String s) { - super(s); - } -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/sun/misc/JarIndex.java --- a/jdk/src/java.base/share/classes/sun/misc/JarIndex.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,333 +0,0 @@ -/* - * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc; - -import java.io.*; -import java.util.*; -import java.util.jar.*; -import java.util.zip.*; - -/** - * This class is used to maintain mappings from packages, classes - * and resources to their enclosing JAR files. Mappings are kept - * at the package level except for class or resource files that - * are located at the root directory. URLClassLoader uses the mapping - * information to determine where to fetch an extension class or - * resource from. - * - * @author Zhenghua Li - * @since 1.3 - */ - -public class JarIndex { - - /** - * The hash map that maintains mappings from - * package/classe/resource to jar file list(s) - */ - private HashMap> indexMap; - - /** - * The hash map that maintains mappings from - * jar file to package/class/resource lists - */ - private HashMap> jarMap; - - /* - * An ordered list of jar file names. - */ - private String[] jarFiles; - - /** - * The index file name. - */ - public static final String INDEX_NAME = "META-INF/INDEX.LIST"; - - /** - * true if, and only if, sun.misc.JarIndex.metaInfFilenames is set to true. - * If true, the names of the files in META-INF, and its subdirectories, will - * be added to the index. Otherwise, just the directory names are added. - */ - private static final boolean metaInfFilenames = - "true".equals(System.getProperty("sun.misc.JarIndex.metaInfFilenames")); - - /** - * Constructs a new, empty jar index. - */ - public JarIndex() { - indexMap = new HashMap<>(); - jarMap = new HashMap<>(); - } - - /** - * Constructs a new index from the specified input stream. - * - * @param is the input stream containing the index data - */ - public JarIndex(InputStream is) throws IOException { - this(); - read(is); - } - - /** - * Constructs a new index for the specified list of jar files. - * - * @param files the list of jar files to construct the index from. - */ - public JarIndex(String[] files) throws IOException { - this(); - this.jarFiles = files; - parseJars(files); - } - - /** - * Returns the jar index, or null if none. - * - * @param jar the JAR file to get the index from. - * @exception IOException if an I/O error has occurred. - */ - public static JarIndex getJarIndex(JarFile jar) throws IOException { - JarIndex index = null; - JarEntry e = jar.getJarEntry(INDEX_NAME); - // if found, then load the index - if (e != null) { - index = new JarIndex(jar.getInputStream(e)); - } - return index; - } - - /** - * Returns the jar files that are defined in this index. - */ - public String[] getJarFiles() { - return jarFiles; - } - - /* - * Add the key, value pair to the hashmap, the value will - * be put in a linked list which is created if necessary. - */ - private void addToList(String key, String value, - HashMap> t) { - LinkedList list = t.get(key); - if (list == null) { - list = new LinkedList<>(); - list.add(value); - t.put(key, list); - } else if (!list.contains(value)) { - list.add(value); - } - } - - /** - * Returns the list of jar files that are mapped to the file. - * - * @param fileName the key of the mapping - */ - public LinkedList get(String fileName) { - LinkedList jarFiles = null; - if ((jarFiles = indexMap.get(fileName)) == null) { - /* try the package name again */ - int pos; - if((pos = fileName.lastIndexOf('/')) != -1) { - jarFiles = indexMap.get(fileName.substring(0, pos)); - } - } - return jarFiles; - } - - /** - * Add the mapping from the specified file to the specified - * jar file. If there were no mapping for the package of the - * specified file before, a new linked list will be created, - * the jar file is added to the list and a new mapping from - * the package to the jar file list is added to the hashmap. - * Otherwise, the jar file will be added to the end of the - * existing list. - * - * @param fileName the file name - * @param jarName the jar file that the file is mapped to - * - */ - public void add(String fileName, String jarName) { - String packageName; - int pos; - if((pos = fileName.lastIndexOf('/')) != -1) { - packageName = fileName.substring(0, pos); - } else { - packageName = fileName; - } - - addMapping(packageName, jarName); - } - - /** - * Same as add(String,String) except that it doesn't strip off from the - * last index of '/'. It just adds the jarItem (filename or package) - * as it is received. - */ - private void addMapping(String jarItem, String jarName) { - // add the mapping to indexMap - addToList(jarItem, jarName, indexMap); - - // add the mapping to jarMap - addToList(jarName, jarItem, jarMap); - } - - /** - * Go through all the jar files and construct the - * index table. - */ - private void parseJars(String[] files) throws IOException { - if (files == null) { - return; - } - - String currentJar = null; - - for (int i = 0; i < files.length; i++) { - currentJar = files[i]; - ZipFile zrf = new ZipFile(currentJar.replace - ('/', File.separatorChar)); - - Enumeration entries = zrf.entries(); - while(entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - String fileName = entry.getName(); - - // Skip the META-INF directory, the index, and manifest. - // Any files in META-INF/ will be indexed explicitly - if (fileName.equals("META-INF/") || - fileName.equals(INDEX_NAME) || - fileName.equals(JarFile.MANIFEST_NAME)) - continue; - - if (!metaInfFilenames || !fileName.startsWith("META-INF/")) { - add(fileName, currentJar); - } else if (!entry.isDirectory()) { - // Add files under META-INF explicitly so that certain - // services, like ServiceLoader, etc, can be located - // with greater accuracy. Directories can be skipped - // since each file will be added explicitly. - addMapping(fileName, currentJar); - } - } - - zrf.close(); - } - } - - /** - * Writes the index to the specified OutputStream - * - * @param out the output stream - * @exception IOException if an I/O error has occurred - */ - public void write(OutputStream out) throws IOException { - BufferedWriter bw = new BufferedWriter - (new OutputStreamWriter(out, "UTF8")); - bw.write("JarIndex-Version: 1.0\n\n"); - - if (jarFiles != null) { - for (int i = 0; i < jarFiles.length; i++) { - /* print out the jar file name */ - String jar = jarFiles[i]; - bw.write(jar + "\n"); - LinkedList jarlist = jarMap.get(jar); - if (jarlist != null) { - Iterator listitr = jarlist.iterator(); - while(listitr.hasNext()) { - bw.write(listitr.next() + "\n"); - } - } - bw.write("\n"); - } - bw.flush(); - } - } - - - /** - * Reads the index from the specified InputStream. - * - * @param is the input stream - * @exception IOException if an I/O error has occurred - */ - public void read(InputStream is) throws IOException { - BufferedReader br = new BufferedReader - (new InputStreamReader(is, "UTF8")); - String line = null; - String currentJar = null; - - /* an ordered list of jar file names */ - Vector jars = new Vector<>(); - - /* read until we see a .jar line */ - while((line = br.readLine()) != null && !line.endsWith(".jar")); - - for(;line != null; line = br.readLine()) { - if (line.length() == 0) - continue; - - if (line.endsWith(".jar")) { - currentJar = line; - jars.add(currentJar); - } else { - String name = line; - addMapping(name, currentJar); - } - } - - jarFiles = jars.toArray(new String[jars.size()]); - } - - /** - * Merges the current index into another index, taking into account - * the relative path of the current index. - * - * @param toIndex The destination index which the current index will - * merge into. - * @param path The relative path of the this index to the destination - * index. - * - */ - public void merge(JarIndex toIndex, String path) { - Iterator>> itr = indexMap.entrySet().iterator(); - while(itr.hasNext()) { - Map.Entry> e = itr.next(); - String packageName = e.getKey(); - LinkedList from_list = e.getValue(); - Iterator listItr = from_list.iterator(); - while(listItr.hasNext()) { - String jarName = listItr.next(); - if (path != null) { - jarName = path.concat(jarName); - } - toIndex.addMapping(packageName, jarName); - } - } - } -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/sun/misc/resources/Messages.java --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2002, 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc.resources; - -/** - * This class represents the {@code ResourceBundle} - * for sun.misc. - * - * @author Michael Colburn - */ - -public class Messages extends java.util.ListResourceBundle { - - /** - * Returns the contents of this {@code ResourceBundle}. - * - * @return the contents of this {@code ResourceBundle}. - */ - public Object[][] getContents() { - return contents; - } - - private static final Object[][] contents = { - { "optpkg.versionerror", "ERROR: Invalid version format used in {0} JAR file. Check the documentation for the supported version format." }, - { "optpkg.attributeerror", "ERROR: The required {0} JAR manifest attribute is not set in {1} JAR file." }, - { "optpkg.attributeserror", "ERROR: Some required JAR manifest attributes are not set in {0} JAR file." } - }; - -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/sun/misc/resources/Messages_de.java --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_de.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc.resources; - -/** - * This class represents the {@code ResourceBundle} - * for sun.misc. - * - * @author Michael Colburn - */ - -public class Messages_de extends java.util.ListResourceBundle { - - /** - * Returns the contents of this {@code ResourceBundle}. - * - * @return the contents of this {@code ResourceBundle}. - */ - public Object[][] getContents() { - return contents; - } - - private static final Object[][] contents = { - { "optpkg.versionerror", "ERROR: In JAR-Datei {0} wurde ein ung\u00FCltiges Versionsformat verwendet. Pr\u00FCfen Sie in der Dokumentation, welches Versionsformat unterst\u00FCtzt wird." }, - { "optpkg.attributeerror", "ERROR: In JAR-Datei {1} ist das erforderliche JAR-Manifestattribut {0} nicht festgelegt." }, - { "optpkg.attributeserror", "ERROR: In JAR-Datei {0} sind einige erforderliche JAR-Manifestattribute nicht festgelegt." } - }; - -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/sun/misc/resources/Messages_es.java --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_es.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc.resources; - -/** - * This class represents the {@code ResourceBundle} - * for sun.misc. - * - * @author Michael Colburn - */ - -public class Messages_es extends java.util.ListResourceBundle { - - /** - * Returns the contents of this {@code ResourceBundle}. - * - * @return the contents of this {@code ResourceBundle}. - */ - public Object[][] getContents() { - return contents; - } - - private static final Object[][] contents = { - { "optpkg.versionerror", "ERROR: el formato del archivo JAR {0} pertenece a una versi\u00F3n no v\u00E1lida. Busque en la documentaci\u00F3n el formato de una versi\u00F3n soportada." }, - { "optpkg.attributeerror", "ERROR: el atributo obligatorio JAR manifest {0} no est\u00E1 definido en el archivo JAR {1}." }, - { "optpkg.attributeserror", "ERROR: algunos atributos obligatorios JAR manifest no est\u00E1n definidos en el archivo JAR {0}." } - }; - -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/sun/misc/resources/Messages_fr.java --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_fr.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc.resources; - -/** - * This class represents the {@code ResourceBundle} - * for sun.misc. - * - * @author Michael Colburn - */ - -public class Messages_fr extends java.util.ListResourceBundle { - - /** - * Returns the contents of this {@code ResourceBundle}. - * - * @return the contents of this {@code ResourceBundle}. - */ - public Object[][] getContents() { - return contents; - } - - private static final Object[][] contents = { - { "optpkg.versionerror", "ERREUR\u00A0: le format de version utilis\u00E9 pour le fichier JAR {0} n''est pas valide. Pour conna\u00EEtre le format de version pris en charge, consultez la documentation." }, - { "optpkg.attributeerror", "ERREUR\u00A0: l''attribut manifest JAR {0} obligatoire n''est pas d\u00E9fini dans le fichier JAR {1}." }, - { "optpkg.attributeserror", "ERREUR\u00A0: certains attributs manifest JAR obligatoires ne sont pas d\u00E9finis dans le fichier JAR {0}." } - }; - -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/sun/misc/resources/Messages_it.java --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_it.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc.resources; - -/** - * This class represents the {@code ResourceBundle} - * for sun.misc. - * - * @author Michael Colburn - */ - -public class Messages_it extends java.util.ListResourceBundle { - - /** - * Returns the contents of this {@code ResourceBundle}. - * - * @return the contents of this {@code ResourceBundle}. - */ - public Object[][] getContents() { - return contents; - } - - private static final Object[][] contents = { - { "optpkg.versionerror", "ERRORE: Formato versione non valido nel file JAR {0}. Verificare nella documentazione il formato della versione supportato." }, - { "optpkg.attributeerror", "ERRORE: L''attributo manifest JAR {0} richiesto non \u00E8 impostato nel file JAR {1}." }, - { "optpkg.attributeserror", "ERRORE: Alcuni attributi manifesti JAR obbligatori non sono impostati nel file JAR {0}." } - }; - -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/sun/misc/resources/Messages_ja.java --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_ja.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc.resources; - -/** - * This class represents the {@code ResourceBundle} - * for sun.misc. - * - * @author Michael Colburn - */ - -public class Messages_ja extends java.util.ListResourceBundle { - - /** - * Returns the contents of this {@code ResourceBundle}. - * - * @return the contents of this {@code ResourceBundle}. - */ - public Object[][] getContents() { - return contents; - } - - private static final Object[][] contents = { - { "optpkg.versionerror", "\u30A8\u30E9\u30FC: JAR\u30D5\u30A1\u30A4\u30EB{0}\u3067\u7121\u52B9\u306A\u30D0\u30FC\u30B8\u30E7\u30F3\u5F62\u5F0F\u304C\u4F7F\u7528\u3055\u308C\u3066\u3044\u307E\u3059\u3002\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u308B\u30D0\u30FC\u30B8\u30E7\u30F3\u5F62\u5F0F\u306B\u3064\u3044\u3066\u306E\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u3092\u53C2\u7167\u3057\u3066\u304F\u3060\u3055\u3044\u3002" }, - { "optpkg.attributeerror", "\u30A8\u30E9\u30FC: \u5FC5\u8981\u306AJAR\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u5C5E\u6027{0}\u304CJAR\u30D5\u30A1\u30A4\u30EB{1}\u306B\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002" }, - { "optpkg.attributeserror", "\u30A8\u30E9\u30FC: \u8907\u6570\u306E\u5FC5\u8981\u306AJAR\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u5C5E\u6027\u304CJAR\u30D5\u30A1\u30A4\u30EB{0}\u306B\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002" } - }; - -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/sun/misc/resources/Messages_ko.java --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_ko.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc.resources; - -/** - * This class represents the {@code ResourceBundle} - * for sun.misc. - * - * @author Michael Colburn - */ - -public class Messages_ko extends java.util.ListResourceBundle { - - /** - * Returns the contents of this {@code ResourceBundle}. - * - * @return the contents of this {@code ResourceBundle}. - */ - public Object[][] getContents() { - return contents; - } - - private static final Object[][] contents = { - { "optpkg.versionerror", "\uC624\uB958: {0} JAR \uD30C\uC77C\uC5D0 \uBD80\uC801\uD569\uD55C \uBC84\uC804 \uD615\uC2DD\uC774 \uC0AC\uC6A9\uB418\uC5C8\uC2B5\uB2C8\uB2E4. \uC124\uBA85\uC11C\uC5D0\uC11C \uC9C0\uC6D0\uB418\uB294 \uBC84\uC804 \uD615\uC2DD\uC744 \uD655\uC778\uD558\uC2ED\uC2DC\uC624." }, - { "optpkg.attributeerror", "\uC624\uB958: \uD544\uC694\uD55C {0} JAR manifest \uC18D\uC131\uC774 {1} JAR \uD30C\uC77C\uC5D0 \uC124\uC815\uB418\uC5B4 \uC788\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4." }, - { "optpkg.attributeserror", "\uC624\uB958: \uD544\uC694\uD55C \uC77C\uBD80 JAR manifest \uC18D\uC131\uC774 {0} JAR \uD30C\uC77C\uC5D0 \uC124\uC815\uB418\uC5B4 \uC788\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4." } - }; - -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/sun/misc/resources/Messages_pt_BR.java --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_pt_BR.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc.resources; - -/** - * This class represents the {@code ResourceBundle} - * for sun.misc. - * - * @author Michael Colburn - */ - -public class Messages_pt_BR extends java.util.ListResourceBundle { - - /** - * Returns the contents of this {@code ResourceBundle}. - * - * @return the contents of this {@code ResourceBundle}. - */ - public Object[][] getContents() { - return contents; - } - - private static final Object[][] contents = { - { "optpkg.versionerror", "ERRO: formato de vers\u00E3o inv\u00E1lido usado no arquivo JAR {0}. Verifique a documenta\u00E7\u00E3o para obter o formato de vers\u00E3o suportado." }, - { "optpkg.attributeerror", "ERRO: o atributo de manifesto JAR {0} necess\u00E1rio n\u00E3o est\u00E1 definido no arquivo JAR {1}." }, - { "optpkg.attributeserror", "ERRO: alguns atributos de manifesto JAR necess\u00E1rios n\u00E3o est\u00E3o definidos no arquivo JAR {0}." } - }; - -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/sun/misc/resources/Messages_sv.java --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_sv.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc.resources; - -/** - * This class represents the {@code ResourceBundle} - * for sun.misc. - * - * @author Michael Colburn - */ - -public class Messages_sv extends java.util.ListResourceBundle { - - /** - * Returns the contents of this {@code ResourceBundle}. - * - * @return the contents of this {@code ResourceBundle}. - */ - public Object[][] getContents() { - return contents; - } - - private static final Object[][] contents = { - { "optpkg.versionerror", "FEL: Ogiltigt versionsformat i {0} JAR-fil. Kontrollera i dokumentationen vilket versionsformat som st\u00F6ds." }, - { "optpkg.attributeerror", "FEL: Obligatoriskt JAR manifest-attribut {0} \u00E4r inte inst\u00E4llt i {1} JAR-filen." }, - { "optpkg.attributeserror", "FEL: Vissa obligatoriska JAR manifest-attribut \u00E4r inte inst\u00E4llda i {0} JAR-filen." } - }; - -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/sun/misc/resources/Messages_zh_CN.java --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_zh_CN.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc.resources; - -/** - * This class represents the {@code ResourceBundle} - * for sun.misc. - * - * @author Michael Colburn - */ - -public class Messages_zh_CN extends java.util.ListResourceBundle { - - /** - * Returns the contents of this {@code ResourceBundle}. - * - * @return the contents of this {@code ResourceBundle}. - */ - public Object[][] getContents() { - return contents; - } - - private static final Object[][] contents = { - { "optpkg.versionerror", "\u9519\u8BEF: {0} JAR \u6587\u4EF6\u4E2D\u4F7F\u7528\u7684\u7248\u672C\u683C\u5F0F\u65E0\u6548\u3002\u8BF7\u68C0\u67E5\u6587\u6863\u4EE5\u4E86\u89E3\u652F\u6301\u7684\u7248\u672C\u683C\u5F0F\u3002" }, - { "optpkg.attributeerror", "\u9519\u8BEF: \u5FC5\u8981\u7684{0} JAR \u6E05\u5355\u5C5E\u6027\u672A\u5728{1} JAR \u6587\u4EF6\u4E2D\u8BBE\u7F6E\u3002" }, - { "optpkg.attributeserror", "\u9519\u8BEF: \u67D0\u4E9B\u5FC5\u8981\u7684 JAR \u6E05\u5355\u5C5E\u6027\u672A\u5728{0} JAR \u6587\u4EF6\u4E2D\u8BBE\u7F6E\u3002" } - }; - -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/sun/misc/resources/Messages_zh_TW.java --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_zh_TW.java Tue Apr 05 10:34:05 2016 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.misc.resources; - -/** - * This class represents the {@code ResourceBundle} - * for sun.misc. - * - * @author Michael Colburn - */ - -public class Messages_zh_TW extends java.util.ListResourceBundle { - - /** - * Returns the contents of this {@code ResourceBundle}. - * - * @return the contents of this {@code ResourceBundle}. - */ - public Object[][] getContents() { - return contents; - } - - private static final Object[][] contents = { - { "optpkg.versionerror", "\u932F\u8AA4: {0} JAR \u6A94\u4F7F\u7528\u4E86\u7121\u6548\u7684\u7248\u672C\u683C\u5F0F\u3002\u8ACB\u6AA2\u67E5\u6587\u4EF6\uFF0C\u4EE5\u7372\u5F97\u652F\u63F4\u7684\u7248\u672C\u683C\u5F0F\u3002" }, - { "optpkg.attributeerror", "\u932F\u8AA4: {1} JAR \u6A94\u4E2D\u672A\u8A2D\u5B9A\u5FC5\u8981\u7684 {0} JAR \u8CC7\u8A0A\u6E05\u55AE\u5C6C\u6027\u3002" }, - { "optpkg.attributeserror", "\u932F\u8AA4: {0} JAR \u6A94\u4E2D\u672A\u8A2D\u5B9A\u67D0\u4E9B\u5FC5\u8981\u7684 JAR \u8CC7\u8A0A\u6E05\u55AE\u5C6C\u6027\u3002" } - }; - -} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/java.base/share/classes/sun/util/resources/LocaleData.java --- a/jdk/src/java.base/share/classes/sun/util/resources/LocaleData.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/java.base/share/classes/sun/util/resources/LocaleData.java Tue Apr 05 15:39:35 2016 -0400 @@ -197,8 +197,6 @@ private static abstract class LocaleDataResourceBundleProvider implements ResourceBundleProvider { - abstract protected boolean isSupportedInModule(String baseName, Locale locale); - /** * Changes baseName to its module dependent package name and * calls the super class implementation. For example, @@ -217,10 +215,6 @@ * resource bundles except for the java.time supplementary data. */ public static abstract class CommonResourceBundleProvider extends LocaleDataResourceBundleProvider { - @Override - protected boolean isSupportedInModule(String baseName, Locale locale) { - return LocaleDataStrategy.INSTANCE.inJavaBaseModule(baseName, locale); - } } /** @@ -228,10 +222,6 @@ * resource bundles for java.time. */ public static abstract class SupplementaryResourceBundleProvider extends LocaleDataResourceBundleProvider { - @Override - protected boolean isSupportedInModule(String baseName, Locale locale) { - return SupplementaryStrategy.INSTANCE.inJavaBaseModule(baseName, locale); - } } // Bundles.Strategy implementations diff -r 64f6ae06310e -r eda408d4f253 jdk/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/KeyStore.java --- a/jdk/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/KeyStore.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/KeyStore.java Tue Apr 05 15:39:35 2016 -0400 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -188,8 +188,10 @@ /* * The keystore entries. + * Keys in the map are unique aliases (thus can differ from + * KeyEntry.getAlias()) */ - private Collection entries = new ArrayList(); + private Map entries = new HashMap<>(); /* * The keystore name. @@ -248,13 +250,10 @@ if (engineIsKeyEntry(alias) == false) return null; - for (KeyEntry entry : entries) { - if (alias.equals(entry.getAlias())) { - return entry.getPrivateKey(); - } - } - - return null; + KeyEntry entry = entries.get(alias); + return (entry == null) + ? null + : entry.getPrivateKey(); } /** @@ -274,15 +273,13 @@ return null; } - for (KeyEntry entry : entries) { - if (alias.equals(entry.getAlias())) { - X509Certificate[] certChain = entry.getCertificateChain(); - - return certChain.clone(); - } - } - - return null; + KeyEntry entry = entries.get(alias); + X509Certificate[] certChain = (entry == null) + ? null + : entry.getCertificateChain(); + return (certChain == null) + ? null + : certChain.clone(); } /** @@ -306,15 +303,13 @@ return null; } - for (KeyEntry entry : entries) { - if (alias.equals(entry.getAlias())) - { - X509Certificate[] certChain = entry.getCertificateChain(); - return certChain.length == 0 ? null : certChain[0]; - } - } - - return null; + KeyEntry entry = entries.get(alias); + X509Certificate[] certChain = (entry == null) + ? null + : entry.getCertificateChain(); + return (certChain == null || certChain.length == 0) + ? null + : certChain[0]; } /** @@ -378,16 +373,7 @@ if (key instanceof RSAPrivateCrtKey) { - KeyEntry entry = null; - boolean found = false; - - for (KeyEntry e : entries) { - if (alias.equals(e.getAlias())) { - found = true; - entry = e; - break; - } - } + KeyEntry entry = entries.get(alias); X509Certificate[] xchain; if (chain != null) { @@ -401,11 +387,11 @@ xchain = null; } - if (! found) { + if (entry == null) { entry = //TODO new KeyEntry(alias, key, (X509Certificate[]) chain); new KeyEntry(alias, null, xchain); - entries.add(entry); + storeWithUniqueAlias(alias, entry); } entry.setAlias(alias); @@ -484,23 +470,14 @@ // TODO - build CryptoAPI chain? X509Certificate[] chain = new X509Certificate[]{ (X509Certificate) cert }; - KeyEntry entry = null; - boolean found = false; + KeyEntry entry = entries.get(alias); - for (KeyEntry e : entries) { - if (alias.equals(e.getAlias())) { - found = true; - entry = e; - break; - } + if (entry == null) { + entry = + new KeyEntry(alias, null, chain); + storeWithUniqueAlias(alias, entry); } - if (! found) { - entry = - new KeyEntry(alias, null, chain); - entries.add(entry); - - } if (entry.getPrivateKey() == null) { // trusted-cert entry entry.setAlias(alias); @@ -532,32 +509,26 @@ throw new KeyStoreException("alias must not be null"); } - for (KeyEntry entry : entries) { - if (alias.equals(entry.getAlias())) { + KeyEntry entry = entries.remove(alias); + if (entry != null) { + // Get end-entity certificate and remove from system cert store + X509Certificate[] certChain = entry.getCertificateChain(); + if (certChain != null) { - // Get end-entity certificate and remove from system cert store - X509Certificate[] certChain = entry.getCertificateChain(); - if (certChain != null) { + try { - try { - - byte[] encoding = certChain[0].getEncoded(); - removeCertificate(getName(), alias, encoding, + byte[] encoding = certChain[0].getEncoded(); + removeCertificate(getName(), entry.getAlias(), encoding, encoding.length); - } catch (CertificateException e) { - throw new KeyStoreException("Cannot remove entry: " + - e); - } + } catch (CertificateException e) { + throw new KeyStoreException("Cannot remove entry: ", e); } - Key privateKey = entry.getPrivateKey(); - if (privateKey != null) { - destroyKeyContainer( - Key.getContainerName(privateKey.getHCryptProvider())); - } - - entries.remove(entry); - break; + } + Key privateKey = entry.getPrivateKey(); + if (privateKey != null) { + destroyKeyContainer( + Key.getContainerName(privateKey.getHCryptProvider())); } } } @@ -568,8 +539,7 @@ * @return enumeration of the alias names */ public Enumeration engineAliases() { - - final Iterator iter = entries.iterator(); + final Iterator iter = entries.keySet().iterator(); return new Enumeration() { @@ -580,8 +550,7 @@ public String nextElement() { - KeyEntry entry = iter.next(); - return entry.getAlias(); + return iter.next(); } }; } @@ -594,15 +563,7 @@ * @return true if the alias exists, false otherwise */ public boolean engineContainsAlias(String alias) { - for (Enumeration enumerator = engineAliases(); - enumerator.hasMoreElements();) - { - String a = enumerator.nextElement(); - - if (a.equals(alias)) - return true; - } - return false; + return entries.containsKey(alias); } /** @@ -627,13 +588,8 @@ return false; } - for (KeyEntry entry : entries) { - if (alias.equals(entry.getAlias())) { - return entry.getPrivateKey() != null; - } - } - - return false; + KeyEntry entry = entries.get(alias); + return entry != null && entry.getPrivateKey() != null; } /** @@ -643,15 +599,14 @@ * @return true if the entry identified by the given alias is a * trusted certificate entry, false otherwise. */ - public boolean engineIsCertificateEntry(String alias) - { - for (KeyEntry entry : entries) { - if (alias.equals(entry.getAlias())) { - return entry.getPrivateKey() == null; - } + public boolean engineIsCertificateEntry(String alias) { + + if (alias == null) { + return false; } - return false; + KeyEntry entry = entries.get(alias); + return entry != null && entry.getPrivateKey() == null; } /** @@ -670,9 +625,10 @@ * @return the (alias) name of the first entry with matching certificate, * or null if no such entry exists in this keystore. */ - public String engineGetCertificateAlias(Certificate cert) - { - for (KeyEntry entry : entries) { + public String engineGetCertificateAlias(Certificate cert) { + + for (Map.Entry mapEntry : entries.entrySet()) { + KeyEntry entry = mapEntry.getValue(); if (entry.certChain != null && entry.certChain[0].equals(cert)) { return entry.getAlias(); } @@ -765,7 +721,7 @@ try { // Load keys and/or certificate chains - loadKeysOrCertificateChains(getName(), entries); + loadKeysOrCertificateChains(getName()); } catch (KeyStoreException e) { throw new IOException(e); @@ -773,12 +729,31 @@ } /** + * Stores the given entry into the map, making sure + * the alias, used as the key is unique. + * If the same alias already exists, it tries to append + * a suffix (1), (2), etc to it until it finds a unique + * value. + */ + private void storeWithUniqueAlias(String alias, KeyEntry entry) { + String uniqAlias = alias; + int uniqNum = 1; + + while (true) { + if (entries.putIfAbsent(uniqAlias, entry) == null) { + break; + } + uniqAlias = alias + " (" + (uniqNum++) + ")"; + } + } + + + /** * Generates a certificate chain from the collection of * certificates and stores the result into a key entry. */ private void generateCertificateChain(String alias, - Collection certCollection, - Collection entries) + Collection certCollection) { try { @@ -792,10 +767,8 @@ certChain[i] = (X509Certificate) iter.next(); } - KeyEntry entry = new KeyEntry(alias, null, certChain); - - // Add cert chain - entries.add(entry); + storeWithUniqueAlias(alias, + new KeyEntry(alias, null, certChain)); } catch (Throwable e) { @@ -810,8 +783,7 @@ */ private void generateRSAKeyAndCertificateChain(String alias, long hCryptProv, long hCryptKey, int keyLength, - Collection certCollection, - Collection entries) + Collection certCollection) { try { @@ -825,11 +797,9 @@ certChain[i] = (X509Certificate) iter.next(); } - KeyEntry entry = new KeyEntry(alias, new RSAPrivateKey(hCryptProv, - hCryptKey, keyLength), certChain); - - // Add cert chain - entries.add(entry); + storeWithUniqueAlias(alias, new KeyEntry(alias, + new RSAPrivateKey(hCryptProv, hCryptKey, keyLength), + certChain)); } catch (Throwable e) { @@ -886,8 +856,8 @@ * @param name Name of keystore. * @param entries Collection of key/certificate. */ - private native void loadKeysOrCertificateChains(String name, - Collection entries) throws KeyStoreException; + private native void loadKeysOrCertificateChains(String name) + throws KeyStoreException; /** * Stores a DER-encoded certificate into the certificate store diff -r 64f6ae06310e -r eda408d4f253 jdk/src/jdk.crypto.mscapi/windows/native/libsunmscapi/security.cpp --- a/jdk/src/jdk.crypto.mscapi/windows/native/libsunmscapi/security.cpp Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/jdk.crypto.mscapi/windows/native/libsunmscapi/security.cpp Tue Apr 05 15:39:35 2016 -0400 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -272,7 +272,7 @@ * Signature: (Ljava/lang/String;Ljava/util/Collection;)V */ JNIEXPORT void JNICALL Java_sun_security_mscapi_KeyStore_loadKeysOrCertificateChains - (JNIEnv *env, jobject obj, jstring jCertStoreName, jobject jCollections) + (JNIEnv *env, jobject obj, jstring jCertStoreName) { /** * Certificate in cert store has enhanced key usage extension @@ -331,7 +331,7 @@ // Determine method ID to generate certificate chain jmethodID mGenCertChain = env->GetMethodID(clazzOfThis, "generateCertificateChain", - "(Ljava/lang/String;Ljava/util/Collection;Ljava/util/Collection;)V"); + "(Ljava/lang/String;Ljava/util/Collection;)V"); if (mGenCertChain == NULL) { __leave; } @@ -339,7 +339,7 @@ // Determine method ID to generate RSA certificate chain jmethodID mGenRSAKeyAndCertChain = env->GetMethodID(clazzOfThis, "generateRSAKeyAndCertificateChain", - "(Ljava/lang/String;JJILjava/util/Collection;Ljava/util/Collection;)V"); + "(Ljava/lang/String;JJILjava/util/Collection;)V"); if (mGenRSAKeyAndCertChain == NULL) { __leave; } @@ -366,38 +366,37 @@ } else { // Private key is available - BOOL bGetUserKey = ::CryptGetUserKey(hCryptProv, dwKeySpec, &hUserKey); + BOOL bGetUserKey = ::CryptGetUserKey(hCryptProv, dwKeySpec, &hUserKey); - // Skip certificate if cannot find private key - if (bGetUserKey == FALSE) - { - if (bCallerFreeProv) - ::CryptReleaseContext(hCryptProv, NULL); + // Skip certificate if cannot find private key + if (bGetUserKey == FALSE) + { + if (bCallerFreeProv) + ::CryptReleaseContext(hCryptProv, NULL); - continue; - } + continue; + } - // Set cipher mode to ECB - DWORD dwCipherMode = CRYPT_MODE_ECB; - ::CryptSetKeyParam(hUserKey, KP_MODE, (BYTE*)&dwCipherMode, NULL); + // Set cipher mode to ECB + DWORD dwCipherMode = CRYPT_MODE_ECB; + ::CryptSetKeyParam(hUserKey, KP_MODE, (BYTE*)&dwCipherMode, NULL); - // If the private key is present in smart card, we may not be able to - // determine the key length by using the private key handle. However, - // since public/private key pairs must have the same length, we could - // determine the key length of the private key by using the public key - // in the certificate. - dwPublicKeyLength = ::CertGetPublicKeyLength(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, - &(pCertContext->pCertInfo->SubjectPublicKeyInfo)); + // If the private key is present in smart card, we may not be able to + // determine the key length by using the private key handle. However, + // since public/private key pairs must have the same length, we could + // determine the key length of the private key by using the public key + // in the certificate. + dwPublicKeyLength = ::CertGetPublicKeyLength(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, + &(pCertContext->pCertInfo->SubjectPublicKeyInfo)); -} + } PCCERT_CHAIN_CONTEXT pCertChainContext = NULL; // Build certificate chain by using system certificate store. // Add cert chain into collection for any key usage. // - if (GetCertificateChain(OID_EKU_ANY, pCertContext, - &pCertChainContext)) + if (GetCertificateChain(OID_EKU_ANY, pCertContext, &pCertChainContext)) { for (unsigned int i=0; i < pCertChainContext->cChain; i++) @@ -456,26 +455,26 @@ // collection env->CallVoidMethod(obj, mGenCertChain, env->NewStringUTF(pszNameString), - jArrayList, jCollections); + jArrayList); } else { - // Determine key type: RSA or DSA - DWORD dwData = CALG_RSA_KEYX; - DWORD dwSize = sizeof(DWORD); - ::CryptGetKeyParam(hUserKey, KP_ALGID, (BYTE*)&dwData, - &dwSize, NULL); + // Determine key type: RSA or DSA + DWORD dwData = CALG_RSA_KEYX; + DWORD dwSize = sizeof(DWORD); + ::CryptGetKeyParam(hUserKey, KP_ALGID, (BYTE*)&dwData, + &dwSize, NULL); - if ((dwData & ALG_TYPE_RSA) == ALG_TYPE_RSA) - { - // Generate RSA certificate chain and store into cert - // chain collection - env->CallVoidMethod(obj, mGenRSAKeyAndCertChain, - env->NewStringUTF(pszNameString), - (jlong) hCryptProv, (jlong) hUserKey, - dwPublicKeyLength, jArrayList, jCollections); + if ((dwData & ALG_TYPE_RSA) == ALG_TYPE_RSA) + { + // Generate RSA certificate chain and store into cert + // chain collection + env->CallVoidMethod(obj, mGenRSAKeyAndCertChain, + env->NewStringUTF(pszNameString), + (jlong) hCryptProv, (jlong) hUserKey, + dwPublicKeyLength, jArrayList); + } } -} } // Free cert chain diff -r 64f6ae06310e -r eda408d4f253 jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java --- a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java Tue Apr 05 15:39:35 2016 -0400 @@ -51,8 +51,8 @@ import jdk.internal.module.Hasher; import jdk.internal.module.ModuleInfoExtender; -import sun.misc.JarIndex; -import static sun.misc.JarIndex.INDEX_NAME; +import jdk.internal.util.jar.JarIndex; +import static jdk.internal.util.jar.JarIndex.INDEX_NAME; import static java.util.jar.JarFile.MANIFEST_NAME; import static java.util.stream.Collectors.joining; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; diff -r 64f6ae06310e -r eda408d4f253 jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ImageFileCreator.java --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ImageFileCreator.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ImageFileCreator.java Tue Apr 05 15:39:35 2016 -0400 @@ -46,6 +46,7 @@ import jdk.tools.jlink.internal.Archive.Entry.EntryType; import jdk.tools.jlink.internal.PoolImpl.CompressedModuleData; import jdk.tools.jlink.plugin.ExecutableImage; +import jdk.tools.jlink.plugin.PluginException; import jdk.tools.jlink.plugin.Pool; import jdk.tools.jlink.plugin.Pool.ModuleData; import jdk.tools.jlink.plugin.Pool.ModuleDataType; @@ -183,6 +184,8 @@ PoolImpl resultResources; try { resultResources = pluginSupport.visitResources(allContent); + } catch (PluginException pe) { + throw pe; } catch (Exception ex) { throw new IOException(ex); } diff -r 64f6ae06310e -r eda408d4f253 jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/GenerateJLIClassesPlugin.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/GenerateJLIClassesPlugin.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.tools.jlink.internal.plugins; + +import java.io.ByteArrayInputStream; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import jdk.tools.jlink.plugin.PluginException; +import jdk.tools.jlink.plugin.Pool; +import jdk.tools.jlink.plugin.TransformerPlugin; + +/** + * Plugin to generate java.lang.invoke classes. + */ +public final class GenerateJLIClassesPlugin implements TransformerPlugin { + + private static final String NAME = "generate-jli-classes"; + + private static final String BMH_PARAM = "bmh"; + + private static final String BMH_SPECIES_PARAM = "bmh-species"; + + private static final String DESCRIPTION = PluginsResourceBundle.getDescription(NAME); + + private static final String BMH = "java/lang/invoke/BoundMethodHandle"; + + private static final Method FACTORY_METHOD; + + List speciesTypes; + + public GenerateJLIClassesPlugin() { + } + + @Override + public Set getType() { + return Collections.singleton(CATEGORY.TRANSFORMER); + } + + @Override + public String getName() { + return NAME; + } + + @Override + public String getDescription() { + return DESCRIPTION; + } + + @Override + public Set getState() { + return EnumSet.of(STATE.AUTO_ENABLED, STATE.FUNCTIONAL); + } + + @Override + public boolean hasArguments() { + return true; + } + + @Override + public String getArgumentsDescription() { + return PluginsResourceBundle.getArgument(NAME); + } + + /** + * @return the default Species forms to generate. + * + * This list was derived from running a Java concatenating strings + * with -Djava.lang.invoke.stringConcat=MH_INLINE_SIZED_EXACT set + * plus a subset of octane. A better long-term solution is to define + * and run a set of quick generators and extracting this list as a + * step in the build process. + */ + public static List defaultSpecies() { + return List.of("LL", "L3", "L4", "L5", "L6", "L7", "L7I", + "L7II", "L7IIL", "L8", "L9", "L10", "L11", "L11I", "L11II", + "L12", "L13", "LI", "D", "L3I", "LIL", "LLI", "LLIL", + "LILL", "I", "LLILL"); + } + + @Override + public void configure(Map config) { + String mainArgument = config.get(NAME); + + // Enable by default + boolean bmhEnabled = true; + if (mainArgument != null) { + Set args = Arrays.stream(mainArgument.split(",")) + .collect(Collectors.toSet()); + if (!args.contains(BMH_PARAM)) { + bmhEnabled = false; + } + } + + if (!bmhEnabled) { + speciesTypes = List.of(); + } else { + String args = config.get(BMH_SPECIES_PARAM); + List bmhSpecies; + if (args != null && !args.isEmpty()) { + bmhSpecies = Arrays.stream(args.split(",")) + .map(String::trim) + .filter(s -> !s.isEmpty()) + .collect(Collectors.toList()); + } else { + bmhSpecies = defaultSpecies(); + } + + // Expand BMH species signatures + speciesTypes = bmhSpecies.stream() + .map(type -> expandSignature(type)) + .collect(Collectors.toList()); + + // Validation check + for (String type : speciesTypes) { + for (char c : type.toCharArray()) { + if ("LIJFD".indexOf(c) < 0) { + throw new PluginException("All characters must " + + "correspond to a basic field type: LIJFD"); + } + } + } + } + } + + @Override + public void visit(Pool in, Pool out) { + for (Pool.ModuleData data : in.getContent()) { + if (("/java.base/" + BMH + ".class").equals(data.getPath())) { + // Add BoundMethodHandle unchanged + out.add(data); + speciesTypes.forEach(types -> generateConcreteClass(types, data, out)); + } else { + if (!out.contains(data)) { + out.add(data); + } + } + } + } + + @SuppressWarnings("unchecked") + private void generateConcreteClass(String types, Pool.ModuleData data, Pool out) { + try { + // Generate class + Map.Entry result = (Map.Entry) + FACTORY_METHOD.invoke(null, types); + String className = result.getKey(); + byte[] bytes = result.getValue(); + + // Add class to pool + Pool.ModuleData ndata = new Pool.ModuleData(data.getModule(), + "/java.base/" + className + ".class", + Pool.ModuleDataType.CLASS_OR_RESOURCE, + new ByteArrayInputStream(bytes), bytes.length); + if (!out.contains(ndata)) { + out.add(ndata); + } + } catch (Exception ex) { + throw new PluginException(ex); + } + } + + static { + try { + Class BMHFactory = Class.forName("java.lang.invoke.BoundMethodHandle$Factory"); + Method genClassMethod = BMHFactory.getDeclaredMethod("generateConcreteBMHClassBytes", + String.class); + genClassMethod.setAccessible(true); + FACTORY_METHOD = genClassMethod; + } catch (Exception e) { + throw new PluginException(e); + } + } + + // Convert LL -> LL, L3 -> LLL + private static String expandSignature(String signature) { + StringBuilder sb = new StringBuilder(); + char last = 'X'; + int count = 0; + for (int i = 0; i < signature.length(); i++) { + char c = signature.charAt(i); + if (c >= '0' && c <= '9') { + count *= 10; + count += (c - '0'); + } else { + for (int j = 1; j < count; j++) { + sb.append(last); + } + sb.append(c); + last = c; + count = 0; + } + } + for (int j = 1; j < count; j++) { + sb.append(last); + } + return sb.toString(); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/IncludeLocalesPlugin.java --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/IncludeLocalesPlugin.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/IncludeLocalesPlugin.java Tue Apr 05 15:39:35 2016 -0400 @@ -92,6 +92,7 @@ "*sun/text/resources/cldr/ext/[^\\/]+_%%.class," + "*sun/util/resources/cldr/ext/[^\\/]+_%%.class,"; private Predicate predicate; + private String userParam; private List priorityList; private List available; private List filtered; @@ -155,13 +156,17 @@ @Override public void configure(Map config) { - try { - priorityList = Arrays.stream(config.get(NAME).split(",")) - .map(Locale.LanguageRange::new) - .collect(Collectors.toList()); - } catch (IllegalArgumentException iae) { - throw new PluginException(iae.getLocalizedMessage()); - } + userParam = config.get(NAME); + priorityList = Arrays.stream(userParam.split(",")) + .map(s -> { + try { + return new Locale.LanguageRange(s); + } catch (IllegalArgumentException iae) { + throw new PluginException(String.format( + PluginsResourceBundle.getMessage(NAME + ".invalidtag"), s)); + } + }) + .collect(Collectors.toList()); } @Override @@ -191,7 +196,8 @@ filtered = filterLocales(available); if (filtered.isEmpty()) { - throw new PluginException(PluginsResourceBundle.getMessage(NAME + ".nomatchinglocales")); + throw new PluginException( + String.format(PluginsResourceBundle.getMessage(NAME + ".nomatchinglocales"), userParam)); } try { diff -r 64f6ae06310e -r eda408d4f253 jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties Tue Apr 05 15:39:35 2016 -0400 @@ -20,7 +20,7 @@ Level 1: ZIP\n\ Level 2: both.\n\ An optional filter can be specified to list the pattern of files to be filtered.\n\ -Use ^ for negation. eg: *Exception.class,*Error.class,^/java.base/java/lang/* +Use ^ for negation. e.g.: *Exception.class,*Error.class,^/java.base/java/lang/* compact-cp.argument= @@ -32,17 +32,22 @@ copy-files.description=\ If files to copy are not absolute path, JDK home dir is used.\n\ -eg: jrt-fs.jar,LICENSE,/home/me/myfile.txt=somewehere/conf.txt +e.g.: jrt-fs.jar,LICENSE,/home/me/myfile.txt=somewehere/conf.txt exclude-files.argument= exclude-files.description=\ -Specify files to exclude. eg: *.diz, /java.base/native/client/* +Specify files to exclude. e.g.: *.diz, /java.base/native/client/* exclude-resources.argument= exclude-resources.description=\ -Specify resources to exclude. eg: *.jcov, */META-INF/* +Specify resources to exclude. e.g.: *.jcov, */META-INF/* + +generate-jli-classes.argument= + +generate-jli-classes.description=\ +Concrete java.lang.invoke classes to generate installed-modules.description=Fast loading of module descriptors (always enabled) @@ -51,7 +56,7 @@ sort-resources.argument= sort-resources.description=\ -Sort resources. eg: */modules-info.class,/java-base/java/lang/* +Sort resources. e.g.: */modules-info.class,/java-base/java/lang/* strip-debug.description=\ Strip debug information from the output image @@ -73,13 +78,16 @@ include-locales.description=\ BCP 47 language tags separated by a comma, allowing locale matching\n\ -defined in RFC 4647. eg: en,ja,*-IN +defined in RFC 4647. e.g.: en,ja,*-IN include-locales.missingpackages=\ Missing locale data packages in jdk.localedata:\n\t include-locales.nomatchinglocales=\ -No matching locales found. Check the specified pattern. +No matching locales found for \"%s\". Check the specified pattern. + +include-locales.invalidtag=\ +Invalid language tag: %s main.status.ok=Functional. diff -r 64f6ae06310e -r eda408d4f253 jdk/src/jdk.jlink/share/classes/module-info.java --- a/jdk/src/jdk.jlink/share/classes/module-info.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/jdk.jlink/share/classes/module-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -45,5 +45,6 @@ provides jdk.tools.jlink.plugin.TransformerPlugin with jdk.tools.jlink.internal.plugins.OptimizationPlugin; provides jdk.tools.jlink.plugin.TransformerPlugin with jdk.tools.jlink.internal.plugins.ExcludeVMPlugin; provides jdk.tools.jlink.plugin.TransformerPlugin with jdk.tools.jlink.internal.plugins.IncludeLocalesPlugin; + provides jdk.tools.jlink.plugin.TransformerPlugin with jdk.tools.jlink.internal.plugins.GenerateJLIClassesPlugin; provides jdk.tools.jlink.plugin.PostProcessorPlugin with jdk.tools.jlink.internal.plugins.ReleaseInfoPlugin; } diff -r 64f6ae06310e -r eda408d4f253 jdk/src/jdk.localedata/share/classes/sun/util/resources/provider/LocaleDataProvider.java --- a/jdk/src/jdk.localedata/share/classes/sun/util/resources/provider/LocaleDataProvider.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/jdk.localedata/share/classes/sun/util/resources/provider/LocaleDataProvider.java Tue Apr 05 15:39:35 2016 -0400 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,34 +25,33 @@ package sun.util.resources.provider; -import java.lang.reflect.Module; import java.util.Locale; import java.util.ResourceBundle; -import sun.util.locale.provider.ResourceBundleProviderSupport; import sun.util.resources.LocaleData; /** - * {@code LocaleDataProvider} in module jdk.localedata implements - * {@code LocaleDataBundleProvider} in module java.base. This class works as a - * service agent between {@code ResourceBundle.getBundle} callers in java.base - * and resource bundles in jdk.localedata. + * Service Provider for loading locale data resource bundles in jdk.localedata + * except for JavaTimeSupplementary resource bundles. */ public class LocaleDataProvider extends LocaleData.CommonResourceBundleProvider { @Override - protected boolean isSupportedInModule(String baseName, Locale locale) { - // The assumption here is that there are two modules containing - // resource bundles for locale support. If resource bundles are split - // into more modules, this method will need to be changed to determine - // what locales are exactly supported. - return !super.isSupportedInModule(baseName, locale); + public ResourceBundle getBundle(String baseName, Locale locale) { + return loadResourceBundle(toBundleName(baseName, locale)); } - @Override - public ResourceBundle getBundle(String baseName, Locale locale) { - if (isSupportedInModule(baseName, locale)) { - Module module = LocaleDataProvider.class.getModule(); - String bundleName = toBundleName(baseName, locale); - return ResourceBundleProviderSupport.loadResourceBundle(module, bundleName); + /** + * Utility method for loading a resource bundle in jdk.localedata. + */ + static ResourceBundle loadResourceBundle(String bundleName) { + Class c = Class.forName(LocaleDataProvider.class.getModule(), bundleName); + if (c != null && ResourceBundle.class.isAssignableFrom(c)) { + try { + @SuppressWarnings("unchecked") + ResourceBundle rb = ((Class) c).newInstance(); + return rb; + } catch (InstantiationException | IllegalAccessException e) { + throw new InternalError(e); + } } return null; } diff -r 64f6ae06310e -r eda408d4f253 jdk/src/jdk.localedata/share/classes/sun/util/resources/provider/SupplementaryLocaleDataProvider.java --- a/jdk/src/jdk.localedata/share/classes/sun/util/resources/provider/SupplementaryLocaleDataProvider.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/src/jdk.localedata/share/classes/sun/util/resources/provider/SupplementaryLocaleDataProvider.java Tue Apr 05 15:39:35 2016 -0400 @@ -25,33 +25,16 @@ package sun.util.resources.provider; -import java.lang.reflect.Module; import java.util.Locale; import java.util.ResourceBundle; - -import sun.util.locale.provider.ResourceBundleProviderSupport; import sun.util.resources.LocaleData; /** - * {@code SupplementaryLocaleDataProvider} in module jdk.localedata implements - * {@code JavaTimeSupplementaryProvider} in module java.base. This class works as a - * service agent between {@code ResourceBundle.getBundle} callers in java.base - * and resource bundles in jdk.localedata. + * Service Provider for loading JavaTimeSupplementary resource bundles in jdk.localedata. */ public class SupplementaryLocaleDataProvider extends LocaleData.SupplementaryResourceBundleProvider { @Override - protected boolean isSupportedInModule(String baseName, Locale locale) { - // The assumption here is that there are two modules containing - // resource bundles for locale support. If resource bundles are split - // into more modules, this method will need to be changed to determine - // what locales are exactly supported. - return !super.isSupportedInModule(baseName, locale); - } - - @Override public ResourceBundle getBundle(String baseName, Locale locale) { - Module module = LocaleDataProvider.class.getModule(); - String bundleName = toBundleName(baseName, locale); - return ResourceBundleProviderSupport.loadResourceBundle(module, bundleName); + return LocaleDataProvider.loadResourceBundle(toBundleName(baseName, locale)); } } diff -r 64f6ae06310e -r eda408d4f253 jdk/test/Makefile --- a/jdk/test/Makefile Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/test/Makefile Tue Apr 05 15:39:35 2016 -0400 @@ -302,6 +302,8 @@ # Set the max memory for jtreg control vm JTREG_MEMORY_OPTION = -J-Xmx512m JTREG_BASIC_OPTIONS += $(JTREG_MEMORY_OPTION) +# Give tests access to JT_JAVA, see JDK-8141609 +JTREG_BASIC_OPTIONS += -e:JDK8_HOME=${JT_JAVA} # Add any extra options JTREG_BASIC_OPTIONS += $(EXTRA_JTREG_OPTIONS) # Set other vm and test options diff -r 64f6ae06310e -r eda408d4f253 jdk/test/ProblemList.txt --- a/jdk/test/ProblemList.txt Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/test/ProblemList.txt Tue Apr 05 15:39:35 2016 -0400 @@ -116,221 +116,184 @@ # jdk_beans -# 8060027 -java/beans/XMLEncoder/Test4903007.java generic-all -java/beans/XMLEncoder/java_awt_GridBagLayout.java generic-all -java/beans/XMLDecoder/8028054/TestConstructorFinder.java generic-all -java/beans/XMLDecoder/8028054/TestMethodFinder.java generic-all +java/beans/XMLEncoder/Test4903007.java 8060027 generic-all +java/beans/XMLEncoder/java_awt_GridBagLayout.java 8060027 generic-all +java/beans/XMLDecoder/8028054/TestConstructorFinder.java 8060027 generic-all +java/beans/XMLDecoder/8028054/TestMethodFinder.java 8060027 generic-all -# 8132565 -java/beans/Introspector/8132566/OverridePropertyInfoTest.java generic-all -java/beans/Introspector/8132566/OverrideUserDefPropertyInfoTest.java generic-all +java/beans/Introspector/8132566/OverridePropertyInfoTest.java 8132565 generic-all +java/beans/Introspector/8132566/OverrideUserDefPropertyInfoTest.java 8132565 generic-all ############################################################################ # jdk_lang -# 8029891 -java/lang/ClassLoader/deadlock/GetResource.java generic-all +java/lang/ClassLoader/deadlock/GetResource.java 8029891 generic-all -# 7008363 -java/lang/StringCoding/CheckEncodings.sh generic-all +java/lang/StringCoding/CheckEncodings.sh 7008363 generic-all ############################################################################ # jdk_instrument -# 8061177 -java/lang/instrument/RedefineBigClass.sh generic-all -java/lang/instrument/RetransformBigClass.sh generic-all +java/lang/instrument/RedefineBigClass.sh 8061177 generic-all +java/lang/instrument/RetransformBigClass.sh 8061177 generic-all -# 8072130 -java/lang/instrument/BootClassPath/BootClassPathTest.sh macosx-all +java/lang/instrument/BootClassPath/BootClassPathTest.sh 8072130 macosx-all -# 8130339 -java/lang/management/MemoryMXBean/LowMemoryTest.java generic-all +java/lang/management/MemoryMXBean/LowMemoryTest.java 8130339 generic-all ############################################################################ # jdk_jmx -# 8030957 -com/sun/management/OperatingSystemMXBean/GetProcessCpuLoad.java aix-all -com/sun/management/OperatingSystemMXBean/GetSystemCpuLoad.java aix-all -javax/management/MBeanServer/OldMBeanServerTest.java aix-all +com/sun/management/OperatingSystemMXBean/GetProcessCpuLoad.java 8030957 aix-all +com/sun/management/OperatingSystemMXBean/GetSystemCpuLoad.java 8030957 aix-all +javax/management/MBeanServer/OldMBeanServerTest.java 8030957 aix-all -# 8042215 -javax/management/remote/mandatory/notif/NotifReconnectDeadlockTest.java generic-all +javax/management/remote/mandatory/notif/NotifReconnectDeadlockTest.java 8042215 generic-all -# 8147985 -sun/management/jmxremote/bootstrap/JMXInterfaceBindingTest.java generic-all +sun/management/jmxremote/bootstrap/JMXInterfaceBindingTest.java 8147985 generic-all ############################################################################ # jdk_net -# 7148829 -sun/net/InetAddress/nameservice/simple/CacheTest.java generic-all -sun/net/InetAddress/nameservice/simple/DefaultCaching.java generic-all +sun/net/InetAddress/nameservice/simple/CacheTest.java 7148829 generic-all +sun/net/InetAddress/nameservice/simple/DefaultCaching.java 7148829 generic-all -# 7122846 -java/net/MulticastSocket/NoLoopbackPackets.java macosx-all -java/net/MulticastSocket/SetLoopbackMode.java macosx-all +java/net/MulticastSocket/NoLoopbackPackets.java 7122846 macosx-all +java/net/MulticastSocket/SetLoopbackMode.java 7122846 macosx-all -# 7145658 -java/net/MulticastSocket/Test.java macosx-all +java/net/MulticastSocket/Test.java 7145658 macosx-all -# 7143960 -java/net/DatagramSocket/SendDatagramToBadAddress.java macosx-all +java/net/DatagramSocket/SendDatagramToBadAddress.java 7143960 macosx-all ############################################################################ # jdk_nio -# 6963118 -java/nio/channels/Selector/Wakeup.java windows-all +java/nio/channels/Selector/Wakeup.java 6963118 windows-all -# 7141822 -java/nio/channels/DatagramChannel/ChangingAddress.java macosx-all +java/nio/channels/DatagramChannel/ChangingAddress.java 7141822 macosx-all + +java/nio/channels/Selector/OutOfBand.java 7132677 macosx-all -# 7132677 -java/nio/channels/Selector/OutOfBand.java macosx-all +java/nio/file/WatchService/Basic.java 7158947 solaris-all Solaris 11 +java/nio/file/WatchService/MayFlies.java 7158947 solaris-all Solaris 11 +java/nio/file/WatchService/LotsOfEvents.java 7158947 solaris-all Solaris 11 -# 7158947, Solaris 11 -java/nio/file/WatchService/Basic.java solaris-all -java/nio/file/WatchService/MayFlies.java solaris-all -java/nio/file/WatchService/LotsOfEvents.java solaris-all - -# 8149712 -java/nio/charset/coders/BashStreams.java generic-all +java/nio/charset/coders/BashStreams.java 8149712 generic-all ############################################################################ # jdk_rmi -# 7140992 -java/rmi/server/Unreferenced/finiteGCLatency/FiniteGCLatency.java generic-all +java/rmi/server/Unreferenced/finiteGCLatency/FiniteGCLatency.java 7140992 generic-all -# 7146541 -java/rmi/transport/rapidExportUnexport/RapidExportUnexport.java linux-all +java/rmi/transport/rapidExportUnexport/RapidExportUnexport.java 7146541 linux-all -# 7191877 -java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java generic-all +java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java 7191877 generic-all -# 7195095 -sun/rmi/transport/proxy/EagerHttpFallback.java generic-all +sun/rmi/transport/proxy/EagerHttpFallback.java 7195095 generic-all -# 8062724 -java/rmi/activation/Activatable/extLoadedImpl/ext.sh generic-all +java/rmi/activation/Activatable/extLoadedImpl/ext.sh 8062724 generic-all -# 8145980 -sun/rmi/rmic/newrmic/equivalence/run.sh generic-all +sun/rmi/rmic/newrmic/equivalence/run.sh 8145980 generic-all ############################################################################ # jdk_security -# 7157786 -sun/security/pkcs11/ec/TestKeyFactory.java generic-all +sun/security/pkcs11/ec/TestKeyFactory.java 7157786 generic-all -# 7164518: no PortUnreachableException on Mac -sun/security/krb5/auto/Unreachable.java macosx-all +sun/security/krb5/auto/Unreachable.java 7164518 macosx-all no PortUnreachableException on Mac -# 7041639: Solaris DSA keypair generation bug -java/security/KeyPairGenerator/SolarisShortDSA.java solaris-all -sun/security/tools/keytool/standard.sh solaris-all +java/security/KeyPairGenerator/SolarisShortDSA.java 7041639 solaris-all +sun/security/tools/keytool/standard.sh 7041639 solaris-all -# 8062758 -java/security/Security/ClassLoaderDeadlock/Deadlock2.sh generic-all +java/security/Security/ClassLoaderDeadlock/Deadlock2.sh 8062758 generic-all -# 8026393 -sun/security/tools/jarsigner/warnings/BadKeyUsageTest.java generic-all +sun/security/tools/jarsigner/warnings/BadKeyUsageTest.java 8026393 generic-all -# 8077138: Some PKCS11 tests fail because NSS library is not initialized -# 8023434: NSS initialization failed -sun/security/pkcs11/Cipher/ReinitCipher.java windows-all -sun/security/pkcs11/Cipher/TestPKCS5PaddingError.java windows-all -sun/security/pkcs11/Cipher/TestRSACipher.java windows-all -sun/security/pkcs11/Cipher/TestRSACipherWrap.java windows-all -sun/security/pkcs11/Cipher/TestRawRSACipher.java windows-all -sun/security/pkcs11/Cipher/TestSymmCiphers.java windows-all -sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java windows-all -sun/security/pkcs11/KeyAgreement/TestDH.java windows-all -sun/security/pkcs11/KeyAgreement/TestInterop.java windows-all -sun/security/pkcs11/KeyAgreement/TestShort.java windows-all -sun/security/pkcs11/KeyGenerator/DESParity.java windows-all -sun/security/pkcs11/KeyGenerator/TestKeyGenerator.java windows-all -sun/security/pkcs11/KeyPairGenerator/TestDH2048.java windows-all -sun/security/pkcs11/KeyStore/SecretKeysBasic.sh windows-all -sun/security/pkcs11/Mac/MacKAT.java windows-all -sun/security/pkcs11/Mac/MacSameTest.java windows-all -sun/security/pkcs11/Mac/ReinitMac.java windows-all -sun/security/pkcs11/MessageDigest/ByteBuffers.java windows-all -sun/security/pkcs11/MessageDigest/DigestKAT.java windows-all -sun/security/pkcs11/MessageDigest/ReinitDigest.java windows-all -sun/security/pkcs11/MessageDigest/TestCloning.java windows-all -sun/security/pkcs11/Provider/ConfigQuotedString.sh windows-all -sun/security/pkcs11/Provider/Login.sh windows-all -sun/security/pkcs11/SampleTest.java windows-all -sun/security/pkcs11/Secmod/AddPrivateKey.java windows-all -sun/security/pkcs11/Secmod/AddTrustedCert.java windows-all -sun/security/pkcs11/Secmod/Crypto.java windows-all -sun/security/pkcs11/Secmod/GetPrivateKey.java windows-all -sun/security/pkcs11/Secmod/JksSetPrivateKey.java windows-all -sun/security/pkcs11/Secmod/LoadKeystore.java windows-all -sun/security/pkcs11/SecureRandom/Basic.java windows-all -sun/security/pkcs11/SecureRandom/TestDeserialization.java windows-all -sun/security/pkcs11/Serialize/SerializeProvider.java windows-all -sun/security/pkcs11/Signature/ByteBuffers.java windows-all -sun/security/pkcs11/Signature/ReinitSignature.java windows-all -sun/security/pkcs11/Signature/TestDSA.java windows-all -sun/security/pkcs11/Signature/TestDSAKeyLength.java windows-all -sun/security/pkcs11/Signature/TestRSAKeyLength.java windows-all -sun/security/pkcs11/ec/ReadCertificates.java windows-all -sun/security/pkcs11/ec/ReadPKCS12.java windows-all -sun/security/pkcs11/ec/TestCurves.java windows-all -sun/security/pkcs11/ec/TestECDH.java windows-all -sun/security/pkcs11/ec/TestECDH2.java windows-all -sun/security/pkcs11/ec/TestECDSA.java windows-all -sun/security/pkcs11/ec/TestECDSA2.java windows-all -sun/security/pkcs11/ec/TestECGenSpec.java windows-all -sun/security/pkcs11/rsa/KeyWrap.java windows-all -sun/security/pkcs11/rsa/TestCACerts.java windows-all -sun/security/pkcs11/rsa/TestKeyFactory.java windows-all -sun/security/pkcs11/rsa/TestKeyPairGenerator.java windows-all -sun/security/pkcs11/rsa/TestSignatures.java windows-all -sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java windows-all -sun/security/pkcs11/tls/TestKeyMaterial.java windows-all -sun/security/pkcs11/tls/TestLeadingZeroesP11.java windows-all -sun/security/pkcs11/tls/TestMasterSecret.java windows-all -sun/security/pkcs11/tls/TestPRF.java windows-all -sun/security/pkcs11/tls/TestPremaster.java windows-all +sun/security/pkcs11/Cipher/ReinitCipher.java 8077138,8023434 windows-all +sun/security/pkcs11/Cipher/TestPKCS5PaddingError.java 8077138,8023434 windows-all +sun/security/pkcs11/Cipher/TestRSACipher.java 8077138,8023434 windows-all +sun/security/pkcs11/Cipher/TestRSACipherWrap.java 8077138,8023434 windows-all +sun/security/pkcs11/Cipher/TestRawRSACipher.java 8077138,8023434 windows-all +sun/security/pkcs11/Cipher/TestSymmCiphers.java 8077138,8023434 windows-all +sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java 8077138,8023434 windows-all +sun/security/pkcs11/KeyAgreement/TestDH.java 8077138,8023434 windows-all +sun/security/pkcs11/KeyAgreement/TestInterop.java 8077138,8023434 windows-all +sun/security/pkcs11/KeyAgreement/TestShort.java 8077138,8023434 windows-all +sun/security/pkcs11/KeyGenerator/DESParity.java 8077138,8023434 windows-all +sun/security/pkcs11/KeyGenerator/TestKeyGenerator.java 8077138,8023434 windows-all +sun/security/pkcs11/KeyPairGenerator/TestDH2048.java 8077138,8023434 windows-all +sun/security/pkcs11/KeyStore/SecretKeysBasic.sh 8077138,8023434 windows-all +sun/security/pkcs11/Mac/MacKAT.java 8077138,8023434 windows-all +sun/security/pkcs11/Mac/MacSameTest.java 8077138,8023434 windows-all +sun/security/pkcs11/Mac/ReinitMac.java 8077138,8023434 windows-all +sun/security/pkcs11/MessageDigest/ByteBuffers.java 8077138,8023434 windows-all +sun/security/pkcs11/MessageDigest/DigestKAT.java 8077138,8023434 windows-all +sun/security/pkcs11/MessageDigest/ReinitDigest.java 8077138,8023434 windows-all +sun/security/pkcs11/MessageDigest/TestCloning.java 8077138,8023434 windows-all +sun/security/pkcs11/Provider/ConfigQuotedString.sh 8077138,8023434 windows-all +sun/security/pkcs11/Provider/Login.sh 8077138,8023434 windows-all +sun/security/pkcs11/SampleTest.java 8077138,8023434 windows-all +sun/security/pkcs11/Secmod/AddPrivateKey.java 8077138,8023434 windows-all +sun/security/pkcs11/Secmod/AddTrustedCert.java 8077138,8023434 windows-all +sun/security/pkcs11/Secmod/Crypto.java 8077138,8023434 windows-all +sun/security/pkcs11/Secmod/GetPrivateKey.java 8077138,8023434 windows-all +sun/security/pkcs11/Secmod/JksSetPrivateKey.java 8077138,8023434 windows-all +sun/security/pkcs11/Secmod/LoadKeystore.java 8077138,8023434 windows-all +sun/security/pkcs11/SecureRandom/Basic.java 8077138,8023434 windows-all +sun/security/pkcs11/SecureRandom/TestDeserialization.java 8077138,8023434 windows-all +sun/security/pkcs11/Serialize/SerializeProvider.java 8077138,8023434 windows-all +sun/security/pkcs11/Signature/ByteBuffers.java 8077138,8023434 windows-all +sun/security/pkcs11/Signature/ReinitSignature.java 8077138,8023434 windows-all +sun/security/pkcs11/Signature/TestDSA.java 8077138,8023434 windows-all +sun/security/pkcs11/Signature/TestDSAKeyLength.java 8077138,8023434 windows-all +sun/security/pkcs11/Signature/TestRSAKeyLength.java 8077138,8023434 windows-all +sun/security/pkcs11/ec/ReadCertificates.java 8077138,8023434 windows-all +sun/security/pkcs11/ec/ReadPKCS12.java 8077138,8023434 windows-all +sun/security/pkcs11/ec/TestCurves.java 8077138,8023434 windows-all +sun/security/pkcs11/ec/TestECDH.java 8077138,8023434 windows-all +sun/security/pkcs11/ec/TestECDH2.java 8077138,8023434 windows-all +sun/security/pkcs11/ec/TestECDSA.java 8077138,8023434 windows-all +sun/security/pkcs11/ec/TestECDSA2.java 8077138,8023434 windows-all +sun/security/pkcs11/ec/TestECGenSpec.java 8077138,8023434 windows-all +sun/security/pkcs11/rsa/KeyWrap.java 8077138,8023434 windows-all +sun/security/pkcs11/rsa/TestCACerts.java 8077138,8023434 windows-all +sun/security/pkcs11/rsa/TestKeyFactory.java 8077138,8023434 windows-all +sun/security/pkcs11/rsa/TestKeyPairGenerator.java 8077138,8023434 windows-all +sun/security/pkcs11/rsa/TestSignatures.java 8077138,8023434 windows-all +sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java 8077138,8023434 windows-all +sun/security/pkcs11/tls/TestKeyMaterial.java 8077138,8023434 windows-all +sun/security/pkcs11/tls/TestLeadingZeroesP11.java 8077138,8023434 windows-all +sun/security/pkcs11/tls/TestMasterSecret.java 8077138,8023434 windows-all +sun/security/pkcs11/tls/TestPRF.java 8077138,8023434 windows-all +sun/security/pkcs11/tls/TestPremaster.java 8077138,8023434 windows-all -# 8051770 -sun/security/provider/SecureRandom/StrongSecureRandom.java macosx-10.10 +sun/security/provider/SecureRandom/StrongSecureRandom.java 8051770 macosx-10.10 -# 8074580 -sun/security/pkcs11/rsa/TestKeyPairGenerator.java generic-all +sun/security/pkcs11/rsa/TestKeyPairGenerator.java 8074580 generic-all -# 8038079 -sun/security/krb5/auto/HttpNegotiateServer.java generic-all +sun/security/krb5/auto/HttpNegotiateServer.java 8038079 generic-all -# 8130302 -sun/security/tools/keytool/autotest.sh generic-all +sun/security/tools/keytool/autotest.sh 8130302 generic-all ############################################################################ # jdk_sound -# 8059743 -javax/sound/midi/Gervill/SoftProvider/GetDevice.java generic-all +javax/sound/midi/Gervill/SoftProvider/GetDevice.java 8059743 generic-all ############################################################################ # jdk_imageio -javax/imageio/plugins/shared/CanWriteSequence.java generic-all -javax/imageio/plugins/tiff/MultiPageTest/MultiPageTest.java generic-all -javax/imageio/plugins/tiff/WriteToSequenceAfterAbort.java generic-all +javax/imageio/plugins/shared/CanWriteSequence.java 8148454 generic-all +javax/imageio/plugins/tiff/MultiPageTest/MultiPageTest.java 8148454 generic-all +javax/imageio/plugins/tiff/WriteToSequenceAfterAbort.java 8148454 generic-all ############################################################################ @@ -348,56 +311,41 @@ # jdk_tools -# Tests take too long, on sparcs see 7143279 -# also see 8059906 -tools/pack200/CommandLineTests.java generic-all +tools/pack200/CommandLineTests.java 7143279,8059906 generic-all + +tools/pack200/Pack200Test.java 8059906,8151901 generic-all -# 8059906 fails on solaris and macosx, 8151901 -tools/pack200/Pack200Test.java generic-all +tools/pack200/Pack200Props.java 8152622 macosx-all -# 8152622 -tools/pack200/Pack200Props.java macosx-all - -# 8068049 -tools/launcher/FXLauncherTest.java linux-all,macosx-all +tools/launcher/FXLauncherTest.java 8068049 linux-all,macosx-all ############################################################################ # jdk_jdi -# 8004127 -com/sun/jdi/RedefineImplementor.sh generic-all +com/sun/jdi/RedefineImplementor.sh 8004127 generic-all -# 8031555 -com/sun/jdi/JdbMethodExitTest.sh generic-all +com/sun/jdi/JdbMethodExitTest.sh 8031555 generic-all -# 8043571 -com/sun/jdi/RepStep.java generic-all +com/sun/jdi/RepStep.java 8043571 generic-all -# 8058616 -com/sun/jdi/RedefinePop.sh generic-all +com/sun/jdi/RedefinePop.sh 8058616 generic-all -# 8068645 -com/sun/jdi/CatchPatternTest.sh generic-all +com/sun/jdi/CatchPatternTest.sh 8068645 generic-all -# 8067354 -com/sun/jdi/GetLocalVariables4Test.sh windows-all +com/sun/jdi/GetLocalVariables4Test.sh 8067354 windows-all ############################################################################ # jdk_util -# 8062512 -java/util/spi/ResourceBundleControlProvider/UserDefaultControlTest.java generic-all +java/util/spi/ResourceBundleControlProvider/UserDefaultControlTest.java 8062512 generic-all -# 8130337 -java/util/stream/test/org/openjdk/tests/java/util/stream/IntPrimitiveOpsTests.java generic-all +java/util/stream/test/org/openjdk/tests/java/util/stream/IntPrimitiveOpsTests.java 8130337 generic-all -# 8080165, 8085982 -java/util/Arrays/ParallelPrefix.java generic-all +java/util/Arrays/ParallelPrefix.java 8080165,8085982 generic-all -# 8079538 -java/util/BitSet/BitSetStreamTest.java generic-all +java/util/BitSet/BitSetStreamTest.java 8079538 generic-all ############################################################################ @@ -407,43 +355,33 @@ # svc_tools -# 8031482 -sun/tools/jcmd/TestJcmdSanity.java windows-all +sun/tools/jcmd/TestJcmdSanity.java 8031482 windows-all -# 8072131, 8132452 -sun/tools/jmap/heapconfig/JMapHeapConfigTest.java generic-all +sun/tools/jmap/heapconfig/JMapHeapConfigTest.java 8072131,8132452 generic-all -# 8046285 -sun/tools/jstatd/TestJstatdExternalRegistry.java generic-all +sun/tools/jstatd/TestJstatdExternalRegistry.java 8046285 generic-all -# 6456333 -sun/tools/jps/TestJpsJarRelative.java generic-all +sun/tools/jps/TestJpsJarRelative.java 6456333 generic-all -# 6734748 -sun/tools/jinfo/JInfoRunningProcessFlagTest.java generic-all +sun/tools/jinfo/JInfoRunningProcessFlagTest.java 6734748 generic-all -# 8057732 -sun/jvmstat/monitor/MonitoredVm/MonitorVmStartTerminate.java generic-all +sun/jvmstat/monitor/MonitoredVm/MonitorVmStartTerminate.java 8057732 generic-all -# 8059035 -sun/tools/jinfo/JInfoSanityTest.java generic-all +sun/tools/jinfo/JInfoSanityTest.java 8059035 generic-all -# 8151899 -demo/jvmti/compiledMethodLoad/CompiledMethodLoadTest.java generic-all +demo/jvmti/compiledMethodLoad/CompiledMethodLoadTest.java 8151899 generic-all ############################################################################ # jdk_other -# 8141370 -com/sun/jndi/ldap/DeadSSLLdapTimeoutTest.java linux-i586,macosx-all +com/sun/jndi/ldap/DeadSSLLdapTimeoutTest.java 8141370 linux-i586,macosx-all ############################################################################ # core_tools -# 8150975 -# tools/jimage/JImageTest.java linux-i586,windows-i586 +tools/jimage/JImageTest.java 8150975 linux-i586,windows-i586 ############################################################################ diff -r 64f6ae06310e -r eda408d4f253 jdk/test/TEST.groups --- a/jdk/test/TEST.groups Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/test/TEST.groups Tue Apr 05 15:39:35 2016 -0400 @@ -60,7 +60,8 @@ :jdk_rmi \ :jdk_beans \ :jdk_imageio \ - :jdk_sound + :jdk_sound \ + :jdk_client_sanity ############################################################################### # @@ -351,6 +352,10 @@ :jdk_sound \ :jdk_imageio +# SwingSet3 tests. +jdk_client_sanity = \ + sanity/client/SwingSet + ############################################################################### # # Serviceability sanity groups diff -r 64f6ae06310e -r eda408d4f253 jdk/test/java/net/BindException/Test.java --- a/jdk/test/java/net/BindException/Test.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/test/java/net/BindException/Test.java Tue Apr 05 15:39:35 2016 -0400 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* * @test * @bug 4417734 + * @key intermittent * @summary Test that we get a BindException in all expected combinations */ import java.net.*; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/java/util/Calendar/Bug8152077.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/util/Calendar/Bug8152077.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8152077 + * @summary Make sure that roll() with HOUR/HOUR_OF_DAY works around standard/daylight + * time transitions + */ + +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.TimeZone; +import static java.util.Calendar.*; + +public class Bug8152077 { + private static final TimeZone LA = TimeZone.getTimeZone("America/Los_Angeles"); + private static final TimeZone BR = TimeZone.getTimeZone("America/Sao_Paulo"); + + private static final int[] ALLDAY_HOURS = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 + }; + private static final int[] AM_HOURS = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 + }; + private static final int[] PM_HOURS = { // in 24-hour clock + 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 + }; + + private static int errors; + + public static void main(String[] args) { + TimeZone initialTz = TimeZone.getDefault(); + try { + testRoll(LA, new int[] { 2016, MARCH, 13 }, + new int[] { 0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 }); + testRoll(LA, new int[] { 2016, MARCH, 13 }, + new int[] { 0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11 }); + testRoll(LA, new int[] { 2016, MARCH, 13 }, PM_HOURS); + + testRoll(LA, new int[] { 2016, NOVEMBER, 6 }, ALLDAY_HOURS); + testRoll(LA, new int[] { 2016, NOVEMBER, 6 }, AM_HOURS); + testRoll(LA, new int[] { 2016, NOVEMBER, 6 }, PM_HOURS); + + testRoll(BR, new int[] { 2016, FEBRUARY, 21 }, ALLDAY_HOURS); + testRoll(BR, new int[] { 2016, FEBRUARY, 21 }, AM_HOURS); + testRoll(BR, new int[] { 2016, FEBRUARY, 21 }, PM_HOURS); + + testRoll(BR, new int[] { 2016, OCTOBER, 15 }, ALLDAY_HOURS); + testRoll(BR, new int[] { 2016, OCTOBER, 15 }, PM_HOURS); + testRoll(BR, new int[] { 2016, OCTOBER, 16 }, + new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 }); + testRoll(BR, new int[] { 2016, OCTOBER, 16 }, + new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }); + testRoll(BR, new int[] { 2016, OCTOBER, 16 }, PM_HOURS); + } finally { + TimeZone.setDefault(initialTz); + } + if (errors > 0) { + throw new RuntimeException("Test failed"); + } + } + + private static void testRoll(TimeZone tz, int[] params, int[] sequence) { + TimeZone.setDefault(tz); + for (int i = 0; i < sequence.length; i++) { + testRoll(+1, params, sequence, i); + testRoll(-1, params, sequence, i); + } + } + + // amount must be 1 or -1. + private static void testRoll(int amount, int[] params, int[] sequence, int startIndex) { + int year = params[0]; + int month = params[1]; + int dayOfMonth = params[2]; + int hourOfDay = sequence[startIndex]; + Calendar cal = new GregorianCalendar(year, month, dayOfMonth, + hourOfDay, 0, 0); + int ampm = cal.get(AM_PM); + + int length = sequence.length; + int count = length * 2; + int field = (length > 12) ? HOUR_OF_DAY : HOUR; + + System.out.printf("roll(%s, %2d) starting from %s%n", + (field == HOUR) ? "HOUR" : "HOUR_OF_DAY", amount, cal.getTime()); + for (int i = 0; i < count; i++) { + int index = (amount > 0) ? (startIndex + i + 1) % length + : Math.floorMod(startIndex - i - 1, length); + int expected = sequence[index]; + if (field == HOUR) { + expected %= 12; + } + cal.roll(field, amount); + int value = cal.get(field); + if (value != expected) { + System.out.println("Unexpected field value: got=" + value + + ", expected=" + expected); + errors++; + } + if (cal.get(DAY_OF_MONTH) != dayOfMonth) { + System.out.println("DAY_OF_MONTH changed: " + dayOfMonth + + " to " + cal.get(DAY_OF_MONTH)); + } + if (field == HOUR && cal.get(AM_PM) != ampm) { + System.out.println("AM_PM changed: " + ampm + " to " + cal.get(AM_PM)); + errors++; + } + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/java/util/List/NestedSubList.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/util/List/NestedSubList.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8079136 + * @run testng NestedSubList + * @summary Accessing a nested sublist leads to StackOverflowError + */ + +import java.util.AbstractList; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Vector; + +import org.testng.annotations.Test; +import org.testng.annotations.DataProvider; +import static org.testng.Assert.fail; + +public class NestedSubList { + + static final int NEST_LIMIT = 65536; + + @Test(dataProvider="lists") + public void testAccessToSublists(List list, boolean modifiable) { + Class cls = list.getClass(); + for (int i = 0; i < NEST_LIMIT; ++i) { + list = list.subList(0, 1); + } + + try { + list.get(0); + if (modifiable) { + list.remove(0); + list.add(0, 42); + } + } catch (StackOverflowError e) { + fail("failed for " + cls); + } + } + + @DataProvider + public static Object[][] lists() { + final boolean MODIFIABLE = true; + final boolean NON_MODIFIABLE = false; + List c = Arrays.asList(42); + + return new Object[][] { + {c, NON_MODIFIABLE}, + {new ArrayList<>(c), MODIFIABLE}, + {new LinkedList<>(c), MODIFIABLE}, + {new MyList(), NON_MODIFIABLE}, + {new Vector<>(c), MODIFIABLE}, + {Collections.singletonList(42), NON_MODIFIABLE}, + {Collections.checkedList(c, Integer.class), NON_MODIFIABLE}, + {Collections.checkedList(new ArrayList<>(c), Integer.class), MODIFIABLE}, + {Collections.checkedList(new LinkedList<>(c), Integer.class), MODIFIABLE}, + {Collections.checkedList(new Vector<>(c), Integer.class), MODIFIABLE}, + {Collections.synchronizedList(c), NON_MODIFIABLE}, + {Collections.synchronizedList(new ArrayList<>(c)), MODIFIABLE}, + {Collections.synchronizedList(new LinkedList<>(c)), MODIFIABLE}, + {Collections.synchronizedList(new Vector<>(c)), MODIFIABLE}, + {Collections.unmodifiableList(c), NON_MODIFIABLE}, + {Collections.unmodifiableList(new ArrayList<>(c)), NON_MODIFIABLE}, + {Collections.unmodifiableList(new LinkedList<>(c)), NON_MODIFIABLE}, + {Collections.unmodifiableList(new Vector<>(c)), NON_MODIFIABLE}, + }; + } + + static class MyList extends AbstractList { + public Integer get(int index) { return 42; } + public int size() { return 1; } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/java/util/List/SubList.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/util/List/SubList.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,676 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8079136 + * @library /lib/testlibrary + * @build jdk.testlibrary.* + * @run testng SubList + * @summary Basic functionality of sublists + * @key randomness + */ + +import java.util.AbstractList; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collections; +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; +import java.util.Random; +import java.util.Vector; + +import org.testng.annotations.Test; +import org.testng.annotations.DataProvider; + +import jdk.testlibrary.RandomFactory; + + +public class SubList extends org.testng.Assert { + + final Random rnd = RandomFactory.getRandom(); + + @Test(dataProvider = "modifiable") + public void testAdd(List list, int from, int to) { + List subList = list.subList(from, to); + Integer e = rnd.nextInt(); + subList.add(e); + assertEquals(list.get(to), e); + assertEquals(subList.size(), to - from + 1); + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModAdd(List list, int from, int to) { + List subList = list.subList(from, to); + list.add(42); + subList.add(42); + } + + @Test(dataProvider = "unresizable", + expectedExceptions = UnsupportedOperationException.class) + public void testUnmodAdd(List list, int from, int to) { + List subList = list.subList(from, to); + subList.add(42); + } + + @Test(dataProvider = "modifiable") + public void testAddAtPos(List list, int from, int to) { + List subList = list.subList(from, to); + int i = rnd.nextInt(1 + to - from); + Integer e = rnd.nextInt(); + subList.add(i, e); + assertEquals(list.get(from + i), e); + assertEquals(subList.size(), to - from + 1); + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModAddAtPos(List list, int from, int to) { + List subList = list.subList(from, to); + list.add(42); + int i = rnd.nextInt(1 + to - from); + subList.add(i, 42); + } + + @Test(dataProvider = "unresizable", + expectedExceptions = UnsupportedOperationException.class) + public void testUnmodAddAtPos(List list, int from, int to) { + List subList = list.subList(from, to); + int i = rnd.nextInt(1 + to - from); + subList.add(i, 42); + } + + @Test(dataProvider = "modifiable") + public void testClear(List list, int from, int to) { + List subList = list.subList(from, to); + subList.clear(); + assertTrue(subList.isEmpty()); + assertEquals(subList.size(), 0); + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModClear(List list, int from, int to) { + List subList = list.subList(from, to); + list.add(42); + subList.clear(); + } + + @Test(dataProvider = "unresizable", + expectedExceptions = UnsupportedOperationException.class) + public void testUnmodClear(List list, int from, int to) { + List subList = list.subList(from, to); + subList.clear(); + } + + @Test(dataProvider = "all") + public void testEquals(List list, int from, int to) { + List subList1 = list.subList(from, to); + List subList2 = list.subList(from, to); + assertTrue(subList1.equals(subList2)); + assertEquals(subList1.hashCode(), subList2.hashCode()); + for (int i = 0; i != 16; ++i) { + int from3 = rnd.nextInt(1 + list.size()); + int to3 = from3 + rnd.nextInt(1 + list.size() - from3); + boolean equal = (to - from) == (to3 - from3); + for (int j = 0; j < to - from && j < to3 - from3; ++j) + equal &= list.get(from + j) == list.get(from3 + j); + List subList3 = list.subList(from3, to3); + assertEquals(subList1.equals(subList3), equal); + } + } + +// @Test(dataProvider = "modifiable", +// expectedExceptions = ConcurrentModificationException.class) +// public void testModEquals(List list, int from, int to) { +// List subList = list.subList(from, to); +// list.add(42); +// subList.equals(subList); +// } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModHashCode(List list, int from, int to) { + List subList = list.subList(from, to); + list.add(42); + subList.hashCode(); + } + + @Test(dataProvider = "all") + public void testGet(List list, int from, int to) { + List subList = list.subList(from, to); + for (int i = 0; i < to - from; ++i) + assertEquals(list.get(from + i), subList.get(i)); + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModGet(List list, int from, int to) { + List subList = list.subList(from, to); + list.add(42); + subList.get(from); + } + + @Test(dataProvider = "all") + public void testIndexOf(List list, int from, int to) { + List subList = list.subList(from, to); + if (from < to) { + Integer e = list.get(from); + int j = subList.indexOf(e); + assertTrue(j == 0); + } + for (int i = 0; i < list.size(); ++i) { + Integer e = list.get(i); + int j = subList.indexOf(e); + if (i < from || i >= to) { + assertTrue(j == -1 || subList.get(j) == e); + } else { + assertTrue(j >= 0); + assertTrue(j <= i - from); + assertEquals(subList.get(j), e); + } + } + for (int i = 0; i < 16; ++i) { + Integer r = rnd.nextInt(); + if (list.contains(r)) continue; + int j = subList.indexOf(r); + assertTrue(j == -1); + } + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModIndexOf(List list, int from, int to) { + List subList = list.subList(from, to); + list.add(42); + subList.indexOf(from); + } + + @Test(dataProvider = "all") + public void testIterator(List list, int from, int to) { + List subList = list.subList(from, to); + Iterator it = subList.iterator(); + for (int i = from; i < to; ++i) { + assertTrue(it.hasNext()); + assertEquals(list.get(i), it.next()); + } + assertFalse(it.hasNext()); + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModIteratorNext(List list, int from, int to) { + List subList = list.subList(from, to); + Iterator it = subList.iterator(); + list.add(42); + it.next(); + } + + @Test(dataProvider = "modifiable") + public void testIteratorRemove(List list, int from, int to) { + List subList = list.subList(from, to); + Iterator it = subList.iterator(); + for (int i = from; i < to; ++i) { + assertTrue(it.hasNext()); + assertEquals(list.get(from), it.next()); + it.remove(); + } + assertFalse(it.hasNext()); + assertTrue(subList.isEmpty()); + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModIteratorRemove(List list, int from, int to) { + List subList = list.subList(from, to); + Iterator it = subList.iterator(); + it.next(); + list.add(42); + it.remove(); + } + + @Test(dataProvider = "unresizable", + expectedExceptions = UnsupportedOperationException.class) + public void testUnmodIteratorRemove(List list, int from, int to) { + List subList = list.subList(from, to); + Iterator it = subList.iterator(); + it.next(); + it.remove(); + } + + @Test(dataProvider = "all") + public void testIteratorForEachRemaining(List list, int from, int to) { + List subList = list.subList(from, to); + for (int k = 0; k < 16; ++k) { + int r = from + rnd.nextInt(1 + to - from); + Iterator it = subList.iterator(); + for (int i = from; i < to; ++i) { + assertTrue(it.hasNext()); + if (i == r) { + Iterator jt = list.listIterator(r); + it.forEachRemaining(x -> + assertTrue(jt.hasNext() && x == jt.next())); + break; + } + assertEquals(list.get(i), it.next()); + } + it.forEachRemaining(x -> fail()); + } + } + + @Test(dataProvider = "all") + public void testLastIndexOf(List list, int from, int to) { + List subList = list.subList(from, to); + if (from < to) { + Integer e = list.get(to - 1); + int j = subList.lastIndexOf(e); + assertTrue(j == to - from - 1); + } + for (int i = 0; i < list.size(); ++i) { + Integer e = list.get(i); + int j = subList.lastIndexOf(e); + if (i < from || i >= to) { + assertTrue(j == -1 || subList.get(j) == e); + } else { + assertTrue(j >= 0 && j >= i - from); + assertEquals(subList.get(j), e); + } + } + for (int i = 0; i < 16; ++i) { + Integer r = rnd.nextInt(); + if (list.contains(r)) continue; + int j = subList.lastIndexOf(r); + assertTrue(j == -1); + } + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModLastIndexOf(List list, int from, int to) { + List subList = list.subList(from, to); + list.add(42); + subList.lastIndexOf(42); + } + + @Test(dataProvider = "unresizable") + public void testListIterator(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(); + for (int i = from; i < to; ++i) { + assertTrue(it.hasNext()); + assertTrue(it.nextIndex() == i - from); + assertEquals(list.get(i), it.next()); + } + assertFalse(it.hasNext()); + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModListIteratorNext(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(); + list.add(42); + it.next(); + } + + @Test(dataProvider = "modifiable") + public void testListIteratorSet(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(); + for (int i = from; i < to; ++i) { + assertTrue(it.hasNext()); + assertTrue(it.nextIndex() == i - from); + assertEquals(list.get(i), it.next()); + Integer e = rnd.nextInt(); + it.set(e); + assertEquals(list.get(i), e); + } + assertFalse(it.hasNext()); + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModListIteratorSet(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(); + it.next(); + list.add(42); + it.set(42); + } + + @Test(dataProvider = "unsettable", + expectedExceptions = UnsupportedOperationException.class) + public void testUnmodListIteratorSet(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(); + it.next(); + it.set(42); + } + + @Test(dataProvider = "unresizable") + public void testListIteratorPrevious(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(subList.size()); + for (int i = to - 1; i >= from; --i) { + assertTrue(it.hasPrevious()); + assertTrue(it.previousIndex() == i - from); + assertEquals(list.get(i), it.previous()); + } + assertFalse(it.hasPrevious()); + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModListIteratorPrevious(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(to - from); + list.add(42); + it.previous(); + } + + @Test(dataProvider = "modifiable") + public void testListIteratorSetPrevious(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(subList.size()); + for (int i = to - 1; i >= from; --i) { + assertTrue(it.hasPrevious()); + assertTrue(it.previousIndex() == i - from); + assertEquals(list.get(i), it.previous()); + Integer e = rnd.nextInt(); + it.set(e); + assertEquals(list.get(i), e); + } + assertFalse(it.hasPrevious()); + } + + @Test(dataProvider = "unsettable", + expectedExceptions = UnsupportedOperationException.class) + public void testUnmodListIteratorSetPrevious(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(to - from); + it.previous(); + it.set(42); + } + + @Test(dataProvider = "modifiable") + public void testListIteratorAdd(List list, int from, int to) { + List subList = list.subList(from, to); + for (int i = 0; i < 16; ++i) { + int r = rnd.nextInt(1 + subList.size()); + ListIterator it = subList.listIterator(r); + Integer e = rnd.nextInt(); + it.add(e); + assertEquals(it.previous(), e); + assertEquals(list.get(from + r), e); + } + } + + @Test(dataProvider = "unresizable", + expectedExceptions = UnsupportedOperationException.class) + public void testUnmodListIteratorAdd(List list, int from, int to) { + List subList = list.subList(from, to); + int r = rnd.nextInt(1 + subList.size()); + ListIterator it = subList.listIterator(r); + it.add(42); + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModListIteratorAdd(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(); + it.next(); + list.add(42); + it.add(42); + } + + @Test(dataProvider = "modifiable") + public void testListIteratorRemoveNext(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(); + for (int i = from; i < to; ++i) { + assertTrue(it.hasNext()); + assertTrue(it.nextIndex() == 0); + assertEquals(list.get(from), it.next()); + it.remove(); + } + assertFalse(it.hasNext()); + assertTrue(subList.isEmpty()); + } + + @Test(dataProvider = "unresizable", + expectedExceptions = UnsupportedOperationException.class) + public void testUnmodListIteratorRemoveNext(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(); + it.next(); + it.remove(); + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModListIteratorRemove(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(); + it.next(); + list.add(42); + it.remove(); + } + + @Test(dataProvider = "modifiable") + public void testListIteratorRemovePrevious(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(subList.size()); + for (int i = to - 1; i >= from; --i) { + assertTrue(it.hasPrevious()); + assertTrue(it.previousIndex() == i - from); + assertEquals(list.get(i), it.previous()); + it.remove(); + } + assertFalse(it.hasPrevious()); + assertTrue(subList.isEmpty()); + } + + @Test(dataProvider = "unresizable", + expectedExceptions = UnsupportedOperationException.class) + public void testUnmodListIteratorRemovePrevious(List list, int from, int to) { + List subList = list.subList(from, to); + ListIterator it = subList.listIterator(subList.size()); + it.previous(); + it.remove(); + } + + @Test(dataProvider = "modifiable") + public void testRemove(List list, int from, int to) { + List subList = list.subList(from, to); + for (int i = 0; i < 16; ++i) { + if (subList.isEmpty()) break; + int r = rnd.nextInt(subList.size()); + Integer e = list.get(from + r); + assertEquals(subList.remove(r), e); + } + } + + @Test(dataProvider = "unresizable", + expectedExceptions = UnsupportedOperationException.class) + public void testUnmodRemove(List list, int from, int to) { + List subList = list.subList(from, to); + int r = rnd.nextInt(subList.size()); + subList.remove(r); + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModRemove(List list, int from, int to) { + List subList = list.subList(from, to); + list.add(42); + subList.remove(0); + } + + @Test(dataProvider = "modifiable") + public void testSet(List list, int from, int to) { + List subList = list.subList(from, to); + for (int i = 0; i < to - from; ++i) { + Integer e0 = list.get(from + i); + Integer e1 = rnd.nextInt(); + assertEquals(subList.set(i, e1), e0); + assertEquals(list.get(from + i), e1); + } + } + + @Test(dataProvider = "modifiable", + expectedExceptions = ConcurrentModificationException.class) + public void testModSet(List list, int from, int to) { + List subList = list.subList(from, to); + list.add(42); + subList.set(0, 42); + } + + @Test(dataProvider = "all") + public void testSubList(List list, int from, int to) { + List subList = list.subList(from, to); + for (int i = 0; i < 16 && from < to; ++i) { + int from1 = rnd.nextInt(to - from); + int to1 = from1 + 1 + rnd.nextInt(to - from - from1); + List subSubList = subList.subList(from1, to1); + for (int j = 0; j < to1 - from1; ++j) + assertEquals(list.get(from + from1 + j), subSubList.get(j)); + } + } + + /** + * All kinds of lists + */ + @DataProvider + public static Object[][] all() { + Object[][] l1 = modifiable(); + Object[][] l2 = unresizable(); + Object[][] res = Arrays.copyOf(l1, l1.length + l2.length); + System.arraycopy(l2, 0, res, l1.length, l2.length); + return res; + } + + /** + * Lists that allow any modifications: resizing and setting values + */ + @DataProvider + public static Object[][] modifiable() { + final List c1 = Arrays.asList(42); + final List c9 = Arrays.asList(40, 41, 42, 43, 44, 45, -1, + Integer.MIN_VALUE, 1000500); + + return new Object[][] { + {new ArrayList<>(c1), 0, 1}, + {new LinkedList<>(c1), 0, 1}, + {new Vector<>(c1), 0, 1}, + {new ArrayList<>(c1).subList(0, 1), 0, 1}, + {new LinkedList<>(c1).subList(0, 1), 0, 1}, + {new Vector<>(c1).subList(0, 1), 0, 1}, + {Collections.checkedList(new ArrayList<>(c1), Integer.class), 0, 1}, + {Collections.checkedList(new LinkedList<>(c1), Integer.class), 0, 1}, + {Collections.checkedList(new Vector<>(c1), Integer.class), 0, 1}, + {Collections.synchronizedList(new ArrayList<>(c1)), 0, 1}, + {Collections.synchronizedList(new LinkedList<>(c1)), 0, 1}, + {Collections.synchronizedList(new Vector<>(c1)), 0, 1}, + + {new ArrayList<>(c9), 2, 5}, + {new LinkedList<>(c9), 2, 5}, + {new Vector<>(c9), 2, 5}, + {new ArrayList<>(c9).subList(1, 8), 1, 4}, + {new LinkedList<>(c9).subList(1, 8), 1, 4}, + {new Vector<>(c9).subList(1, 8), 1, 4}, + {Collections.checkedList(new ArrayList<>(c9), Integer.class), 2, 5}, + {Collections.checkedList(new LinkedList<>(c9), Integer.class), 2, 5}, + {Collections.checkedList(new Vector<>(c9), Integer.class), 2, 5}, + {Collections.synchronizedList(new ArrayList<>(c9)), 2, 5}, + {Collections.synchronizedList(new LinkedList<>(c9)), 2, 5}, + {Collections.synchronizedList(new Vector<>(c9)), 2, 5}, + }; + } + + /** + * Lists that don't allow resizing, but allow setting values + */ + @DataProvider + public static Object[][] unresizable() { + final List c1 = Arrays.asList(42); + final List c9 = Arrays.asList(40, 41, 42, 43, 44, 45, -1, + Integer.MIN_VALUE, 1000500); + + Object[][] l1 = unsettable(); + Object[][] l2 = { + {c1, 0, 1}, + {c1.subList(0, 1), 0, 1}, + {Collections.checkedList(c1, Integer.class), 0, 1}, + {Collections.synchronizedList(c1), 0, 1}, + {c9, 0, 4}, + {c9, 4, 6}, + {c9.subList(1, 8), 1, 4}, + {c9.subList(1, 8), 0, 7}, + {Collections.checkedList(c9, Integer.class), 3, 6}, + {Collections.synchronizedList(c9), 3, 5}, + }; + Object[][] res = Arrays.copyOf(l1, l1.length + l2.length); + System.arraycopy(l2, 0, res, l1.length, l2.length); + return res; + } + + /** + * Lists that don't allow either resizing or setting values + */ + @DataProvider + public static Object[][] unsettable() { + final List c1 = Arrays.asList(42); + final List c9 = Arrays.asList(40, 41, 42, 43, 44, 45, -1, + Integer.MIN_VALUE, 1000500); + + return new Object[][] { + {new MyList(1), 0, 1}, + {new MyList(1).subList(0, 1), 0, 1}, + {Collections.singletonList(42), 0, 1}, + {Collections.singletonList(42).subList(0, 1), 0, 1}, + {Collections.unmodifiableList(c1), 0, 1}, + {Collections.unmodifiableList(new ArrayList<>(c1)), 0, 1}, + {Collections.unmodifiableList(new LinkedList<>(c1)), 0, 1}, + {Collections.unmodifiableList(new Vector<>(c1)), 0, 1}, + + {new MyList(9), 3, 6}, + {new MyList(9).subList(2, 8), 3, 6}, + {Collections.unmodifiableList(c9), 3, 6}, + {Collections.unmodifiableList(new ArrayList<>(c9)), 3, 6}, + {Collections.unmodifiableList(new LinkedList<>(c9)), 3, 6}, + {Collections.unmodifiableList(new Vector<>(c9)), 3, 6}, + }; + } + + static class MyList extends AbstractList { + private int size; + MyList(int s) { size = s; } + public Integer get(int index) { return 42; } + public int size() { return size; } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/java/util/Locale/LocaleProviders.sh --- a/jdk/test/java/util/Locale/LocaleProviders.sh Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/test/java/util/Locale/LocaleProviders.sh Tue Apr 05 15:39:35 2016 -0400 @@ -25,6 +25,7 @@ # @test # @bug 6336885 7196799 7197573 7198834 8000245 8000615 8001440 8008577 # 8010666 8013086 8013233 8013903 8015960 8028771 8054482 8062006 +# 8150432 # @summary tests for "java.locale.providers" system property # @modules java.base/sun.util.locale # java.base/sun.util.locale.provider @@ -168,7 +169,7 @@ PARAM1=HOST fi ;; - CYGWIN_NT-6* | Darwin ) + CYGWIN_NT-6* | CYGWIN_NT-10* | Darwin ) PARAM1=HOST ;; * ) diff -r 64f6ae06310e -r eda408d4f253 jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java --- a/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -154,8 +154,8 @@ } void addList(Function, ? extends List> l) { - // @@@ If collection is instance of List then add sub-list tests addCollection(l); + addCollection(l.andThen(list -> list.subList(0, list.size()))); } void addMap(Function, ? extends Map> m) { diff -r 64f6ae06310e -r eda408d4f253 jdk/test/java/util/concurrent/tck/TimeUnit8Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/util/concurrent/tck/TimeUnit8Test.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,103 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * This file is available under and governed by the GNU General Public + * License version 2 only, as published by the Free Software Foundation. + * However, the following notice accompanied the original version of this + * file: + * + * Written by Doug Lea and Martin Buchholz with assistance from + * members of JCP JSR-166 Expert Group and released to the public + * domain, as explained at + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +import static java.util.concurrent.TimeUnit.DAYS; +import static java.util.concurrent.TimeUnit.HOURS; +import static java.util.concurrent.TimeUnit.MICROSECONDS; +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.MINUTES; +import static java.util.concurrent.TimeUnit.NANOSECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; + +import java.time.temporal.ChronoUnit; +import java.util.concurrent.TimeUnit; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class TimeUnit8Test extends JSR166TestCase { + public static void main(String[] args) { + main(suite(), args); + } + + public static Test suite() { + return new TestSuite(TimeUnit8Test.class); + } + + /** + * tests for toChronoUnit. + */ + public void testToChronoUnit() throws Exception { + assertSame(ChronoUnit.NANOS, NANOSECONDS.toChronoUnit()); + assertSame(ChronoUnit.MICROS, MICROSECONDS.toChronoUnit()); + assertSame(ChronoUnit.MILLIS, MILLISECONDS.toChronoUnit()); + assertSame(ChronoUnit.SECONDS, SECONDS.toChronoUnit()); + assertSame(ChronoUnit.MINUTES, MINUTES.toChronoUnit()); + assertSame(ChronoUnit.HOURS, HOURS.toChronoUnit()); + assertSame(ChronoUnit.DAYS, DAYS.toChronoUnit()); + + // Every TimeUnit has a defined ChronoUnit equivalent + for (TimeUnit x : TimeUnit.values()) + assertSame(x, TimeUnit.of(x.toChronoUnit())); + } + + /** + * tests for TimeUnit.of(ChronoUnit). + */ + public void testTimeUnitOf() throws Exception { + assertSame(NANOSECONDS, TimeUnit.of(ChronoUnit.NANOS)); + assertSame(MICROSECONDS, TimeUnit.of(ChronoUnit.MICROS)); + assertSame(MILLISECONDS, TimeUnit.of(ChronoUnit.MILLIS)); + assertSame(SECONDS, TimeUnit.of(ChronoUnit.SECONDS)); + assertSame(MINUTES, TimeUnit.of(ChronoUnit.MINUTES)); + assertSame(HOURS, TimeUnit.of(ChronoUnit.HOURS)); + assertSame(DAYS, TimeUnit.of(ChronoUnit.DAYS)); + + assertThrows(NullPointerException.class, + () -> TimeUnit.of((ChronoUnit)null)); + + // ChronoUnits either round trip to their TimeUnit + // equivalents, or throw IllegalArgumentException. + for (ChronoUnit cu : ChronoUnit.values()) { + final TimeUnit tu; + try { + tu = TimeUnit.of(cu); + } catch (IllegalArgumentException acceptable) { + continue; + } + assertSame(cu, tu.toChronoUnit()); + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/java/util/concurrent/tck/TimeUnitTest.java --- a/jdk/test/java/util/concurrent/tck/TimeUnitTest.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/test/java/util/concurrent/tck/TimeUnitTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -41,7 +41,6 @@ import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; -import java.time.temporal.ChronoUnit; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -124,6 +123,15 @@ assertEquals(t, NANOSECONDS.convert(t, NANOSECONDS)); } + + for (TimeUnit x : TimeUnit.values()) { + long[] zs = { + 0, 1, -1, + Integer.MAX_VALUE, Integer.MIN_VALUE, + Long.MAX_VALUE, Long.MIN_VALUE, + }; + for (long z : zs) assertEquals(z, x.convert(z, x)); + } } /** @@ -308,6 +316,27 @@ NANOSECONDS.convert(Long.MAX_VALUE / 2, DAYS)); assertEquals(Long.MIN_VALUE, NANOSECONDS.convert(-Long.MAX_VALUE / 4, DAYS)); + + for (TimeUnit x : TimeUnit.values()) + for (TimeUnit y : TimeUnit.values()) { + long ratio = x.toNanos(1) / y.toNanos(1); + if (ratio >= 1) { + assertEquals(ratio, y.convert(1, x)); + assertEquals(1, x.convert(ratio, y)); + long max = Long.MAX_VALUE/ratio; + assertEquals(max * ratio, y.convert(max, x)); + assertEquals(-max * ratio, y.convert(-max, x)); + assertEquals(max, x.convert(max * ratio, y)); + assertEquals(-max, x.convert(-max * ratio, y)); + if (max < Long.MAX_VALUE) { + assertEquals(Long.MAX_VALUE, y.convert(max + 1, x)); + assertEquals(Long.MIN_VALUE, y.convert(-max - 1, x)); + assertEquals(Long.MIN_VALUE, y.convert(Long.MIN_VALUE + 1, x)); + } + assertEquals(Long.MAX_VALUE, y.convert(Long.MAX_VALUE, x)); + assertEquals(Long.MIN_VALUE, y.convert(Long.MIN_VALUE, x)); + } + } } /** @@ -319,6 +348,146 @@ MILLISECONDS.toNanos(Long.MAX_VALUE / 2)); assertEquals(Long.MIN_VALUE, MILLISECONDS.toNanos(-Long.MAX_VALUE / 3)); + + for (TimeUnit x : TimeUnit.values()) { + long ratio = x.toNanos(1) / NANOSECONDS.toNanos(1); + if (ratio >= 1) { + long max = Long.MAX_VALUE/ratio; + for (long z : new long[] {0, 1, -1, max, -max}) + assertEquals(z * ratio, x.toNanos(z)); + if (max < Long.MAX_VALUE) { + assertEquals(Long.MAX_VALUE, x.toNanos(max + 1)); + assertEquals(Long.MIN_VALUE, x.toNanos(-max - 1)); + assertEquals(Long.MIN_VALUE, x.toNanos(Long.MIN_VALUE + 1)); + } + assertEquals(Long.MAX_VALUE, x.toNanos(Long.MAX_VALUE)); + assertEquals(Long.MIN_VALUE, x.toNanos(Long.MIN_VALUE)); + if (max < Integer.MAX_VALUE) { + assertEquals(Long.MAX_VALUE, x.toNanos(Integer.MAX_VALUE)); + assertEquals(Long.MIN_VALUE, x.toNanos(Integer.MIN_VALUE)); + } + } + } + } + + /** + * toMicros saturates positive too-large values to Long.MAX_VALUE + * and negative to LONG.MIN_VALUE + */ + public void testToMicrosSaturate() { + for (TimeUnit x : TimeUnit.values()) { + long ratio = x.toNanos(1) / MICROSECONDS.toNanos(1); + if (ratio >= 1) { + long max = Long.MAX_VALUE/ratio; + for (long z : new long[] {0, 1, -1, max, -max}) + assertEquals(z * ratio, x.toMicros(z)); + if (max < Long.MAX_VALUE) { + assertEquals(Long.MAX_VALUE, x.toMicros(max + 1)); + assertEquals(Long.MIN_VALUE, x.toMicros(-max - 1)); + assertEquals(Long.MIN_VALUE, x.toMicros(Long.MIN_VALUE + 1)); + } + assertEquals(Long.MAX_VALUE, x.toMicros(Long.MAX_VALUE)); + assertEquals(Long.MIN_VALUE, x.toMicros(Long.MIN_VALUE)); + if (max < Integer.MAX_VALUE) { + assertEquals(Long.MAX_VALUE, x.toMicros(Integer.MAX_VALUE)); + assertEquals(Long.MIN_VALUE, x.toMicros(Integer.MIN_VALUE)); + } + } + } + } + + /** + * toMillis saturates positive too-large values to Long.MAX_VALUE + * and negative to LONG.MIN_VALUE + */ + public void testToMillisSaturate() { + for (TimeUnit x : TimeUnit.values()) { + long ratio = x.toNanos(1) / MILLISECONDS.toNanos(1); + if (ratio >= 1) { + long max = Long.MAX_VALUE/ratio; + for (long z : new long[] {0, 1, -1, max, -max}) + assertEquals(z * ratio, x.toMillis(z)); + if (max < Long.MAX_VALUE) { + assertEquals(Long.MAX_VALUE, x.toMillis(max + 1)); + assertEquals(Long.MIN_VALUE, x.toMillis(-max - 1)); + assertEquals(Long.MIN_VALUE, x.toMillis(Long.MIN_VALUE + 1)); + } + assertEquals(Long.MAX_VALUE, x.toMillis(Long.MAX_VALUE)); + assertEquals(Long.MIN_VALUE, x.toMillis(Long.MIN_VALUE)); + if (max < Integer.MAX_VALUE) { + assertEquals(Long.MAX_VALUE, x.toMillis(Integer.MAX_VALUE)); + assertEquals(Long.MIN_VALUE, x.toMillis(Integer.MIN_VALUE)); + } + } + } + } + + /** + * toSeconds saturates positive too-large values to Long.MAX_VALUE + * and negative to LONG.MIN_VALUE + */ + public void testToSecondsSaturate() { + for (TimeUnit x : TimeUnit.values()) { + long ratio = x.toNanos(1) / SECONDS.toNanos(1); + if (ratio >= 1) { + long max = Long.MAX_VALUE/ratio; + for (long z : new long[] {0, 1, -1, max, -max}) + assertEquals(z * ratio, x.toSeconds(z)); + if (max < Long.MAX_VALUE) { + assertEquals(Long.MAX_VALUE, x.toSeconds(max + 1)); + assertEquals(Long.MIN_VALUE, x.toSeconds(-max - 1)); + assertEquals(Long.MIN_VALUE, x.toSeconds(Long.MIN_VALUE + 1)); + } + assertEquals(Long.MAX_VALUE, x.toSeconds(Long.MAX_VALUE)); + assertEquals(Long.MIN_VALUE, x.toSeconds(Long.MIN_VALUE)); + if (max < Integer.MAX_VALUE) { + assertEquals(Long.MAX_VALUE, x.toSeconds(Integer.MAX_VALUE)); + assertEquals(Long.MIN_VALUE, x.toSeconds(Integer.MIN_VALUE)); + } + } + } + } + + /** + * toMinutes saturates positive too-large values to Long.MAX_VALUE + * and negative to LONG.MIN_VALUE + */ + public void testToMinutesSaturate() { + for (TimeUnit x : TimeUnit.values()) { + long ratio = x.toNanos(1) / MINUTES.toNanos(1); + if (ratio > 1) { + long max = Long.MAX_VALUE/ratio; + for (long z : new long[] {0, 1, -1, max, -max}) + assertEquals(z * ratio, x.toMinutes(z)); + assertEquals(Long.MAX_VALUE, x.toMinutes(max + 1)); + assertEquals(Long.MIN_VALUE, x.toMinutes(-max - 1)); + assertEquals(Long.MAX_VALUE, x.toMinutes(Long.MAX_VALUE)); + assertEquals(Long.MIN_VALUE, x.toMinutes(Long.MIN_VALUE)); + assertEquals(Long.MIN_VALUE, x.toMinutes(Long.MIN_VALUE + 1)); + } + } + } + + /** + * toHours saturates positive too-large values to Long.MAX_VALUE + * and negative to LONG.MIN_VALUE + */ + public void testToHoursSaturate() { + for (TimeUnit x : TimeUnit.values()) { + long ratio = x.toNanos(1) / HOURS.toNanos(1); + if (ratio >= 1) { + long max = Long.MAX_VALUE/ratio; + for (long z : new long[] {0, 1, -1, max, -max}) + assertEquals(z * ratio, x.toHours(z)); + if (max < Long.MAX_VALUE) { + assertEquals(Long.MAX_VALUE, x.toHours(max + 1)); + assertEquals(Long.MIN_VALUE, x.toHours(-max - 1)); + assertEquals(Long.MIN_VALUE, x.toHours(Long.MIN_VALUE + 1)); + } + assertEquals(Long.MAX_VALUE, x.toHours(Long.MAX_VALUE)); + assertEquals(Long.MIN_VALUE, x.toHours(Long.MIN_VALUE)); + } + } } /** @@ -461,49 +630,4 @@ assertSame(x, serialClone(x)); } - /** - * tests for toChronoUnit. - */ - public void testToChronoUnit() throws Exception { - assertSame(ChronoUnit.NANOS, NANOSECONDS.toChronoUnit()); - assertSame(ChronoUnit.MICROS, MICROSECONDS.toChronoUnit()); - assertSame(ChronoUnit.MILLIS, MILLISECONDS.toChronoUnit()); - assertSame(ChronoUnit.SECONDS, SECONDS.toChronoUnit()); - assertSame(ChronoUnit.MINUTES, MINUTES.toChronoUnit()); - assertSame(ChronoUnit.HOURS, HOURS.toChronoUnit()); - assertSame(ChronoUnit.DAYS, DAYS.toChronoUnit()); - - // Every TimeUnit has a defined ChronoUnit equivalent - for (TimeUnit x : TimeUnit.values()) - assertSame(x, TimeUnit.of(x.toChronoUnit())); - } - - /** - * tests for TimeUnit.of(ChronoUnit). - */ - public void testTimeUnitOf() throws Exception { - assertSame(NANOSECONDS, TimeUnit.of(ChronoUnit.NANOS)); - assertSame(MICROSECONDS, TimeUnit.of(ChronoUnit.MICROS)); - assertSame(MILLISECONDS, TimeUnit.of(ChronoUnit.MILLIS)); - assertSame(SECONDS, TimeUnit.of(ChronoUnit.SECONDS)); - assertSame(MINUTES, TimeUnit.of(ChronoUnit.MINUTES)); - assertSame(HOURS, TimeUnit.of(ChronoUnit.HOURS)); - assertSame(DAYS, TimeUnit.of(ChronoUnit.DAYS)); - - assertThrows(NullPointerException.class, - () -> TimeUnit.of((ChronoUnit)null)); - - // ChronoUnits either round trip to their TimeUnit - // equivalents, or throw IllegalArgumentException. - for (ChronoUnit cu : ChronoUnit.values()) { - final TimeUnit tu; - try { - tu = TimeUnit.of(cu); - } catch (IllegalArgumentException acceptable) { - continue; - } - assertSame(cu, tu.toChronoUnit()); - } - } - } diff -r 64f6ae06310e -r eda408d4f253 jdk/test/java/util/jar/JarFile/MultiReleaseJarAPI.java --- a/jdk/test/java/util/jar/JarFile/MultiReleaseJarAPI.java Tue Apr 05 10:34:05 2016 -0700 +++ b/jdk/test/java/util/jar/JarFile/MultiReleaseJarAPI.java Tue Apr 05 15:39:35 2016 -0400 @@ -83,6 +83,10 @@ } try (JarFile jf = new JarFile(multirelease)) { + Assert.assertFalse(jf.isMultiRelease()); + } + + try (JarFile jf = new JarFile(multirelease, true, ZipFile.OPEN_READ, Release.RUNTIME)) { Assert.assertTrue(jf.isMultiRelease()); } } diff -r 64f6ae06310e -r eda408d4f253 jdk/test/javax/xml/bind/jxc/8073872/Foo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/javax/xml/bind/jxc/8073872/Foo.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.util.ArrayList; +import java.util.List; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = {"fooObject"}) +@XmlRootElement(name = "Foo") + +public class Foo { + + protected List fooObject; + + public List getFooObject() { + if (fooObject == null) { + fooObject = new ArrayList(); + } + return this.fooObject; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/javax/xml/bind/jxc/8073872/SchemagenStackOverflow.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/javax/xml/bind/jxc/8073872/SchemagenStackOverflow.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8073872 + * @summary test that stackoverflow is not observable when element + * references containing class + * @modules java.xml + * @modules java.xml.bind + * @compile Foo.java + * @run testng/othervm SchemagenStackOverflow + */ + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.stream.Collectors; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.SchemaOutputResolver; +import javax.xml.transform.Result; +import javax.xml.transform.stream.StreamResult; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class SchemagenStackOverflow { + + @Test + public void schemagenStackOverflowTest() throws Exception { + // Create new instance of JAXB context + JAXBContext context = JAXBContext.newInstance(Foo.class); + context.generateSchema(new TestOutputResolver()); + + // Read schema content from file + String content = Files.lines(resultSchemaFile).collect(Collectors.joining("")); + System.out.println("Generated schema content:" + content); + + // Check if schema was generated: check class and list object names + Assert.assertTrue(content.contains("name=\"Foo\"")); + Assert.assertTrue(content.contains("name=\"fooObject\"")); + } + + // Schemagen output resolver + class TestOutputResolver extends SchemaOutputResolver { + @Override + public Result createOutput(String namespaceUri, String fileName) + throws IOException { + return new StreamResult(resultSchemaFile.toFile()); + } + } + + // Schemagen output file name and path + static final String SCHEMA_FILENAME = "generatedSchema.xsd"; + Path resultSchemaFile = Paths.get(System.getProperty("user.dir", ".")) + .resolve(SCHEMA_FILENAME); + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/javax/xml/bind/marshal/8134111/UnmarshalTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/javax/xml/bind/marshal/8134111/UnmarshalTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8134111 + * @summary test that elements without namespace is ignored by unmarshaller + * when elementFormDefault is set to QUALIFIED. + * @compile testTypes/package-info.java testTypes/Root.java + * testTypes/WhenType.java testTypes/ObjectFactory.java + * @modules java.xml.bind + * @run testng/othervm UnmarshalTest + */ + +import java.io.StringReader; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import org.testng.annotations.Test; +import static org.testng.Assert.assertNull; +import org.xml.sax.InputSource; +import testTypes.Root; + +public class UnmarshalTest { + + @Test + public void unmarshalUnexpectedNsTest() throws Exception { + JAXBContext context; + Unmarshaller unm; + // Create JAXB context from testTypes package + context = JAXBContext.newInstance("testTypes"); + // Create unmarshaller from JAXB context + unm = context.createUnmarshaller(); + // Unmarshall xml document with unqualified dtime element + Root r = (Root) unm.unmarshal(new InputSource(new StringReader(DOC))); + // Print dtime value and check if it is null + System.out.println("dtime is:"+r.getWhen().getDtime()); + assertNull(r.getWhen().getDtime()); + } + + //Xml document to unmarshall with unqualified dtime element + private final String DOC = + "" + + "" + + "2015-06-24T13:16:14.933-04:00" + + "" + + ""; +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/javax/xml/bind/marshal/8134111/testTypes/ObjectFactory.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/javax/xml/bind/marshal/8134111/testTypes/ObjectFactory.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package testTypes; + +import javax.xml.bind.annotation.XmlRegistry; + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the testTypes package. + * + */ +@XmlRegistry +public class ObjectFactory { + + /** + * Create a new ObjectFactory that can be used to create + * new instances of schema derived classes for package: testTypes + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link Root } + * + */ + public Root createRoot() { + return new Root(); + } + + /** + * Create an instance of {@link WhenType } + * + */ + public WhenType createWhenType() { + return new WhenType(); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/javax/xml/bind/marshal/8134111/testTypes/Root.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/javax/xml/bind/marshal/8134111/testTypes/Root.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package testTypes; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +/** + *

Java class for anonymous complex type. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = {"when"}) +@XmlRootElement(name = "root", + namespace = "http://www.example.org/testNamespace/") +public class Root { + + @XmlElement(required = true, + namespace = "http://www.example.org/testNamespace/") + protected WhenType when; + + /** + * Gets the value of the when property. + * + * @return + * possible object is + * {@link WhenType } + * + */ + public WhenType getWhen() { + return when; + } + + /** + * Sets the value of the when property. + * + * @param value + * allowed object is + * {@link WhenType } + * + */ + public void setWhen(WhenType value) { + this.when = value; + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/javax/xml/bind/marshal/8134111/testTypes/WhenType.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/javax/xml/bind/marshal/8134111/testTypes/WhenType.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package testTypes; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.datatype.XMLGregorianCalendar; + +/** + *

Java class for WhenType complex type. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "WhenType", + propOrder = {"dtime"}) +public class WhenType { + + @XmlElement(required = true) + @XmlSchemaType(name = "dateTime") + protected XMLGregorianCalendar dtime; + + /** + * Gets the value of the dtime property. + * + * @return + * possible object is + * {@link XMLGregorianCalendar } + * + */ + public XMLGregorianCalendar getDtime() { + return dtime; + } + + /** + * Sets the value of the dtime property. + * + * @param value + * allowed object is + * {@link XMLGregorianCalendar } + * + */ + public void setDtime(XMLGregorianCalendar value) { + this.dtime = value; + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/javax/xml/bind/marshal/8134111/testTypes/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/javax/xml/bind/marshal/8134111/testTypes/package-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +@javax.xml.bind.annotation.XmlSchema( + namespace = "http://www.example.org/testNamespace/", + elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +package testTypes; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/jdk/internal/jrtfs/remote/Main.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/jdk/internal/jrtfs/remote/Main.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.IOException; +import java.net.URI; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.stream.Stream; + +/** + * Basic jrt file system functionality testing + * + */ +public class Main { + + public static void main(String[] args) throws Exception { + String javaHome = args[0]; + FileSystem fs = null; + boolean isInstalled = false; + if (args.length == 2) { + fs = createFsByInstalledProvider(); + isInstalled = true; + } else { + fs = createFsWithURLClassloader(javaHome); + } + + Path mods = fs.getPath("/modules"); + try (Stream stream = Files.walk(mods)) { + stream.forEach(path -> { + path.getFileName(); + }); + } finally { + try { + fs.close(); + } catch (UnsupportedOperationException e) { + if (!isInstalled) { + throw new RuntimeException( + "UnsupportedOperationException is thrown unexpectedly"); + } + } + } + } + + private static FileSystem createFsWithURLClassloader(String javaHome) throws IOException{ + URL url = Paths.get(javaHome, "jrt-fs.jar").toUri().toURL(); + URLClassLoader loader = new URLClassLoader(new URL[] { url }); + return FileSystems.newFileSystem(URI.create("jrt:/"), null, loader); + } + + private static FileSystem createFsByInstalledProvider() throws IOException { + return FileSystems.getFileSystem(URI.create("jrt:/")); + } +} + diff -r 64f6ae06310e -r eda408d4f253 jdk/test/jdk/internal/jrtfs/remote/RemoteRuntimeImageTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/jdk/internal/jrtfs/remote/RemoteRuntimeImageTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8141609 + * @summary Verify JDK 8 can use jrt-fs.jar to work with jrt file system. + * @run main RemoteRuntimeImageTest + */ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; +public class RemoteRuntimeImageTest { + //the jrt-fs.jar shipped together with jdk + private static final String JRTFS_JAR = "jrt-fs.jar"; + private static final String SRC_DIR = System.getProperty("test.src"); + private static final String CLASSES_DIR = "classes"; + private static final String TEST_JAVAHOME = System.getProperty("test.jdk"); + + public static void main(String[] args) throws Exception { + // By default, set to ${JT_JAVA} + String jdk8Home = System.getenv("JDK8_HOME"); + if (jdk8Home == null || jdk8Home.isEmpty()) { + System.err.println("Failed to locate JDK8 with system " + + "environment variable 'JDK8_HOME'. Skip testing!"); + return; + } + + Path jdk8Path = getJdk8Path(jdk8Home); + if (!isJdk8(jdk8Path)) { + System.err.println("This test is only for JDK 8. Skip testing"); + return; + } + + String java = jdk8Path.resolve("bin/java").toAbsolutePath().toString(); + String javac = jdk8Path.resolve("bin/javac").toAbsolutePath().toString(); + + Files.createDirectories(Paths.get(".", CLASSES_DIR)); + String jrtJar = Paths.get(TEST_JAVAHOME, JRTFS_JAR).toAbsolutePath().toString(); + + // Compose command-lines for compiling and executing tests + List> cmds = Arrays.asList( + // Commands to compile test classes + Arrays.asList(javac, "-d", CLASSES_DIR, "-cp", jrtJar, + SRC_DIR + File.separatorChar + "Main.java"), + // Run test + Arrays.asList(java, "-cp", CLASSES_DIR, "Main", TEST_JAVAHOME), + // Run test with jrtfs.jar in class path, + // which means to install jrt FileSystem provider + Arrays.asList(java, "-cp", CLASSES_DIR + File.pathSeparatorChar + jrtJar, + "Main", TEST_JAVAHOME, "installed") + ); + + cmds.forEach(cmd -> execCmd(cmd)); + } + + private static void execCmd(List command){ + System.out.println(); + System.out.println("Executing command: " + command); + Process p = null; + try { + p = new ProcessBuilder(command).inheritIO().start(); + p.waitFor(); + int rc = p.exitValue(); + if (rc != 0) { + throw new RuntimeException("Unexpected exit code:" + rc); + } + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } finally { + if (p != null && p.isAlive()){ + p.destroy(); + } + } + } + + private static Path getJdk8Path(String jdk8Home) { + Path jdk8Path = Paths.get(jdk8Home); + // It is possible to point to the path of java executable by ${JT_JAVA} + return Files.isDirectory(jdk8Path)? jdk8Path : jdk8Path.getParent().getParent(); + } + + private static boolean isJdk8(Path jdk8Home) throws FileNotFoundException, IOException { + File file = jdk8Home.resolve("release").toFile(); + Properties props = new Properties(); + try (FileInputStream in = new FileInputStream(file)) { + props.load(in); + } + + String version = props.getProperty("JAVA_VERSION", ""); + System.out.println("JAVA_VERSION is " + version); + return version.startsWith("\"1.8"); + } +} + diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/README --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/README Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,45 @@ +This suite contains automated client sanity tests which can be run using JTReg. + +Contact alexander.kouznetsov@oracle.com in case of issues. + +------------------------------------------------------------------------------- +How to run: + +1) Download/Install the JDK to be tested in the system. + (For example C:/java/jdk1.9.0 in windows or + /export/jdk/jdk1.9.0 in linux/mac/solaris) +2) Download/Install JTReg harness, minimum required version is 4.1 b13. +3) Open terminal(cmd in windows, *not* cygwin) and go to the this directory. +4) To run + - see the notes below on how to prepare for the test run + - set JT_HOME to , for example + set JT_HOME=C:\Java\client\jtreg (Windows) + - run the command + 'sh -ea -k:\!screenshots -jdk: SwingSet' + + For example: 'sh C:/jtreg/bin/jtreg -ea -k:\!screenshots -jdk:C:/java/jdk1.9.0 SwingSet' (Windows) + 'sh /export/jtreg/bin/jtreg -ea -k:\!screenshots -jdk:/export/jdk/jdk1.9.0 SwingSet' (Linux/Solaris) + 'sh /export/jtreg/bin/jtreg -ea -k:\!screenshots -jdk:/export/jdk/jdk1.9.0/Contents/Home SwingSet' (Mac) + +Try to minimize all the other windows for no interference and test stability. +Do not touch keyboard or mouse, open any window, nor lock the screen while the tests are running. +The tests will be executed, and the results will be displayed in the terminal. + +A report will be generated under + a) JTReg: "JTReport/index.html". +The failure logs could be found under: + a) JTReg: "JTWork//.jtr" + +The following additional options might be useful: +-retain:all to keep work files for passed tests +-k:\!screenshots removal of this option will run tests that require full environment with Robot and screenshots +-g to run JavaTest GUI + +------------------------------------------------------------------------------- + +The tests in the suite are based on SwingSet3 demo application. They use Jemmy to +operate on controls of the demo and verify that it is behaving as expected. Both +Jemmy and SwingSet3 sources are available as copies in lib folder. + +Original Jemmy repository is https://jemmy.java.net +Original SwingSet3 repository is https://java.net/projects/swingset3 \ No newline at end of file diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/SwingSet/src/ButtonDemoScreenshotTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/SwingSet/src/ButtonDemoScreenshotTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.InputEvent; +import java.awt.image.BufferedImage; +import org.netbeans.jemmy.ClassReference; +import org.netbeans.jemmy.image.StrictImageComparator; +import org.netbeans.jemmy.operators.JButtonOperator; +import org.netbeans.jemmy.operators.JFrameOperator; +import static org.jemmy2ext.JemmyExt.*; +import org.testng.annotations.Test; +import static com.sun.swingset3.demos.button.ButtonDemo.*; + +/* + * @test + * @key headful screenshots + * @summary Verifies buttons on SwingSet3 ButtonDemo page by clicking each + * button, taking its screenshots and checking that pressed button + * image is different from initial button image. + * + * @library /sanity/client/lib/jemmy/src + * @library /sanity/client/lib/Jemmy2Ext/src + * @library /sanity/client/lib/SwingSet3/src + * @build org.jemmy2ext.JemmyExt + * @build com.sun.swingset3.demos.button.ButtonDemo + * @run testng ButtonDemoScreenshotTest + */ +public class ButtonDemoScreenshotTest { + + private static final int BUTTON_COUNT = 6; // TODO: Decide about "open browser" buttons (value was 8 originally) + + @Test + public void test() throws Exception { + captureDebugInfoOnFail(() -> { + Robot rob = new Robot(); + + new ClassReference(com.sun.swingset3.demos.button.ButtonDemo.class.getCanonicalName()).startApplication(); + + JFrameOperator mainFrame = new JFrameOperator(DEMO_TITLE); + waitImageIsStill(rob, mainFrame); + + // Check all the buttons + for (int i = 0; i < BUTTON_COUNT; i++) { + checkButton(mainFrame, i, rob); + } + }); + } + + public void checkButton(JFrameOperator jfo, int i, Robot rob) { + JButtonOperator button = new JButtonOperator(jfo, i); + + Point loc = button.getLocationOnScreen(); + rob.mouseMove(loc.x, loc.y); + + BufferedImage initialButtonImage = capture(rob, button); + assertNotBlack(initialButtonImage); + save(initialButtonImage, "button" + i + "_0initial.png"); + rob.mousePress(InputEvent.BUTTON1_MASK); + try { + waitPressed(button); + BufferedImage pressedButtonImage = capture(rob, button); + assertNotBlack(pressedButtonImage); + save(pressedButtonImage, "button" + i + "_1pressed.png"); + + StrictImageComparator sComparator = new StrictImageComparator(); + assertNotEquals("Button " + i + " Test", sComparator, initialButtonImage, pressedButtonImage); + } finally { + rob.mouseRelease(InputEvent.BUTTON1_MASK); + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/SwingSet/src/ButtonDemoTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/SwingSet/src/ButtonDemoTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.swingset3.demos.JHyperlink; +import com.sun.swingset3.demos.button.ButtonDemo; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import javax.swing.ButtonModel; +import javax.swing.JButton; +import javax.swing.event.ChangeEvent; +import static org.testng.AssertJUnit.*; +import org.testng.annotations.Test; +import org.jemmy2ext.JemmyExt.ByToolTipChooser; +import static org.jemmy2ext.JemmyExt.EXACT_STRING_COMPARATOR; +import org.netbeans.jemmy.ClassReference; +import org.netbeans.jemmy.operators.JButtonOperator; +import org.netbeans.jemmy.operators.JFrameOperator; +import static com.sun.swingset3.demos.button.ButtonDemo.*; +import org.jemmy2ext.JemmyExt; +import org.jemmy2ext.JemmyExt.MultiThreadedTryCatch; +import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail; + +/* + * @test + * @key headful + * @summary Verifies buttons on SwingSet3 ButtonDemo page by clicking each button + * and checking model change events. It also verifies tooltips and text + * on buttons before and after click. + * + * @library /sanity/client/lib/jemmy/src + * @library /sanity/client/lib/Jemmy2Ext/src + * @library /sanity/client/lib/SwingSet3/src + * @build org.jemmy2ext.JemmyExt + * @build com.sun.swingset3.demos.button.ButtonDemo + * @run testng ButtonDemoTest + */ +public class ButtonDemoTest { + + private static final String[] BUTTON_TEXT_AFTER = { + DO_IT_AGAIN,}; + + private static final String[] BUTTON_TEXT_BEFORE = { + DO_IT, + "", + FIND, + GO, + CONNECT, + "", + GET_MORE_INFO, + null + }; + + private static final String[] BUTTON_TOOLTIP = { + SIMPLE_BUTTON, + IMAGE_BUTTON, + BUTTON_WITH_TEXT_AND_IMAGE, + BUTTON_WITH_BACKGROUND_COLOR, + BUTTON_WITH_NO_BORDER, + BUTTON_WITH_ROLLOVER_IMAGE, + JAVA_SE_URL, + JAVA_BLOGS_URL + }; + + private static final String[] GOLDEN = { + "isArmed = false, isEnabled = true, isPressed = false, isSelected = false", + "isArmed = true, isEnabled = true, isPressed = false, isSelected = false", + "isArmed = true, isEnabled = true, isPressed = true, isSelected = false", + "isArmed = true, isEnabled = true, isPressed = false, isSelected = false", + "isArmed = false, isEnabled = true, isPressed = false, isSelected = false" + }; + + @Test + public void test() throws Exception { + + captureDebugInfoOnFail(() -> { + + new ClassReference(ButtonDemo.class.getCanonicalName()).startApplication(); + + JFrameOperator mainFrame = new JFrameOperator(DEMO_TITLE); + mainFrame.setComparator(EXACT_STRING_COMPARATOR); + + // Check all the buttons + for (int i = 0; i < BUTTON_TOOLTIP.length; i++) { + String tooltip = BUTTON_TOOLTIP[i]; + + JButtonOperator button = new JButtonOperator(mainFrame, new ByToolTipChooser(tooltip)); + + assertEquals(BUTTON_TEXT_BEFORE[i], button.getText()); + + // Two buttons are hyperlinks, we don't want to click them + if (!button.getSource().getClass().equals(JHyperlink.class)) { + checkButton(button); + } + + if (BUTTON_TEXT_AFTER.length > i) { + assertEquals(BUTTON_TEXT_AFTER[i], button.getText()); + } else { + assertEquals(BUTTON_TEXT_BEFORE[i], button.getText()); + } + } + + }); + } + + private void checkButton(JButtonOperator button) throws Exception { + MultiThreadedTryCatch tryCatch = new JemmyExt.MultiThreadedTryCatch(); + try { + BlockingQueue modelStateChanges = new ArrayBlockingQueue<>(GOLDEN.length); + button.getQueueTool().invokeAndWait(() -> { + try { + JButton jButton = (JButton) button.getSource(); + ButtonModel model = jButton.getModel(); + String line = toString(model); + System.out.println("Inital: " + line); + modelStateChanges.add(line); + model.addChangeListener((ChangeEvent e) -> { + try { + String line2 = toString(model); + System.out.println("ChangeEvent: " + line2); + + // We are only interested in the first GOLDEN.length events + if (modelStateChanges.remainingCapacity() > 0) { + modelStateChanges.add(line2); + } + } catch (RuntimeException | Error t) { + tryCatch.register(t); + } + }); + } catch (Error error) { + // All exceptions are already handled by Jemmy but Errors are not + tryCatch.register(error); + throw error; + } + }); + + assertEquals("Initial state check", GOLDEN[0], modelStateChanges.take()); + + button.clickMouse(); + + for (int state = 1; state < GOLDEN.length; state++) { + assertEquals(GOLDEN[state], modelStateChanges.take()); + } + } catch (RuntimeException | Error | InterruptedException t) { + tryCatch.registerRoot(t); + } finally { + tryCatch.throwRegistered(); + } + } + + private static String toString(ButtonModel model) { + return "isArmed = " + model.isArmed() + + ", isEnabled = " + model.isEnabled() + + ", isPressed = " + model.isPressed() + + ", isSelected = " + model.isSelected(); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/SwingSet/src/ComboBoxDemoTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/SwingSet/src/ComboBoxDemoTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.swingset3.demos.combobox.ComboBoxDemo; +import static org.testng.AssertJUnit.*; +import org.testng.annotations.Test; +import org.netbeans.jemmy.ClassReference; +import org.netbeans.jemmy.operators.JComboBoxOperator; +import org.netbeans.jemmy.operators.JFrameOperator; +import static com.sun.swingset3.demos.combobox.ComboBoxDemo.*; +import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail; + +/* + * @test + * @key headful + * @summary Verifies ComboBoxes on SwingSet2 ComboBoxDemo page by selecting + * each value of each ComboBox. + * + * @library /sanity/client/lib/jemmy/src + * @library /sanity/client/lib/Jemmy2Ext/src + * @library /sanity/client/lib/SwingSet3/src + * @build org.jemmy2ext.JemmyExt + * @build com.sun.swingset3.demos.combobox.ComboBoxDemo + * @run testng ComboBoxDemoTest + */ +public class ComboBoxDemoTest { + + private static enum ComboBoxInfo { + PRESETS("Presets:"), + HAIR("Hair:"), + EYES_N_NOSE("Eyes & Nose:"), + MOUTH("Mouth:"); + + private final String comboBoxName; + + private ComboBoxInfo(String comboBoxName) { + this.comboBoxName = comboBoxName; + } + + } + + @Test + public void test() throws Exception { + captureDebugInfoOnFail(() -> { + new ClassReference(ComboBoxDemo.class.getCanonicalName()).startApplication(); + + JFrameOperator frame = new JFrameOperator(DEMO_TITLE); + for (ComboBoxInfo comboBoxInfo : ComboBoxInfo.values()) { + comboBoxChecker(frame, comboBoxInfo); + } + }); + } + + private void comboBoxChecker(JFrameOperator jfo, ComboBoxInfo comboBoxInfo) { + JComboBoxOperator jcbo = new JComboBoxOperator(jfo, comboBoxInfo.ordinal()); + for (int i = 0; i < jcbo.getItemCount(); i++) { + jcbo.selectItem(i); + assertEquals(comboBoxInfo.comboBoxName + " ComboBox SelectedIndex is correct", i, jcbo.getSelectedIndex()); + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/SwingSet/src/ListDemoTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/SwingSet/src/ListDemoTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.swingset3.demos.list.ListDemo; +import static com.sun.swingset3.demos.list.ListDemo.DEMO_TITLE; +import static org.testng.AssertJUnit.*; +import org.testng.annotations.Test; +import static org.jemmy2ext.JemmyExt.getLabeledContainerOperator; +import org.netbeans.jemmy.ClassReference; +import org.netbeans.jemmy.operators.JCheckBoxOperator; +import org.netbeans.jemmy.operators.JFrameOperator; +import org.netbeans.jemmy.operators.JListOperator; +import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail; + +/* + * @test + * @key headful + * @summary Verifies SwingSet3 ListDemo page by checking and unchecking all + * the checkboxes on the page and verifying the number of items in the + * list. + * + * @library /sanity/client/lib/jemmy/src + * @library /sanity/client/lib/Jemmy2Ext/src + * @library /sanity/client/lib/SwingSet3/src + * @build org.jemmy2ext.JemmyExt + * @build com.sun.swingset3.demos.list.ListDemo + * @run testng ListDemoTest + */ +public class ListDemoTest { + + private static final int CHECKBOX_COUNT = 50; + + @Test + public void test() throws Exception { + captureDebugInfoOnFail(() -> { + new ClassReference(ListDemo.class.getCanonicalName()).startApplication(); + + JFrameOperator frame = new JFrameOperator(DEMO_TITLE); + JListOperator listOp = new JListOperator(frame); + + // Check *NO* Prefix and Suffixes Marked + for (int i = 0; i < CHECKBOX_COUNT; i++) { + JCheckBoxOperator checkBox = getJCheckBoxOperator(frame, i); + checkBox.changeSelection(false); + } + System.out.println("######## Number of Items = " + listOp.getModel().getSize()); + assertEquals("Select None number of items is correct", 0, listOp.getModel().getSize()); + + // Check *ALL* Prefix and Suffixes Marked + for (int i = 0; i < CHECKBOX_COUNT; i++) { + JCheckBoxOperator checkBox = getJCheckBoxOperator(frame, i); + checkBox.changeSelection(true); + } + System.out.println("######## Number of Items = " + listOp.getModel().getSize()); + assertEquals("Select All number of items is correct", CHECKBOX_COUNT / 2 * CHECKBOX_COUNT / 2, listOp.getModel().getSize()); + + // Check *ALL* Prefix and *NO* Suffixes Marked + for (int i = 0; i < CHECKBOX_COUNT; i++) { + JCheckBoxOperator checkBox = getJCheckBoxOperator(frame, i); + if (i < CHECKBOX_COUNT / 2) { + checkBox.changeSelection(true); + } else { + checkBox.changeSelection(false); + } + } + System.out.println("######## Number of Items = " + listOp.getModel().getSize()); + assertEquals("Select All Prefixes and NO Suffixes number of items is correct", 0, listOp.getModel().getSize()); + + // Check *NO* Prefix and *ALL* Suffixes Marked + for (int i = 0; i < CHECKBOX_COUNT; i++) { + JCheckBoxOperator checkBox = getJCheckBoxOperator(frame, i); + if (i < CHECKBOX_COUNT / 2) { + checkBox.changeSelection(false); + } else { + checkBox.changeSelection(true); + } + } + System.out.println("######## Number of Items = " + listOp.getModel().getSize()); + assertEquals("Select NO Prefixes and All Suffixes number of items is correct", 0, listOp.getModel().getSize()); + }); + } + + private JCheckBoxOperator getJCheckBoxOperator(JFrameOperator frame, int index) { + + // We map first half of indexes to the Prefixes panel and the second half + // to the Suffixes panel + String labelText; + int subindex; + if (index < CHECKBOX_COUNT / 2) { + labelText = "Prefixes"; + subindex = index; + } else { + labelText = "Suffixes"; + subindex = index - CHECKBOX_COUNT / 2; + } + + return new JCheckBoxOperator(getLabeledContainerOperator(frame, labelText), subindex); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/SwingSet/src/OptionPaneDemoTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/SwingSet/src/OptionPaneDemoTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,339 @@ +/* + * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.swingset3.demos.optionpane.OptionPaneDemo; +import static com.sun.swingset3.demos.optionpane.OptionPaneDemo.*; +import javax.swing.UIManager; +import static org.jemmy2ext.JemmyExt.*; +import static org.testng.AssertJUnit.*; +import org.testng.annotations.Test; +import org.netbeans.jemmy.ClassReference; +import org.netbeans.jemmy.operators.JButtonOperator; +import org.netbeans.jemmy.operators.JComboBoxOperator; +import org.netbeans.jemmy.operators.JDialogOperator; +import org.netbeans.jemmy.operators.JFrameOperator; +import org.netbeans.jemmy.operators.JLabelOperator; +import org.netbeans.jemmy.operators.JTextFieldOperator; + + +/* + * @test + * @key headful + * @summary Verifies SwingSet3 OptionPaneDemo page by opening all the dialogs + * and choosing different options in them. + * + * @library /sanity/client/lib/jemmy/src + * @library /sanity/client/lib/Jemmy2Ext/src + * @library /sanity/client/lib/SwingSet3/src + * @build org.jemmy2ext.JemmyExt + * @build com.sun.swingset3.demos.optionpane.OptionPaneDemo + * @run testng OptionPaneDemoTest + */ +public class OptionPaneDemoTest { + + public static final String SOME_TEXT_TO_TYPE = "I am some text"; + public static final String MESSAGE = UIManager.getString("OptionPane.messageDialogTitle"); + public static final String OK = "OK"; + public static final String CANCEL = "Cancel"; + public static final String INPUT = UIManager.getString("OptionPane.inputDialogTitle"); + public static final String TEXT_TO_TYPE = "Hooray! I'm a textField"; + public static final String NO = "No"; + public static final String YES = "Yes"; + public static final String SELECT_AN__OPTION = UIManager.getString("OptionPane.titleText"); + + @Test + public void test() throws Exception { + captureDebugInfoOnFail(() -> { + new ClassReference(OptionPaneDemo.class.getCanonicalName()).startApplication(); + + JFrameOperator frame = new JFrameOperator(DEMO_TITLE); + + showInputDialog(frame); + showWarningDialog(frame); + showMessageDialog(frame); + showComponentDialog(frame); + showConfirmationDialog(frame); + }); + } + + public void showInputDialog(JFrameOperator jfo) throws Exception { + // Cancel with text case + { + new JButtonOperator(jfo, INPUT_BUTTON).pushNoBlock(); + + JDialogOperator jdo = new JDialogOperator(INPUT); + JTextFieldOperator jto = new JTextFieldOperator(jdo); + jto.setText(SOME_TEXT_TO_TYPE); + + assertTrue("Show Input Dialog cancel w/ Text", jdo.isShowing()); + + new JButtonOperator(jdo, CANCEL).push(); + + assertFalse("Show Input Dialog cancel w/ Text", jdo.isShowing()); + } + + // Cancel with *NO* text case + { + new JButtonOperator(jfo, INPUT_BUTTON).pushNoBlock(); + + JDialogOperator jdo = new JDialogOperator(INPUT); + + assertTrue("Show Input Dialog cancel w/o Text", jdo.isShowing()); + + new JButtonOperator(jdo, CANCEL).push(); + + assertFalse("Show Input Dialog cancel w/o Text", jdo.isShowing()); + } + + // Text field has *NO* input + { + new JButtonOperator(jfo, INPUT_BUTTON).pushNoBlock(); + + JDialogOperator jdo = new JDialogOperator(INPUT); + + assertTrue("Show Input Dialog w/o Input", jdo.isShowing()); + + new JButtonOperator(jdo, OK).push(); + + assertFalse("Show Input Dialog w/o Input", jdo.isShowing()); + } + + // Text field has input + { + final String enteredText = "Rambo"; + + new JButtonOperator(jfo, INPUT_BUTTON).pushNoBlock(); + + JDialogOperator jdo = new JDialogOperator(INPUT); + JTextFieldOperator jto = new JTextFieldOperator(jdo); + jto.setText(enteredText); + new JButtonOperator(jdo, OK).pushNoBlock(); + + JDialogOperator jdo1 = new JDialogOperator(MESSAGE); + + assertTrue("Show Input Dialog w/ Input", jdo1.isShowing()); + + final String labelText = enteredText + INPUT_RESPONSE; + JLabelOperator jLabelOperator = new JLabelOperator(jdo1, labelText); + assertEquals("Text from the field made it into the dialog", labelText, jLabelOperator.getText()); + + new JButtonOperator(jdo1, OK).push(); + + assertFalse("Show Input Dialog w/ Input", jdo1.isShowing()); + } + } + + public void showWarningDialog(JFrameOperator jfo) throws Exception { + new JButtonOperator(jfo, WARNING_BUTTON).pushNoBlock(); + + JDialogOperator jdo = new JDialogOperator(WARNING_TITLE); + + assertTrue("Show Warning Dialog", jdo.isShowing()); + + new JButtonOperator(jdo, OK).push(); + + assertFalse("Show Warning Dialog", jdo.isShowing()); + } + + public void showMessageDialog(JFrameOperator jfo) throws Exception { + new JButtonOperator(jfo, MESSAGE_BUTTON).pushNoBlock(); + + JDialogOperator jdo = new JDialogOperator(MESSAGE); + + assertTrue("Show Message Dialog", jdo.isShowing()); + + new JButtonOperator(jdo, OK).push(); + + assertFalse("Show Message Dialog", jdo.isShowing()); + } + + public void showComponentDialog(JFrameOperator jfo) throws Exception { + // Case: Cancel + { + new JButtonOperator(jfo, COMPONENT_BUTTON).pushNoBlock(); + + JDialogOperator jdo = new JDialogOperator(COMPONENT_TITLE); + + assertTrue("Show Component Dialog Cancel Option", jdo.isShowing()); + + new JButtonOperator(jdo, COMPONENT_OP5).push(); + + assertFalse("Show Component Dialog Cancel Option", jdo.isShowing()); + } + + // Case: Yes option selected + { + new JButtonOperator(jfo, COMPONENT_BUTTON).pushNoBlock(); + + JDialogOperator jdo = new JDialogOperator(COMPONENT_TITLE); + new JButtonOperator(jdo, COMPONENT_OP1).pushNoBlock(); + + JDialogOperator jdo1 = new JDialogOperator(MESSAGE); + + assertTrue("Component Dialog Example Yes Option", jdo1.isShowing()); + + final String labelText = COMPONENT_R1; + JLabelOperator jLabelOperator = new JLabelOperator(jdo1, labelText); + assertEquals("Dialog contains appropriate text", labelText, jLabelOperator.getText()); + + new JButtonOperator(jdo1, OK).push(); + + assertFalse("Component Dialog Example Yes Option", jdo1.isShowing()); + } + + // Case: No option selected + { + new JButtonOperator(jfo, COMPONENT_BUTTON).pushNoBlock(); + + JDialogOperator jdo = new JDialogOperator(COMPONENT_TITLE); + new JButtonOperator(jdo, COMPONENT_OP2).pushNoBlock(); + + JDialogOperator jdo1 = new JDialogOperator(MESSAGE); + + assertTrue("Component Dialog Example No Option", jdo1.isShowing()); + + final String labelText = COMPONENT_R2; + JLabelOperator jLabelOperator = new JLabelOperator(jdo1, labelText); + assertEquals("Dialog contains appropriate text", labelText, jLabelOperator.getText()); + + new JButtonOperator(jdo1, OK).push(); + + assertFalse("Component Dialog Example No Option", jdo1.isShowing()); + } + + // Case: Maybe option selected + { + new JButtonOperator(jfo, COMPONENT_BUTTON).pushNoBlock(); + + JDialogOperator jdo = new JDialogOperator(COMPONENT_TITLE); + new JButtonOperator(jdo, COMPONENT_OP3).pushNoBlock(); + + JDialogOperator jdo1 = new JDialogOperator(MESSAGE); + + assertTrue("Component Dialog Maybe Yes Option", jdo1.isShowing()); + + final String labelText = COMPONENT_R3; + JLabelOperator jLabelOperator = new JLabelOperator(jdo1, labelText); + assertEquals("Dialog contains appropriate text", labelText, jLabelOperator.getText()); + + new JButtonOperator(jdo1, OK).push(); + + assertFalse("Component Dialog Maybe Yes Option", jdo1.isShowing()); + } + + // Case: Probably option selected + { + new JButtonOperator(jfo, COMPONENT_BUTTON).pushNoBlock(); + + JDialogOperator jdo = new JDialogOperator(COMPONENT_TITLE); + new JButtonOperator(jdo, COMPONENT_OP4).pushNoBlock(); + + JDialogOperator jdo1 = new JDialogOperator(MESSAGE); + + assertTrue("Component Dialog Example Probably Option", jdo1.isShowing()); + + final String labelText = COMPONENT_R4; + JLabelOperator jLabelOperator = new JLabelOperator(jdo1, labelText); + assertEquals("Dialog contains appropriate text", labelText, jLabelOperator.getText()); + + new JButtonOperator(jdo1, OK).push(); + + assertFalse("Component Dialog Example Probably Option", jdo1.isShowing()); + } + + // Case TextField and ComboBox functional + { + new JButtonOperator(jfo, COMPONENT_BUTTON).push(); + + JDialogOperator jdo = new JDialogOperator(COMPONENT_TITLE); + + JTextFieldOperator jto = new JTextFieldOperator(jdo); + jto.clearText(); + jto.typeText(TEXT_TO_TYPE); + + JComboBoxOperator jcbo = new JComboBoxOperator(jdo); + jcbo.selectItem(2); + + assertEquals("Show Component Dialog TextField", TEXT_TO_TYPE, jto.getText()); + assertEquals("Show Component Dialog ComboBox", 2, jcbo.getSelectedIndex()); + + new JButtonOperator(jdo, "cancel").push(); + } + } + + public void showConfirmationDialog(JFrameOperator jfo) throws Exception { + // Case: Yes option selected + { + new JButtonOperator(jfo, CONFIRM_BUTTON).pushNoBlock(); + + JDialogOperator jdo = new JDialogOperator(SELECT_AN__OPTION); + new JButtonOperator(jdo, YES).pushNoBlock(); + + JDialogOperator jdo1 = new JDialogOperator(MESSAGE); + + assertTrue("Show Confirmation Dialog Yes Option", jdo1.isShowing()); + + final String labelText = CONFIRM_YES; + JLabelOperator jLabelOperator = new JLabelOperator(jdo1, labelText); + assertEquals("Dialog contains appropriate text", labelText, jLabelOperator.getText()); + + new JButtonOperator(jdo1, OK).push(); + + assertFalse("Show Confirmation Dialog Yes Option", jdo1.isShowing()); + } + + // Case: No option selected + { + new JButtonOperator(jfo, CONFIRM_BUTTON).pushNoBlock(); + + JDialogOperator jdo = new JDialogOperator(SELECT_AN__OPTION); + new JButtonOperator(jdo, NO).pushNoBlock(); + + JDialogOperator jdo1 = new JDialogOperator(MESSAGE); + + assertTrue("Show Confirmation Dialog No Option", jdo1.isShowing()); + + final String labelText = CONFIRM_NO; + JLabelOperator jLabelOperator = new JLabelOperator(jdo1, labelText); + assertEquals("Dialog contains appropriate text", labelText, jLabelOperator.getText()); + + new JButtonOperator(jdo1, OK).push(); + + assertFalse("Show Confirmation Dialog No Option", jdo1.isShowing()); + } + + // Case: Cancel option selected + { + new JButtonOperator(jfo, CONFIRM_BUTTON).pushNoBlock(); + + JDialogOperator jdo = new JDialogOperator(SELECT_AN__OPTION); + + assertTrue("Show Confirmation Dialog Cancel Option", jdo.isShowing()); + + new JButtonOperator(jdo, CANCEL).push(); + + assertFalse("Show Confirmation Dialog Cancel Option", jdo.isShowing()); + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/SwingSet/src/ProgressBarDemoTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/SwingSet/src/ProgressBarDemoTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.swingset3.demos.progressbar.ProgressBarDemo; +import static com.sun.swingset3.demos.progressbar.ProgressBarDemo.*; +import java.awt.Component; +import static org.testng.AssertJUnit.*; +import org.testng.annotations.Test; +import org.netbeans.jemmy.ClassReference; +import org.netbeans.jemmy.ComponentChooser; +import org.netbeans.jemmy.operators.JButtonOperator; +import org.netbeans.jemmy.operators.JFrameOperator; +import org.netbeans.jemmy.operators.JProgressBarOperator; +import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail; + +/* + * @test + * @key headful + * @summary Verifies SwingSet3 ProgressBarDemo page by pressing start and stop + * buttons and checking the progress bar and the buttons state. + * + * @library /sanity/client/lib/jemmy/src + * @library /sanity/client/lib/Jemmy2Ext/src + * @library /sanity/client/lib/SwingSet3/src + * @build org.jemmy2ext.JemmyExt + * @build com.sun.swingset3.demos.progressbar.ProgressBarDemo + * @run testng ProgressBarDemoTest + */ +public class ProgressBarDemoTest { + + @Test + public void test() throws Exception { + captureDebugInfoOnFail(() -> { + new ClassReference(ProgressBarDemo.class.getCanonicalName()).startApplication(); + + JFrameOperator frame = new JFrameOperator(DEMO_TITLE); + + JButtonOperator startButton = new JButtonOperator(frame, START_BUTTON); + JButtonOperator stopButton = new JButtonOperator(frame, STOP_BUTTON); + JProgressBarOperator jpbo = new JProgressBarOperator(frame); + + // Check that progress completes and corect enable/disable of start/stop buttons + checkCompleteProgress(frame, startButton, stopButton, jpbo); + + // Check progess bar progression and start/stop button disabled/enabled states + checkStartStop(frame, startButton, stopButton, jpbo); + }); + } + + // Check that progress completes and corect enable/disable of start/stop buttons + public void checkStartStop(JFrameOperator frame, JButtonOperator startButton, JButtonOperator stopButton, JProgressBarOperator progressBar) throws Exception { + int initialProgress = progressBar.getValue(); + System.out.println("initialProgress = " + initialProgress); + int maximum = progressBar.getMaximum(); + + startButton.pushNoBlock(); + + progressBar.waitState(new ComponentChooser() { + + @Override + public boolean checkComponent(Component comp) { + int value = progressBar.getValue(); + System.out.println("checkComponent1 value = " + value); + return value < maximum; + } + + @Override + public String getDescription() { + return "Progress < maximum (" + maximum + ")"; + } + }); + + stopButton.waitComponentEnabled(); + + progressBar.waitState(new ComponentChooser() { + + @Override + public boolean checkComponent(Component comp) { + int value = progressBar.getValue(); + System.out.println("checkComponent2 value = " + value); + return value > 0; + } + + @Override + public String getDescription() { + return "Progress > 0"; + } + }); + + int progress = progressBar.getValue(); + System.out.println("progress = " + progress); + + //Check that progress par has progressed and Start Button Disabled + assertTrue("Progress Bar Progressing (progress > 0, actual value: " + progress + ")", progress > 0); + assertFalse("Start Button Disabled", startButton.isEnabled()); + assertTrue("Stop Button Enabled", stopButton.isEnabled()); + + //Wait a liitle bit longer then Press stop get progress + progressBar.waitState(new ComponentChooser() { + + @Override + public boolean checkComponent(Component comp) { + return progressBar.getValue() > progress; + } + + @Override + public String getDescription() { + return "Progress > " + progress; + } + }); + + stopButton.pushNoBlock(); + + startButton.waitComponentEnabled(); + + int interimProgress = progressBar.getValue(); + + // Check that progress par has Stopped and Start Button Disabled + assertTrue("Progress Bar Stopped " + + "(interimProgress, actual value: " + interimProgress + " " + + "> progress, actual value: " + progress + ")", + interimProgress > progress); + assertTrue("Start Button Enabled", startButton.isEnabled()); + assertFalse("Stop Button Disabled", stopButton.isEnabled()); + } + + // Check progess bar progression and start/stop button disabled/enabled states + public void checkCompleteProgress(JFrameOperator frame, JButtonOperator startButton, JButtonOperator stopButton, JProgressBarOperator progressBar) throws Exception { + startButton.pushNoBlock(); + + progressBar.waitValue(progressBar.getMaximum()); + + startButton.waitComponentEnabled(); + + assertEquals("Complete Progress", progressBar.getMaximum(), progressBar.getValue()); + assertTrue("Start Button Enabled", startButton.isEnabled()); + assertFalse("Stop Button Disabled", stopButton.isEnabled()); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/SwingSet/src/ScrollPaneDemoTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/SwingSet/src/ScrollPaneDemoTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.swingset3.demos.scrollpane.ScrollPaneDemo; +import static com.sun.swingset3.demos.scrollpane.ScrollPaneDemo.DEMO_TITLE; +import static org.testng.AssertJUnit.*; +import org.testng.annotations.Test; +import org.netbeans.jemmy.ClassReference; +import org.netbeans.jemmy.operators.JFrameOperator; +import org.netbeans.jemmy.operators.JScrollPaneOperator; +import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail; + +/* + * @test + * @key headful + * @summary Verifies SwingSet3 ScrollPaneDemo by scrolling to bottom, to top, + * to left and to right and checking scroll bar values. + * + * @library /sanity/client/lib/jemmy/src + * @library /sanity/client/lib/Jemmy2Ext/src + * @library /sanity/client/lib/SwingSet3/src + * @build org.jemmy2ext.JemmyExt + * @build com.sun.swingset3.demos.scrollpane.ScrollPaneDemo + * @run testng ScrollPaneDemoTest + */ +public class ScrollPaneDemoTest { + + @Test + public void test() throws Exception { + captureDebugInfoOnFail(() -> { + new ClassReference(ScrollPaneDemo.class.getName()).startApplication(); + + JFrameOperator frame = new JFrameOperator(DEMO_TITLE); + JScrollPaneOperator jspo = new JScrollPaneOperator(frame); + + // Set initial scrollbar positions + int initialVerticalValue = jspo.getVerticalScrollBar().getValue(); + int initialHorizontalValue = jspo.getHorizontalScrollBar().getValue(); + + System.out.println("Initial Vertical Value = " + jspo.getVerticalScrollBar().getValue()); + System.out.println("Initial HoriZontal Value = " + jspo.getHorizontalScrollBar().getValue()); + + // Check scroll to Bottom + { + jspo.scrollToBottom(); + int currentValue = jspo.getVerticalScrollBar().getValue(); + System.out.println("Final Value = " + currentValue); + assertTrue("Scroll to Bottom of Pane " + + "(initialVerticalValue, actual value: " + initialVerticalValue + " " + + "< currentValue, actual value = " + currentValue + ")", + initialVerticalValue < currentValue); + } + + // Check scroll to Top + { + jspo.scrollToTop(); + int currentValue = jspo.getVerticalScrollBar().getValue(); + System.out.println("Top Scroll Final Value = " + currentValue); + assertTrue("Scroll to Top of Pane " + + "(initialVerticalValue, actual value: " + initialVerticalValue + " " + + "> currentValue, actual value = " + currentValue + ")", + initialVerticalValue > currentValue); + } + + // Check scroll to Left + { + jspo.scrollToLeft(); + int currentValue = jspo.getHorizontalScrollBar().getValue(); + System.out.println("Scroll to Left Final Value = " + currentValue); + assertTrue("Scroll to Left of Pane " + + "(initialHorizontalValue, actual value: " + initialHorizontalValue + " " + + "> currentValue, actual value = " + currentValue + ")", + initialHorizontalValue > currentValue); + } + + // Check scroll to Right + { + jspo.scrollToRight(); + int currentValue = jspo.getHorizontalScrollBar().getValue(); + System.out.println("Scroll to Right Final Value = " + currentValue); + assertTrue("Scroll to Right of Pane " + + "(initialHorizontalValue, actual value: " + initialHorizontalValue + " " + + "< currentValue, actual value = " + currentValue + ")", + initialHorizontalValue < currentValue); + } + }); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/SwingSet/src/SpinnerDemoTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/SwingSet/src/SpinnerDemoTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.swingset3.demos.spinner.SpinnerDemo; +import static com.sun.swingset3.demos.spinner.SpinnerDemo.DEMO_TITLE; +import java.text.DecimalFormat; +import static org.testng.AssertJUnit.*; +import org.testng.annotations.Test; +import org.netbeans.jemmy.ClassReference; +import org.netbeans.jemmy.operators.JFrameOperator; +import org.netbeans.jemmy.operators.JSpinnerOperator; +import org.netbeans.jemmy.operators.JTextFieldOperator; +import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail; + +/* + * @test + * @key headful + * @summary Verifies SwingSet3 SpinnerDemo by adjusting each spinner value via + * the spinner button and checking text field value. + * + * @library /sanity/client/lib/jemmy/src + * @library /sanity/client/lib/Jemmy2Ext/src + * @library /sanity/client/lib/SwingSet3/src + * @build org.jemmy2ext.JemmyExt + * @build com.sun.swingset3.demos.spinner.SpinnerDemo + * @run testng SpinnerDemoTest + */ +public class SpinnerDemoTest { + + private static final int SPINNERS_COUNT = 9; + private static final DecimalFormat decimalFormat = new DecimalFormat(); + + @Test + public void test() throws Exception { + captureDebugInfoOnFail(() -> { + new ClassReference(SpinnerDemo.class.getCanonicalName()).startApplication(); + + JFrameOperator frame = new JFrameOperator(DEMO_TITLE); + + // Check changing different spinners + for (int i = 0; i < SPINNERS_COUNT; i++) { + changeValues(frame, i); + } + }); + } + + private void changeValues(JFrameOperator jfo, int spinnerIndex) throws Exception { + JSpinnerOperator spinner = new JSpinnerOperator(jfo, spinnerIndex); + JTextFieldOperator jtfo = new JTextFieldOperator(spinner); + float originalFieldValue = decimalFormat.parse(jtfo.getText()).floatValue(); + float finalFieldValue; + + // increment by one the value via spinner + spinner.getIncreaseOperator().push(); + finalFieldValue = decimalFormat.parse(jtfo.getText()).floatValue(); + + // check that the value was increased + assertTrue("Increment Spinner " + spinner + + " (originalFieldValue, actual value: " + originalFieldValue + " " + + "< finalFieldValue, actual value = " + finalFieldValue + ")", + originalFieldValue < finalFieldValue); + + // decrease value via spinner + spinner.getDecreaseOperator().push(); + finalFieldValue = decimalFormat.parse(jtfo.getText()).floatValue(); + + // check that the value was decrimented + assertTrue("Decrement Spinner " + spinner + + " (originalFieldValue, actual value: " + originalFieldValue + " " + + ">= finalFieldValue, actual value = " + finalFieldValue + ")", + originalFieldValue >= finalFieldValue); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/SwingSet/src/SplitPaneDemoTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/SwingSet/src/SplitPaneDemoTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.swingset3.demos.splitpane.SplitPaneDemo; +import static com.sun.swingset3.demos.splitpane.SplitPaneDemo.*; +import java.awt.event.KeyEvent; +import javax.swing.JSplitPane; +import static org.testng.AssertJUnit.*; +import org.testng.annotations.Test; +import org.netbeans.jemmy.ClassReference; +import org.netbeans.jemmy.operators.JButtonOperator; +import org.netbeans.jemmy.operators.JCheckBoxOperator; +import org.netbeans.jemmy.operators.JFrameOperator; +import org.netbeans.jemmy.operators.JRadioButtonOperator; +import org.netbeans.jemmy.operators.JSplitPaneOperator; +import org.netbeans.jemmy.operators.JTextFieldOperator; +import static org.jemmy2ext.JemmyExt.*; + +/* + * @test + * @key headful + * @summary Verifies SwingSet3 SplitPaneDemo by performing OneClick expansion, + * changing size of the divier, moving the divider to different positions + * and changing the divider orientation. + * + * @library /sanity/client/lib/jemmy/src + * @library /sanity/client/lib/Jemmy2Ext/src + * @library /sanity/client/lib/SwingSet3/src + * @build org.jemmy2ext.JemmyExt + * @build com.sun.swingset3.demos.splitpane.SplitPaneDemo + * @run testng SplitPaneDemoTest + */ +public class SplitPaneDemoTest { + + @Test + public void test() throws Exception { + captureDebugInfoOnFail(() -> { + new ClassReference(SplitPaneDemo.class.getCanonicalName()).startApplication(); + + JFrameOperator frame = new JFrameOperator(DEMO_TITLE); + + JSplitPaneOperator splitPane = new JSplitPaneOperator(frame); + + // Toggle OneTouch Expandable + checkOneTouch(frame, splitPane, true); + checkOneTouch(frame, splitPane, false); + + // Check changing divider size to minimum and maximum values + changeDividerSize(frame, splitPane, 50); + changeDividerSize(frame, splitPane, 6); + + // Check moving the divider + checkDividerMoves(frame, splitPane, false); + checkDividerMoves(frame, splitPane, true); + + // Check different minumum Day/Night sizes + changeMinimumSizes(frame, splitPane, 100); + changeMinimumSizes(frame, splitPane, 0); + }); + } + + // Check for different day and night minimum size + public void changeMinimumSizes(JFrameOperator frame, JSplitPaneOperator splitPane, int amount) throws Exception { + for (String label : new String[]{FIRST_COMPONENT_MIN_SIZE, SECOND_COMPONENT_MIN_SIZE}) { + JTextFieldOperator size = new JTextFieldOperator(getLabeledContainerOperator(frame, label)); + size.enterText(Integer.toString(amount)); + size.pressKey(KeyEvent.VK_ENTER); + } + checkDividerMoves(frame, splitPane, false); + checkDividerMoves(frame, splitPane, true); + } + + // Check moving of divider + public void checkDividerMoves(JFrameOperator frame, JSplitPaneOperator splitPane, boolean isVertical) throws Exception { + if (isVertical) { + new JRadioButtonOperator(frame, VERTICAL_SPLIT).doClick(); + } else { + new JRadioButtonOperator(frame, HORIZONTAL_SPLIT).doClick(); + } + + splitPane.moveDivider(0.0); + assertEquals("Move Minimum, dividerLocation is at minimumDividerLocation", + splitPane.getMinimumDividerLocation(), splitPane.getDividerLocation()); + + // use getMaximumDividerLocation() to move divider to here because using proportion 1.0 does not work + splitPane.moveDivider(1.0); + + assertEquals("Move Maximum, dividerLocation is at maximumDividerLocation", + splitPane.getMaximumDividerLocation(), splitPane.getDividerLocation()); + + splitPane.moveDivider(0.5); + assertEquals("Move Middle, dividerLocation is at the artithmetic average of minimum and maximum DividerLocations", + (splitPane.getMaximumDividerLocation() + splitPane.getMinimumDividerLocation()) / 2, splitPane.getDividerLocation()); + } + + // Check changing the size of the divider + public void changeDividerSize(JFrameOperator frame, JSplitPaneOperator splitPane, int amount) throws Exception { + JTextFieldOperator size = new JTextFieldOperator(getLabeledContainerOperator(frame, DIVIDER_SIZE)); + size.clearText(); + size.typeText(Integer.toString(amount)); + size.pressKey(KeyEvent.VK_ENTER); + + assertEquals("Change Divider Size", amount, splitPane.getDividerSize()); + } + + public void checkOneTouch(JFrameOperator frame, JSplitPaneOperator splitPane, boolean oneTouch) throws Exception { + JCheckBoxOperator checkBox = new JCheckBoxOperator(frame, ONE_TOUCH_EXPANDABLE); + JButtonOperator buttonLeft = new JButtonOperator(splitPane.getDivider(), 0); + JButtonOperator buttonRight = new JButtonOperator(splitPane.getDivider(), 1); + int initDividerLocation = splitPane.getDividerLocation(); + + if (oneTouch) { + if (!checkBox.isSelected()) { + // uncheck + checkBox.doClick(); + } + + int left = getUIValue(splitPane, (JSplitPane sp) -> sp.getInsets().left); + System.out.println("left = " + left); + int right = getUIValue(splitPane, (JSplitPane sp) -> sp.getInsets().right); + System.out.println("right = " + right); + + // expand full left + buttonLeft.push(); + assertEquals("Expandable Left", left, splitPane.getDividerLocation()); + + // expand back from full left + buttonRight.push(); + assertEquals("Expandable Back to Original from Left", + initDividerLocation, splitPane.getDividerLocation()); + + // expand all the way right + buttonRight.push(); + assertEquals("Expandable Right", + splitPane.getWidth() - splitPane.getDividerSize() - right, + splitPane.getDividerLocation()); + + // Click to move back from right expansion + buttonLeft.push(); + assertEquals("Expandable Back to Original from Right", + initDividerLocation, splitPane.getDividerLocation()); + } + + // Test for case where one touch expandable is disabled + if (!oneTouch) { + if (checkBox.isSelected()) { + // uncheck + checkBox.doClick(); + } + assertFalse("One Touch Expandable Off", splitPane.isOneTouchExpandable()); + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/SwingSet/src/TabbedPaneDemoTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/SwingSet/src/TabbedPaneDemoTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.swingset3.demos.tabbedpane.TabbedPaneDemo; +import static com.sun.swingset3.demos.tabbedpane.TabbedPaneDemo.*; +import static org.jemmy2ext.JemmyExt.getLabeledContainerOperator; +import static org.testng.AssertJUnit.*; +import org.testng.annotations.Test; +import org.netbeans.jemmy.ClassReference; +import org.netbeans.jemmy.operators.ContainerOperator; +import org.netbeans.jemmy.operators.JFrameOperator; +import org.netbeans.jemmy.operators.JRadioButtonOperator; +import org.netbeans.jemmy.operators.JTabbedPaneOperator; +import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail; + +/* + * @test + * @key headful + * @summary Verifies SwingSet3 TabbedPaneDemo by iterating through tab placement + * positions, opening each tab and verifying the the tab gets selected. + * + * @library /sanity/client/lib/jemmy/src + * @library /sanity/client/lib/Jemmy2Ext/src + * @library /sanity/client/lib/SwingSet3/src + * @build org.jemmy2ext.JemmyExt + * @build com.sun.swingset3.demos.tabbedpane.TabbedPaneDemo + * @run testng TabbedPaneDemoTest + */ +public class TabbedPaneDemoTest { + + @Test + public void test() throws Exception { + captureDebugInfoOnFail(() -> { + new ClassReference(TabbedPaneDemo.class.getCanonicalName()).startApplication(); + + JFrameOperator mainFrame = new JFrameOperator(DEMO_TITLE); + + for (String tp : new String[]{TOP, LEFT, BOTTOM, RIGHT}) { + testTabs(mainFrame, tp); + } + }); + } + + public void testTabs(JFrameOperator mainFrame, String tabPlacement) throws Exception { + ContainerOperator rbCont = getLabeledContainerOperator(mainFrame, TAB_PLACEMENT); + new JRadioButtonOperator(rbCont, tabPlacement).doClick(); + + final String[] tabTitles = new String[]{CAMILLE, MIRANDA, EWAN, BOUNCE}; + for (int i = 0; i < tabTitles.length; i++) { + String pageTitle = tabTitles[i]; + JTabbedPaneOperator tabOperator = new JTabbedPaneOperator(mainFrame); + tabOperator.selectPage(pageTitle); + + assertEquals("Selected tab is selected", i, tabOperator.getSelectedIndex()); + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/SwingSet/src/TextFieldDemoTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/SwingSet/src/TextFieldDemoTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.swingset3.demos.textfield.JHistoryTextField; +import com.sun.swingset3.demos.textfield.TextFieldDemo; +import static com.sun.swingset3.demos.textfield.TextFieldDemo.*; +import java.awt.Color; +import java.awt.event.KeyEvent; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import javax.swing.JFormattedTextField; +import static org.jemmy2ext.JemmyExt.*; +import static org.testng.AssertJUnit.*; +import org.testng.annotations.Test; +import org.netbeans.jemmy.ClassReference; +import org.netbeans.jemmy.QueueTool; +import org.netbeans.jemmy.operators.ContainerOperator; +import org.netbeans.jemmy.operators.JButtonOperator; +import org.netbeans.jemmy.operators.JFrameOperator; +import org.netbeans.jemmy.operators.JLabelOperator; +import org.netbeans.jemmy.operators.JPasswordFieldOperator; +import org.netbeans.jemmy.operators.JTextFieldOperator; + +/* + * @test + * @key headful + * @summary Verifies SwingSet3 TextFieldDemo by entering text in each field and + * checking that app reacts accordingly. + * + * @library /sanity/client/lib/jemmy/src + * @library /sanity/client/lib/Jemmy2Ext/src + * @library /sanity/client/lib/SwingSet3/src + * @build org.jemmy2ext.JemmyExt + * @build com.sun.swingset3.demos.textfield.TextFieldDemo + * @run testng TextFieldDemoTest + */ +public class TextFieldDemoTest { + + @Test + public void test() throws Exception { + captureDebugInfoOnFail(() -> { + new ClassReference(TextFieldDemo.class.getCanonicalName()).startApplication(); + + JFrameOperator frame = new JFrameOperator(DEMO_TITLE); + + historyTextField(frame); + dateTextField(frame); + passwordField(frame); + }); + } + + private void historyTextField(JFrameOperator jfo) throws Exception { + JTextFieldOperator jtfo = new JTextFieldOperator(jfo, new ByClassChooser(JHistoryTextField.class)); + jtfo.typeText("cat"); + + jtfo.pressKey(KeyEvent.VK_DOWN); + jtfo.pressKey(KeyEvent.VK_DOWN); + jtfo.pressKey(KeyEvent.VK_ENTER); + + final String expectedValue = "category"; + jtfo.waitText(expectedValue); + assertEquals("Select History Item", expectedValue, jtfo.getText()); + } + + public void dateTextField(JFrameOperator jfo) throws Exception { + JTextFieldOperator jtfo = new JTextFieldOperator(jfo, + new ByClassChooser(JFormattedTextField.class)); + ContainerOperator containerOperator = new ContainerOperator<>(jtfo.getParent()); + JButtonOperator jbo = new JButtonOperator(containerOperator, GO); + JLabelOperator dowLabel = new JLabelOperator(containerOperator); + Calendar calendar = Calendar.getInstance(Locale.ENGLISH); + + // Check default date Day of the Week + jbo.push(); + assertEquals("Default DOW", + calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.ENGLISH), + dowLabel.getText()); + + // Check Custom Day of the Week + calendar.set(2012, 9, 11); // Represents "Oct 11, 2012" + Date date = calendar.getTime(); + String dateString = jtfo.getQueueTool().invokeAndWait( + new QueueTool.QueueAction("Formatting the value using JFormattedTextField formatter") { + + @Override + public String launch() throws Exception { + return ((JFormattedTextField) jtfo.getSource()).getFormatter().valueToString(date); + } + }); + System.out.println("dateString = " + dateString); + jtfo.enterText(dateString); + + jbo.push(); + assertEquals("Custom DOW", "Thursday", dowLabel.getText()); + } + + public void passwordField(JFrameOperator jfo) throws Exception { + JPasswordFieldOperator password1 = new JPasswordFieldOperator(jfo, 0); + JPasswordFieldOperator password2 = new JPasswordFieldOperator(jfo, 1); + + password1.typeText("password"); + password2.typeText("password"); + + // Check Matching Passwords + assertEquals("Matching Passwords", Color.green, password1.getBackground()); + assertEquals("Matching Passwords", Color.green, password2.getBackground()); + + // Check non-matching passwords + password2.typeText("passwereertegrs"); + assertEquals("Non-Matching Passwords", Color.white, password1.getBackground()); + assertEquals("Non-Matching Passwords", Color.white, password2.getBackground()); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/SwingSet/src/ToggleButtonDemoTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/SwingSet/src/ToggleButtonDemoTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.swingset3.DemoProperties; +import com.sun.swingset3.demos.togglebutton.DirectionPanel; +import com.sun.swingset3.demos.togglebutton.LayoutControlPanel; +import com.sun.swingset3.demos.togglebutton.ToggleButtonDemo; +import static com.sun.swingset3.demos.togglebutton.ToggleButtonDemo.*; +import java.util.function.BiFunction; +import org.jemmy2ext.JemmyExt.ByClassChooser; +import static org.jemmy2ext.JemmyExt.EXACT_STRING_COMPARATOR; +import static org.jemmy2ext.JemmyExt.getBorderTitledJPanelOperator; +import static org.jemmy2ext.JemmyExt.getLabeledContainerOperator; +import static org.testng.AssertJUnit.*; +import org.testng.annotations.Test; +import org.netbeans.jemmy.ClassReference; +import org.netbeans.jemmy.ComponentChooser; +import org.netbeans.jemmy.operators.ContainerOperator; +import org.netbeans.jemmy.operators.JCheckBoxOperator; +import org.netbeans.jemmy.operators.JFrameOperator; +import org.netbeans.jemmy.operators.JRadioButtonOperator; +import org.netbeans.jemmy.operators.JTabbedPaneOperator; +import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail; + +/* + * @test + * @key headful + * @summary Verifies SwingSet3 ToggleButtonDemo by toggling each radio button, + * each checkbox and each location of the direction dial toggle. + * It verifies initial selected values for all the elements and checks + * that those change upon clicking. When toggling radio buttons it + * verifies that other radio buttons in the same group are not longer + * selected. + * + * @library /sanity/client/lib/jemmy/src + * @library /sanity/client/lib/Jemmy2Ext/src + * @library /sanity/client/lib/SwingSet3/src + * @build org.jemmy2ext.JemmyExt + * @build com.sun.swingset3.demos.togglebutton.ToggleButtonDemo + * @run testng ToggleButtonDemoTest + */ +public class ToggleButtonDemoTest { + + @Test + public void test() throws Exception { + captureDebugInfoOnFail(() -> { + new ClassReference(ToggleButtonDemo.class.getCanonicalName()).startApplication(); + + JFrameOperator mainFrame = new JFrameOperator(ToggleButtonDemo.class.getAnnotation(DemoProperties.class).value()); + JTabbedPaneOperator tabPane = new JTabbedPaneOperator(mainFrame); + + // Radio Button Toggles + testRadioButtons(getBorderTitledJPanelOperator(mainFrame, TEXT_RADIO_BUTTONS), 3, null); + testRadioButtons(getBorderTitledJPanelOperator(mainFrame, IMAGE_RADIO_BUTTONS), 3, null); + testRadioButtons(getLabeledContainerOperator(mainFrame, PAD_AMOUNT), 3, (t, i) -> DEFAULT.equals(t)); + + // switch to the Check Boxes Tab + tabPane.selectPage(CHECK_BOXES); + + // Check Box Toggles + ContainerOperator textCheckBoxesJPanel = getBorderTitledJPanelOperator(mainFrame, TEXT_CHECKBOXES); + testCheckBox(textCheckBoxesJPanel, CHECK1, false); + testCheckBox(textCheckBoxesJPanel, CHECK2, false); + testCheckBox(textCheckBoxesJPanel, CHECK3, false); + + ContainerOperator imageCheckBoxesJPanel = getBorderTitledJPanelOperator(mainFrame, IMAGE_CHECKBOXES); + testCheckBox(imageCheckBoxesJPanel, CHECK1, false); + testCheckBox(imageCheckBoxesJPanel, CHECK2, false); + testCheckBox(imageCheckBoxesJPanel, CHECK3, false); + + ContainerOperator displayOptionsContainer = getLabeledContainerOperator(mainFrame, DISPLAY_OPTIONS); + testCheckBox(displayOptionsContainer, PAINT_BORDER, false); + testCheckBox(displayOptionsContainer, PAINT_FOCUS, true); + testCheckBox(displayOptionsContainer, ENABLED, true); + testCheckBox(displayOptionsContainer, CONTENT_FILLED, true); + + // Direction Button Toggles + testToggleButtons(mainFrame); + }); + } + + /** + * The interface is invoked for each radio button providing its name and + * index and it should return whether the radio button has to be selected. + */ + private static interface SelectedRadioButton extends BiFunction { + } + + /** + * Tests a group of radio buttons + * + * @param parent container containing the buttons + * @param radioButtonCount number of radio buttons + * @param selectedRadioButton initial selected radio button + */ + private void testRadioButtons(ContainerOperator parent, int radioButtonCount, SelectedRadioButton selectedRadioButton) { + JRadioButtonOperator[] jrbo = new JRadioButtonOperator[radioButtonCount]; + for (int i = 0; i < radioButtonCount; i++) { + jrbo[i] = new JRadioButtonOperator(parent, i); + if (selectedRadioButton != null && selectedRadioButton.apply(jrbo[i].getText(), i)) { + assertTrue("Radio Button " + i + " is initially selected", jrbo[i].isSelected()); + } else { + assertFalse("Radio Button " + i + " is initially not selected", jrbo[i].isSelected()); + } + } + + for (int i = 0; i < radioButtonCount; i++) { + jrbo[i].doClick(); + assertTrue("Radio Button " + i + " is selected", jrbo[i].isSelected()); + + for (int j = 0; j < radioButtonCount; j++) { + if (i != j) { + assertFalse("Radio Button " + j + " is not selected", jrbo[j].isSelected()); + } + } + } + } + + /** + * Will change the state of the CheckBox then change back to initial state. + * + * @param parent + * @param text + * @param expectedValue + * @throws Exception + */ + private void testCheckBox(ContainerOperator parent, String text, boolean expectedValue) { + + parent.setComparator(EXACT_STRING_COMPARATOR); + JCheckBoxOperator jcbo = new JCheckBoxOperator(parent, text); + assertEquals("Initial selection state of the checkbox '" + text + "'", expectedValue, jcbo.isSelected()); + + // click check box (toggle the state) + jcbo.doClick(); + assertEquals("Selection state of the checkbox '" + text + "' after click", !expectedValue, jcbo.isSelected()); + if (jcbo.isSelected()) { + // toggle back to not-selected state + jcbo.doClick(); + assertFalse("Check Box '" + text + "' is not selected", jcbo.isSelected()); + } else { + // toggle back to selected state + jcbo.doClick(); + + assertTrue("Check Box '" + text + "' is selected", jcbo.isSelected()); + } + } + + + /* + * testDirectionRadioButtons(JFrameOperator) will toggle each position of + * the direction radio button panels + */ + private void testToggleButtons(JFrameOperator jfo) { + ComponentChooser directionPanelChooser = new ByClassChooser(DirectionPanel.class); + + String text_Position = LayoutControlPanel.TEXT_POSITION; + ContainerOperator textPositionContainer = getLabeledContainerOperator(jfo, text_Position); + ContainerOperator directionPanelOperator = new ContainerOperator<>(textPositionContainer, directionPanelChooser); + testRadioButtons(directionPanelOperator, 9, (t, i) -> i == 5); + + // Unfortunately, both directionPanels are in the same parent container + // so we have to use indexes here. + // There is no guarantee that if the UI changes, the code would be still + // valid in terms of which directionPanel is checked first. However, it + // does guarantee that two different directionPanels are checked. + String content_Alignment = LayoutControlPanel.CONTENT_ALIGNMENT; + ContainerOperator contentAlignmentContainer = getLabeledContainerOperator(jfo, content_Alignment); + ContainerOperator directionPanelOperator2 = new ContainerOperator<>(contentAlignmentContainer, directionPanelChooser, + contentAlignmentContainer.getSource() == textPositionContainer.getSource() ? 1 : 0); + testRadioButtons(directionPanelOperator2, 9, (t, i) -> i == 4); + + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/SwingSet/src/TreeDemoTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/SwingSet/src/TreeDemoTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.swingset3.demos.tree.TreeDemo; +import static com.sun.swingset3.demos.tree.TreeDemo.DEMO_TITLE; +import javax.swing.tree.TreePath; +import static org.testng.AssertJUnit.*; +import org.testng.annotations.Test; +import org.netbeans.jemmy.ClassReference; +import org.netbeans.jemmy.operators.JFrameOperator; +import org.netbeans.jemmy.operators.JTreeOperator; +import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail; + +/* + * @test + * @key headful + * @summary Verifies SwingSet3 TreeDemo by expanding all collapsed nodes in the + * tree and then collapsing all the expanded nodes in the tree. It + * verifies the number of nodes expanded, number of nodes collapsed and + * number of rows in the tree in the begininng, after expanding and + * after collapsing the nodes. It also checks that the tree grows + * vertically (as ScrollPane allows it). + * + * @library /sanity/client/lib/jemmy/src + * @library /sanity/client/lib/Jemmy2Ext/src + * @library /sanity/client/lib/SwingSet3/src + * @build org.jemmy2ext.JemmyExt + * @build com.sun.swingset3.demos.tree.TreeDemo + * @run testng TreeDemoTest + */ +public class TreeDemoTest { + + @Test + public void test() throws Exception { + captureDebugInfoOnFail(() -> { + new ClassReference(TreeDemo.class.getCanonicalName()).startApplication(); + + JFrameOperator frame = new JFrameOperator(DEMO_TITLE); + + JTreeOperator tree = new JTreeOperator(frame); + + assertEquals("Initial number of rows in the tree", 4, tree.getRowCount()); + + int initialTreeHeight = tree.getHeight(); + + // expand all nodes + int expandsCount = 0; + for (int i = 0; i < tree.getRowCount(); i++) { + TreePath tp = tree.getPathForRow(i); + if (tree.getChildCount(tp) > 0 && !tree.isExpanded(tp)) { + tree.expandRow(i); + expandsCount++; + } + } + + assertEquals("Number of rows expanded", 75, expandsCount); + assertEquals("Number of rows in the tree after expanding all of them", + 616, tree.getRowCount()); + + int expandedTreeHeight = tree.getHeight(); + assertTrue("Expanded tree height has increased, current " + + expandedTreeHeight + " > initial " + initialTreeHeight, + expandedTreeHeight > initialTreeHeight); + + // collapse all nodes + int collapsesCount = 0; + for (int i = tree.getRowCount() - 1; i >= 0; i--) { + TreePath tp = tree.getPathForRow(i); + if (tree.getChildCount(tp) > 0 && tree.isExpanded(tp)) { + tree.collapseRow(i); + collapsesCount++; + } + } + + assertEquals("Number of rows collapsed", 76, collapsesCount); + assertEquals("Number of rows in the tree after collapsing all of them", + 1, tree.getRowCount()); + + int collapsedTreeHeight = tree.getHeight(); + assertTrue("Collpased tree height is not longer than initial, " + + "current " + collapsedTreeHeight + " <= initial " + + initialTreeHeight, + collapsedTreeHeight <= initialTreeHeight); + + }); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/SwingSet/src/WindowDemoTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/SwingSet/src/WindowDemoTest.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.swingset3.demos.window.WindowDemo; +import static com.sun.swingset3.demos.window.WindowDemo.*; +import static org.jemmy2ext.JemmyExt.*; +import static org.testng.AssertJUnit.*; +import org.testng.annotations.Test; +import org.netbeans.jemmy.ClassReference; +import org.netbeans.jemmy.operators.JButtonOperator; +import org.netbeans.jemmy.operators.JFrameOperator; +import org.netbeans.jemmy.operators.JLabelOperator; +import org.netbeans.jemmy.operators.WindowOperator; + +/* + * @test + * @key headful + * @summary Verifies SwingSet3 WindowDemo by checking that separate JWindow is + * shown, it contains predefined label and no new windows are opened + * when the "Show JWindow..." button is clicked. + * + * @library /sanity/client/lib/jemmy/src + * @library /sanity/client/lib/Jemmy2Ext/src + * @library /sanity/client/lib/SwingSet3/src + * @build org.jemmy2ext.JemmyExt + * @build com.sun.swingset3.demos.window.WindowDemo + * @run testng WindowDemoTest + */ +public class WindowDemoTest { + + @Test + public void test() throws Exception { + captureDebugInfoOnFail(() -> { + new ClassReference(WindowDemo.class.getCanonicalName()).startApplication(); + + JFrameOperator frame = new JFrameOperator(); + + assertEquals("Only one JWindow is shown", 1, getJWindowCount()); + + WindowOperator window = new WindowOperator(getJWindow()); + + assertTrue("JFrame is showing", frame.isShowing()); + assertFalse("JFrame is not iconified", isIconified(frame)); + assertTrue("JWindow is showing", window.isShowing()); + + final String labelText = I_HAVE_NO_SYSTEM_BORDER; + JLabelOperator jLabelOperator = new JLabelOperator(window, labelText); + assertEquals("JWindow contains the label with corresponding text", labelText, jLabelOperator.getText()); + + new JButtonOperator(frame, SHOW_J_WINDOW).push(); + + assertEquals("Only one JWindow is shown", 1, getJWindowCount()); + }); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/TEST.ROOT.template --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/TEST.ROOT.template Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,24 @@ +# This file identifies the root of the test-suite hierarchy. +# It also contains test-suite configuration information. + +# The list of keywords supported in the entire test suite. The +# "intermittent" keyword marks tests known to fail intermittently. +# The "randomness" keyword marks tests using randomness with test +# cases differing from run to run. (A test using a fixed random seed +# would not count as "randomness" by this definition.) Extra care +# should be taken to handle test failures of intermittent or +# randomness tests. +# +# A "headful" test requires a graphical environment to meaningfully +# run. Tests that are not headful are "headless." + +keys=screenshots + +# Tests that must run in othervm mode +othervm.dirs=sanity/client/SwingSet + +# Tests that cannot run concurrently +exclusiveAccess.dirs=sanity/client/SwingSet + +# Tests using jtreg 4.1 b13 features +requiredVersion=4.1 b13 diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/TEST.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/TEST.properties Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,14 @@ +# This file contains test-suite configuration information related to this portion +# of the test suite. +# +# A "screenshots" test requires a 100% headful graphical environment +# as they rely on Robot to take screenshots and move mouse. + +# The list of keywords supported in this part of the test suite +keys=screenshots + +# Tests that cannot run concurrently +exclusiveAccess.dirs=SwingSet + +# Tests require jtreg 4.1 b13 features +#requiredVersion=4.1 b13 diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/Jemmy2Ext/src/org/jemmy2ext/JemmyExt.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/Jemmy2Ext/src/org/jemmy2ext/JemmyExt.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,614 @@ +/* + * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.jemmy2ext; + +import java.awt.Component; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.Window; +import java.awt.image.BufferedImage; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.IntStream; +import javax.imageio.ImageIO; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JPanel; +import javax.swing.JWindow; +import javax.swing.border.Border; +import javax.swing.border.CompoundBorder; +import javax.swing.border.TitledBorder; +import org.netbeans.jemmy.ComponentChooser; +import org.netbeans.jemmy.DefaultCharBindingMap; +import org.netbeans.jemmy.QueueTool; +import org.netbeans.jemmy.TimeoutExpiredException; +import org.netbeans.jemmy.Waitable; +import org.netbeans.jemmy.Waiter; +import org.netbeans.jemmy.drivers.scrolling.JSpinnerDriver; +import org.netbeans.jemmy.image.StrictImageComparator; +import org.netbeans.jemmy.operators.ComponentOperator; +import org.netbeans.jemmy.operators.ContainerOperator; +import org.netbeans.jemmy.operators.FrameOperator; +import org.netbeans.jemmy.operators.JButtonOperator; +import org.netbeans.jemmy.operators.JFrameOperator; +import org.netbeans.jemmy.operators.JLabelOperator; +import org.netbeans.jemmy.operators.Operator; +import org.netbeans.jemmy.util.Dumper; +import org.netbeans.jemmy.util.PNGEncoder; +import static org.testng.AssertJUnit.*; + +/** + * This class solves two tasks: 1. It adds functionality that is missing in + * Jemmy 2. It references all the Jemmy API that is needed by tests so that they + * can just @build JemmyExt class and do not worry about Jemmy + * + * @author akouznet + */ +public class JemmyExt { + + /** + * Statically referencing all the classes that are needed by tests so that + * they're compiled by jtreg + */ + static final Class[] DEPENDENCIES = { + JSpinnerDriver.class, + DefaultCharBindingMap.class + }; + + public static void assertNotBlack(BufferedImage image) { + int w = image.getWidth(); + int h = image.getHeight(); + try { + assertFalse("All pixels are not black", IntStream.range(0, w).parallel().allMatch(x + -> IntStream.range(0, h).allMatch(y -> (image.getRGB(x, y) & 0xffffff) == 0) + )); + } catch (Throwable t) { + save(image, "allPixelsAreBlack.png"); + throw t; + } + } + + public static void waitArmed(JButtonOperator button) { + button.waitState(new ComponentChooser() { + + @Override + public boolean checkComponent(Component comp) { + return isArmed(button); + } + + @Override + public String getDescription() { + return "Button is armed"; + } + }); + } + + public static boolean isArmed(JButtonOperator button) { + return button.getQueueTool().invokeSmoothly(new QueueTool.QueueAction("getModel().isArmed()") { + + @Override + public Boolean launch() throws Exception { + return ((JButton) button.getSource()).getModel().isArmed(); + } + }); + } + + public static void waitPressed(JButtonOperator button) { + button.waitState(new ComponentChooser() { + + @Override + public boolean checkComponent(Component comp) { + return isPressed(button); + } + + @Override + public String getDescription() { + return "Button is pressed"; + } + }); + } + + public static boolean isPressed(JButtonOperator button) { + return button.getQueueTool().invokeSmoothly(new QueueTool.QueueAction("getModel().isPressed()") { + + @Override + public Boolean launch() throws Exception { + return ((JButton) button.getSource()).getModel().isPressed(); + } + }); + } + + public static void assertEquals(String string, StrictImageComparator comparator, BufferedImage expected, BufferedImage actual) { + try { + assertTrue(string, comparator.compare(expected, actual)); + } catch (Error err) { + save(expected, "expected.png"); + save(actual, "actual.png"); + throw err; + } + } + + public static void assertNotEquals(String string, StrictImageComparator comparator, BufferedImage notExpected, BufferedImage actual) { + try { + assertFalse(string, comparator.compare(notExpected, actual)); + } catch (Error err) { + save(notExpected, "notExpected.png"); + save(actual, "actual.png"); + throw err; + } + } + + public static void save(BufferedImage image, String filename) { + String filepath = filename; + try { + filepath = new File(filename).getCanonicalPath(); + System.out.println("Saving screenshot to " + filepath); + BufferedOutputStream file = new BufferedOutputStream(new FileOutputStream(filepath)); + new PNGEncoder(file, PNGEncoder.COLOR_MODE).encode(image); + } catch (IOException ioe) { + throw new RuntimeException("Failed to save image to " + filepath, ioe); + } + } + + public static void waitImageIsStill(Robot rob, ComponentOperator operator) { + operator.waitState(new ComponentChooser() { + + private BufferedImage previousImage = null; + private int index = 0; + private final StrictImageComparator sComparator = new StrictImageComparator(); + + @Override + public boolean checkComponent(Component comp) { + BufferedImage currentImage = capture(rob, operator); + save(currentImage, "waitImageIsStill" + index + ".png"); + index++; + boolean compareResult = previousImage == null ? false : sComparator.compare(currentImage, previousImage); + previousImage = currentImage; + return compareResult; + } + + @Override + public String getDescription() { + return "Image of " + operator + " is still"; + } + }); + } + + private static class ThrowableHolder { + + volatile Throwable t; + } + + public static void waitFor(String description, RunnableWithException r) throws Exception { + Waiter waiter = new Waiter<>(new Waitable() { + + @Override + public Boolean actionProduced(ThrowableHolder obj) { + try { + r.run(); + return true; + } catch (Throwable t) { + obj.t = t; + return null; + } + } + + @Override + public String getDescription() { + return description; + } + }); + ThrowableHolder th = new ThrowableHolder(); + try { + waiter.waitAction(th); + } catch (TimeoutExpiredException tee) { + Throwable t = th.t; + if (t != null) { + t.addSuppressed(tee); + if (t instanceof Exception) { + throw (Exception) t; + } else if (t instanceof Error) { + throw (Error) t; + } else if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } else { + throw new IllegalStateException("Unexpected exception type", t); + } + } + } + } + + public static BufferedImage capture(Robot rob, ComponentOperator operator) { + Rectangle boundary = new Rectangle(operator.getLocationOnScreen(), + operator.getSize()); + return rob.createScreenCapture(boundary); + } + + /** + * Wraps the test code so that in case of any failure as much information as + * possible is captured + * + * @param r test code Runnable + * @throws Exception whatever exception the test may throw + */ + public static void captureDebugInfoOnFail(RunnableWithException r) throws Exception { + // TODO: Remove this once https://bugs.openjdk.java.net/browse/JDK-8151671 is fixed + try { + r.run(); + System.out.println("TEST PASSED"); + } catch (Throwable t) { + captureAll(); + throw t; + } + } + + /** + * This is a helper class which allows to catch throwables thrown in other + * threads and throw them in the main test thread + */ + public static class MultiThreadedTryCatch { + + private final List throwables + = Collections.synchronizedList(new ArrayList<>()); + + /** + * Throws registered throwables. If the list of the registered + * throwables is not empty, it re-throws the first throwable in the list + * adding all others into its suppressed list. Can be used in any + * thread. + * + * @throws Exception + */ + public void throwRegistered() throws Exception { + Throwable root = null; + synchronized (throwables) { + if (!throwables.isEmpty()) { + root = throwables.remove(0); + while (!throwables.isEmpty()) { + root.addSuppressed(throwables.remove(0)); + } + } + } + if (root != null) { + if (root instanceof Error) { + throw (Error) root; + } else if (root instanceof Exception) { + throw (Exception) root; + } else { + throw new AssertionError("Unexpected exception type: " + root.getClass() + " (" + root + ")"); + } + } + } + + /** + * Registers a throwable and adds it to the list of throwables. Can be + * used in any thread. + * + * @param t + */ + public void register(Throwable t) { + t.printStackTrace(); + throwables.add(t); + } + + /** + * Registers a throwable and adds it as the first item of the list of + * catched throwables. + * + * @param t + */ + public void registerRoot(Throwable t) { + t.printStackTrace(); + throwables.add(0, t); + } + } + + /** + * Trying to capture as much information as possible. Currently it includes + * full dump and a screenshot of the whole screen. + */ + public static void captureAll() { + PNGEncoder.captureScreen("failure.png", PNGEncoder.COLOR_MODE); + try { + Dumper.dumpAll("dumpAll.xml"); + } catch (FileNotFoundException ex) { + Logger.getLogger(JemmyExt.class.getName()).log(Level.SEVERE, null, ex); + } + captureWindows(); + } + + /** + * Captures each showing window image using Window.paint() method. + */ + private static void captureWindows() { + try { + EventQueue.invokeAndWait(() -> { + Window[] windows = Window.getWindows(); + int index = 0; + for (Window w : windows) { + if (!w.isShowing()) { + continue; + } + BufferedImage img = new BufferedImage(w.getWidth(), w.getHeight(), BufferedImage.TYPE_INT_ARGB); + Graphics g = img.getGraphics(); + w.paint(g); + g.dispose(); + + try { + ImageIO.write(img, "png", new File("window" + index++ + ".png")); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); + } catch (InterruptedException | InvocationTargetException ex) { + Logger.getLogger(JemmyExt.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public static interface RunnableWithException { + + public void run() throws Exception; + } + + public static void waitIsFocused(JFrameOperator jfo) { + jfo.waitState(new ComponentChooser() { + + @Override + public boolean checkComponent(Component comp) { + return jfo.isFocused(); + } + + @Override + public String getDescription() { + return "JFrame is focused"; + } + }); + } + + public static int getJWindowCount() { + return new QueueTool().invokeAndWait(new QueueTool.QueueAction(null) { + + @Override + public Integer launch() throws Exception { + Window[] windows = Window.getWindows(); + int windowCount = 0; + for (Window w : windows) { + if (w.getClass().equals(JWindow.class)) { + windowCount++; + } + } + return windowCount; + } + }); + } + + public static JWindow getJWindow() { + return getJWindow(0); + } + + public static JWindow getJWindow(int index) { + return new QueueTool().invokeAndWait(new QueueTool.QueueAction(null) { + + @Override + public JWindow launch() throws Exception { + Window[] windows = Window.getWindows(); + int windowIndex = 0; + for (Window w : windows) { + if (w.getClass().equals(JWindow.class)) { + if (windowIndex == index) { + return (JWindow) w; + } + windowIndex++; + } + } + return null; + } + }); + } + + public static boolean isIconified(FrameOperator frameOperator) { + return frameOperator.getQueueTool().invokeAndWait(new QueueTool.QueueAction("Frame is iconified") { + + @Override + public Boolean launch() throws Exception { + return (((Frame) frameOperator.getSource()).getState() & Frame.ICONIFIED) != 0; + } + }); + } + + public static final Operator.DefaultStringComparator EXACT_STRING_COMPARATOR + = new Operator.DefaultStringComparator(true, true); + + /** + * Finds a label with the exact labelText and returns the operator for its + * parent container. + * + * @param container + * @param labelText + * @return + */ + public static ContainerOperator getLabeledContainerOperator(ContainerOperator container, String labelText) { + + container.setComparator(EXACT_STRING_COMPARATOR); + + JLabelOperator jLabelOperator = new JLabelOperator(container, labelText); + + assert labelText.equals(jLabelOperator.getText()); + + return new ContainerOperator<>(jLabelOperator.getParent()); + } + + /** + * Finds a JPanel with exact title text. + * + * @param container + * @param titleText + * @return + */ + public static ContainerOperator getBorderTitledJPanelOperator(ContainerOperator container, String titleText) { + return new ContainerOperator<>(container, new JPanelByBorderTitleFinder(titleText, EXACT_STRING_COMPARATOR)); + } + + public static final QueueTool QUEUE_TOOL = new QueueTool(); + + /** + * Allows to find JPanel by the title text in its border. + */ + public static class JPanelByBorderTitleFinder implements ComponentChooser { + + String titleText; + Operator.StringComparator comparator; + + /** + * @param titleText title text pattern + * @param comparator specifies string comparison algorithm. + */ + public JPanelByBorderTitleFinder(String titleText, Operator.StringComparator comparator) { + this.titleText = titleText; + this.comparator = comparator; + } + + /** + * @param titleText title text pattern + */ + public JPanelByBorderTitleFinder(String titleText) { + this(titleText, Operator.getDefaultStringComparator()); + } + + @Override + public boolean checkComponent(Component comp) { + assert EventQueue.isDispatchThread(); + if (comp instanceof JPanel) { + return checkBorder(((JPanel) comp).getBorder()); + } + return false; + } + + public boolean checkBorder(Border border) { + if (border instanceof TitledBorder) { + String title = ((TitledBorder) border).getTitle(); + return comparator.equals(title, titleText); + } else if (border instanceof CompoundBorder) { + CompoundBorder compoundBorder = (CompoundBorder) border; + return checkBorder(compoundBorder.getInsideBorder()) || checkBorder(compoundBorder.getOutsideBorder()); + } else { + return false; + } + } + + @Override + public String getDescription() { + return ("JPanel with border title text \"" + titleText + "\" with comparator " + comparator); + } + } + + public static class ByClassSimpleNameChooser implements ComponentChooser { + + private final String className; + + public ByClassSimpleNameChooser(String className) { + this.className = className; + } + + @Override + public boolean checkComponent(Component comp) { + return comp.getClass().getSimpleName().equals(className); + } + + @Override + public String getDescription() { + return "Component with the simple class name of " + className; + } + + } + + public static class ByClassChooser implements ComponentChooser { + + private final Class clazz; + + public ByClassChooser(Class clazz) { + this.clazz = clazz; + } + + @Override + public boolean checkComponent(Component comp) { + return comp.getClass().equals(clazz); + } + + @Override + public String getDescription() { + return "Component with the class of " + clazz; + } + + } + + public static class ByToolTipChooser implements ComponentChooser { + + private final String tooltip; + + public ByToolTipChooser(String tooltip) { + if (tooltip == null) { + throw new NullPointerException("Tooltip cannot be null"); + } + this.tooltip = tooltip; + } + + @Override + public boolean checkComponent(Component comp) { + return (comp instanceof JComponent) + ? tooltip.equals(((JComponent) comp).getToolTipText()) + : false; + } + + @Override + public String getDescription() { + return "JComponent with the tooltip '" + tooltip + "'"; + } + + } + + @SuppressWarnings(value = "unchecked") + public static R getUIValue(O operator, Function getter) { + return operator.getQueueTool().invokeSmoothly(new QueueTool.QueueAction("getting UI value through the queue using " + getter) { + + @Override + public R launch() throws Exception { + return getter.apply((S) operator.getSource()); + } + }); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/README --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/README Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,4 @@ +This content of this src folder was originally taken from SwingSet3 demo project: https://java.net/projects/swingset3/. +Then it was modified to increase testability and remove extra content and extra dependencies. + +Do NOT modify files in it. \ No newline at end of file diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/DemoProperties.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/DemoProperties.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Annotation type for specifying meta-data about Demo + * + * @author aim + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface DemoProperties { + + String value(); // Name + + String category(); + + String description(); + + String iconFile() default ""; + + String[] sourceFiles() default ""; +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/DemoUtilities.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/DemoUtilities.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos; + +import java.awt.*; +import java.net.URI; +import java.io.IOException; +import javax.swing.*; + +/** + * @author Pavel Porvatov + */ +public class DemoUtilities { + + private DemoUtilities() { + // Hide constructor + } + + public static void setToplevelLocation(Window toplevel, Component component, + int relativePosition) { + + Rectangle compBounds = component.getBounds(); + + // Convert component location to screen coordinates + Point p = new Point(); + SwingUtilities.convertPointToScreen(p, component); + + int x; + int y; + + // Set frame location to be centered on panel + switch (relativePosition) { + case SwingConstants.NORTH: { + x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2); + y = p.y - toplevel.getHeight(); + break; + } + case SwingConstants.EAST: { + x = p.x + compBounds.width; + y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2); + break; + } + case SwingConstants.SOUTH: { + x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2); + y = p.y + compBounds.height; + break; + } + case SwingConstants.WEST: { + x = p.x - toplevel.getWidth(); + y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2); + break; + } + case SwingConstants.NORTH_EAST: { + x = p.x + compBounds.width; + y = p.y - toplevel.getHeight(); + break; + } + case SwingConstants.NORTH_WEST: { + x = p.x - toplevel.getWidth(); + y = p.y - toplevel.getHeight(); + break; + } + case SwingConstants.SOUTH_EAST: { + x = p.x + compBounds.width; + y = p.y + compBounds.height; + break; + } + case SwingConstants.SOUTH_WEST: { + x = p.x - toplevel.getWidth(); + y = p.y + compBounds.height; + break; + } + default: + case SwingConstants.CENTER: { + x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2); + y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2); + } + } + toplevel.setLocation(x, y); + } + + public static boolean browse(URI uri) throws IOException { + // Try using the Desktop api first + try { + Desktop desktop = Desktop.getDesktop(); + desktop.browse(uri); + + return true; + } catch (SecurityException e) { + e.printStackTrace(); + } + + return false; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/JGridPanel.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/JGridPanel.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos; + +import java.awt.*; +import javax.swing.*; + +/** + * JGridPanel + * + * @author Pavel Porvatov + */ +public class JGridPanel extends JPanel { + + public static final int DEFAULT_GAP = 5; + + public enum Layout { + FIRST, + CENTER, + LAST, + FILL + } + + private enum ComponentType { + NO_RESIZABLE, + HORIZONTAL_FILL, + FULL + } + + private final int cols; + + private int bigCol = -1; + + private int bigRow = -1; + + private int vGap = -1; + + private int hGap = -1; + + public JGridPanel(int cols) { + this(cols, -1, -1); + } + + public JGridPanel(int cols, int bigCol) { + this(cols, bigCol, -1); + } + + public JGridPanel(int cols, int bigCol, int bigRow) { + super(new GridBagLayout()); + + assert cols > 0; + assert bigCol >= -1 && bigCol < cols; + assert bigRow >= -1; + + this.cols = cols; + this.bigCol = bigCol; + this.bigRow = bigRow; + } + + public void setVGap(int vGap) { + this.vGap = vGap; + } + + public void setHGap(int hGap) { + this.hGap = hGap; + } + + public JGridPanel cell() { + return cell(null, getHLayout(null), getVLayout(null), null); + } + + public JGridPanel cell(Component component) { + return cell(component, getHLayout(component), getVLayout(component), null); + } + + public JGridPanel cell(Component component, Layout hLayout) { + return cell(component, hLayout, getVLayout(component), null); + } + + public JGridPanel cell(Component component, Layout hLayout, Layout vLayout) { + return cell(component, hLayout, vLayout, null); + } + + public JGridPanel cell(Component component, Insets insets) { + assert insets != null; + + return cell(component, getHLayout(component), getVLayout(component), insets); + } + + private JGridPanel cell(Component component, Layout hLayout, Layout vLayout, Insets insets) { + int componentCount = getComponentCount(); + int x = componentCount % cols; + int y = componentCount / cols; + + int weightx = x == bigCol || (bigCol < 0 && hLayout == Layout.FILL) ? 1 : 0; + int weighty = y == bigRow || (bigRow < 0 && vLayout == Layout.FILL) ? 1 : 0; + + if (insets == null) { + int topGap = y == 0 ? 0 : vGap; + int leftGap = x == 0 ? 0 : hGap; + + insets = new Insets(topGap < 0 ? DEFAULT_GAP : topGap, + leftGap < 0 ? DEFAULT_GAP : leftGap, 0, 0); + } + + add(component == null ? createSeparator() : component, + new GridBagConstraints(x, y, + 1, 1, + weightx, weighty, + getAnchor(hLayout, vLayout), getFill(hLayout, vLayout), + insets, 0, 0)); + + return this; + } + + public void setComponent(Component component, int col, int row) { + assert col >= 0 && col < cols; + assert row >= 0; + + GridBagLayout layout = (GridBagLayout) getLayout(); + + for (int i = 0; i < getComponentCount(); i++) { + Component oldComponent = getComponent(i); + + GridBagConstraints constraints = layout.getConstraints(oldComponent); + + if (constraints.gridx == col && constraints.gridy == row) { + remove(i); + + add(component == null ? createSeparator() : component, constraints); + + validate(); + repaint(); + + return; + } + } + + // Cell not found + assert false; + } + + private static JComponent createSeparator() { + return new JLabel(); + } + + private static int getFill(Layout hLayout, Layout vLayout) { + if (hLayout == Layout.FILL) { + return vLayout == Layout.FILL ? GridBagConstraints.BOTH : GridBagConstraints.HORIZONTAL; + } + + return vLayout == Layout.FILL ? GridBagConstraints.VERTICAL : GridBagConstraints.NONE; + } + + private static ComponentType getComponentType(Component component) { + if (component == null + || component instanceof JLabel + || component instanceof JRadioButton + || component instanceof JCheckBox + || component instanceof JButton) { + return ComponentType.NO_RESIZABLE; + } + + if (component instanceof JComboBox + || component instanceof JTextField) { + return ComponentType.HORIZONTAL_FILL; + } + + return ComponentType.FULL; + } + + private static Layout getHLayout(Component component) { + if (getComponentType(component) == ComponentType.NO_RESIZABLE) { + return Layout.FIRST; + } else { + return Layout.FILL; + } + } + + private static Layout getVLayout(Component component) { + if (getComponentType(component) == ComponentType.FULL) { + return Layout.FILL; + } else { + return Layout.CENTER; + } + } + + private static final int[][] ANCHORS = new int[][]{ + {GridBagConstraints.NORTHWEST, GridBagConstraints.NORTH, GridBagConstraints.NORTHEAST}, + {GridBagConstraints.WEST, GridBagConstraints.CENTER, GridBagConstraints.EAST}, + {GridBagConstraints.SOUTHWEST, GridBagConstraints.SOUTH, GridBagConstraints.SOUTHEAST} + }; + + private static int getAnchorIndex(Layout layout) { + if (layout == Layout.CENTER) { + return 1; + } else if (layout == Layout.LAST) { + return 2; + } else { + return 0; + } + } + + private static int getAnchor(Layout hLayout, Layout vLayout) { + return ANCHORS[getAnchorIndex(vLayout)][getAnchorIndex(hLayout)]; + } + + public void setBorderEqual(int border) { + setBorder(BorderFactory.createEmptyBorder(border, border, border, border)); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/JHyperlink.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/JHyperlink.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,237 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos; + +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Graphics; +import java.awt.Insets; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.net.URI; +import java.net.URISyntaxException; +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.ButtonModel; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +/** + * + * @author aim + */ +//Create HTML hyperlink +//Create HTML image hyperlink +public class JHyperlink extends JButton { + + private static final BrowseAction defaultBrowseAction = new BrowseAction(); + + private URI targetURI; + private boolean visited; + + private final transient Rectangle viewRect = new Rectangle(); + private final transient Rectangle iconRect = new Rectangle(); + private final transient Rectangle textRect = new Rectangle(); + + //remind(aim): lookup colors instead of hardcoding them + private Color normalForeground; + private Color activeForeground; + private Color visitedForeground; + private boolean drawUnderline = true; + + static { + UIManager.put("Hyperlink.foreground", Color.blue); + UIManager.put("Hyperlink.activeForeground", Color.red); + UIManager.put("Hyperlink.visitedForeground", new Color(85, 145, 90)); + } + + /** + * Creates a new instance of JHyperlink + */ + public JHyperlink() { + super(); + normalForeground = UIManager.getColor("Hyperlink.foreground"); + activeForeground = UIManager.getColor("Hyperlink.activeForeground"); + visitedForeground = UIManager.getColor("Hyperlink.visitedForeground"); + setBorderPainted(false); + setContentAreaFilled(false); + setForeground(normalForeground); + setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + setMargin(new Insets(0, 0, 0, 0)); + setAction(defaultBrowseAction); + } + + /** + * Creates a new instance of JHyperlink + */ + public JHyperlink(String text) { + this(); + setText(text); // override the inheritence of the action's name + } + + public JHyperlink(String text, String targetURI) throws URISyntaxException { + this(text, new URI(targetURI)); + } + + public JHyperlink(String text, URI target) { + this(text); + setTarget(target); + } + + public JHyperlink(String text, Action action) { + this(text); + setAction(action); // replaces default browse action + setText(text); // override the inheritence of the action's name + } + + public JHyperlink(String text, Icon icon) { + this(text); + setIcon(icon); + } + + public JHyperlink(Icon icon, String targetURI) throws URISyntaxException { + this(null, icon, targetURI); + } + + public JHyperlink(String text, Icon icon, String targetURI) throws URISyntaxException { + this(text, new URI(targetURI)); + setIcon(icon); + } + + public JHyperlink(String text, Icon icon, URI target) { + this(text); + setIcon(icon); + setTarget(target); + } + + public void setTarget(URI target) { + this.targetURI = target; + setToolTipText(target.toASCIIString()); + } + + public URI getTarget() { + return targetURI; + } + + public void setVisited(boolean visited) { + this.visited = visited; + } + + public boolean isVisited() { + return visited; + } + + @Override + public void setForeground(Color foreground) { + normalForeground = foreground; + super.setForeground(foreground); + } + + public void setVisitedForeground(Color visited) { + visitedForeground = visited; + } + + public void setDrawUnderline(boolean drawUnderline) { + this.drawUnderline = drawUnderline; + } + + public boolean getDrawUnderline() { + return drawUnderline; + } + + @Override + protected void paintComponent(Graphics g) { + // Set the foreground on the fly to ensure the text is painted + // with the proper color in super.paintComponent + ButtonModel model = getModel(); + if (model.isArmed()) { + super.setForeground(activeForeground); + } else if (visited) { + super.setForeground(visitedForeground); + } else { + super.setForeground(normalForeground); + } + super.paintComponent(g); + + if (drawUnderline) { + Insets insets = getInsets(); + viewRect.x = insets.left; + viewRect.y = insets.top; + viewRect.width = getWidth() - insets.left - insets.right; + viewRect.height = getHeight() - insets.top - insets.bottom; + int baseline = getBaseline(viewRect.width, viewRect.height); + + iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0; + textRect.x = textRect.y = textRect.width = textRect.height = 0; + SwingUtilities.layoutCompoundLabel(g.getFontMetrics(), getText(), + getIcon(), getVerticalAlignment(), getHorizontalAlignment(), + getVerticalTextPosition(), getHorizontalTextPosition(), + viewRect, iconRect, textRect, getIconTextGap()); + + // getBaseline not returning correct results, so workaround for now + if (UIManager.getLookAndFeel().getName().equals("Nimbus")) { + baseline += 7; + } else { + baseline += 3; + } + + g.setColor(getForeground()); + g.drawLine(textRect.x, + baseline, + textRect.x + textRect.width, + baseline); + } + + } + + // This action is stateless and hence can be shared across hyperlinks + private static class BrowseAction extends AbstractAction { + + public BrowseAction() { + super(); + } + + @Override + public void actionPerformed(ActionEvent e) { + JHyperlink hyperlink = (JHyperlink) e.getSource(); + + URI targetURI = hyperlink.getTarget(); + if (targetURI != null) { + try { + DemoUtilities.browse(targetURI); + hyperlink.setVisited(true); + } catch (Exception ex) { + ex.printStackTrace(); + System.err.println(ex); + } + + } + } + + } +// +// + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/ResourceManager.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/ResourceManager.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos; + +import java.net.URL; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.*; + +/** + * @author Pavel Porvatov + */ +public class ResourceManager { + + private static final Logger logger = Logger.getLogger(ResourceManager.class.getName()); + + private final Class demoClass; + + // Resource bundle for internationalized and accessible text + private ResourceBundle bundle = null; + + public ResourceManager(Class demoClass) { + this.demoClass = demoClass; + + String bundleName = demoClass.getPackage().getName() + ".resources." + demoClass.getSimpleName(); + + try { + bundle = ResourceBundle.getBundle(bundleName); + } catch (MissingResourceException e) { + logger.log(Level.SEVERE, "Couldn't load bundle: " + bundleName); + } + } + + public String getString(String key) { + return bundle != null ? bundle.getString(key) : key; + } + + public char getMnemonic(String key) { + return (getString(key)).charAt(0); + } + + public ImageIcon createImageIcon(String filename, String description) { + String path = "resources/images/" + filename; + + URL imageURL = demoClass.getResource(path); + + if (imageURL == null) { + logger.log(Level.SEVERE, "unable to access image file: " + path); + + return null; + } else { + return new ImageIcon(imageURL, description); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/ButtonDemo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/ButtonDemo.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.button; + +import java.awt.Color; +import java.awt.FlowLayout; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.net.URISyntaxException; +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +import com.sun.swingset3.DemoProperties; +import com.sun.swingset3.demos.JHyperlink; + +/** + * + * @author aim + */ +@DemoProperties( + value = "JButton Demo", + category = "Controls", + description = "Demonstrates the many uses of JButton, Swing's push button component.", + sourceFiles = { + "com/sun/swingset3/demos/button/ButtonDemo.java", + "com/sun/swingset3/demos/JHyperlink.java", + "com/sun/swingset3/demos/button/resources/ButtonDemo.html", + "com/sun/swingset3/demos/button/resources/images/blogs.png", + "com/sun/swingset3/demos/button/resources/images/ButtonDemo.gif", + "com/sun/swingset3/demos/button/resources/images/document-print.png", + "com/sun/swingset3/demos/button/resources/images/earth_day.gif", + "com/sun/swingset3/demos/button/resources/images/earth_night.gif", + "com/sun/swingset3/demos/button/resources/images/edit-find.png", + "com/sun/swingset3/demos/button/resources/images/redbutton.png", + "com/sun/swingset3/demos/button/resources/images/redbutton_dark.png", + "com/sun/swingset3/demos/button/resources/images/redbutton_glow.png" + } +) +public final class ButtonDemo extends JPanel { + + public static final String DEMO_TITLE = ButtonDemo.class.getAnnotation(DemoProperties.class).value(); + public static final String DO_IT_AGAIN = "Do it again"; + public static final String DO_IT = "Do it"; + public static final String BUTTON_WITH_TEXT_AND_IMAGE = "button with text and image"; + public static final String BUTTON_WITH_BACKGROUND_COLOR = "button with background color"; + public static final String GO = "Go"; + public static final String FIND = "Find"; + public static final String IMAGE_BUTTON = "image button"; + public static final String SIMPLE_BUTTON = "simple button"; + public static final String GET_MORE_INFO = "Get More Info"; + public static final String JAVA_BLOGS_URL = "https://blogs.oracle.com/java/"; + public static final String JAVA_SE_URL = "http://www.oracle.com/technetwork/java/javase/overview/index.html"; + public static final String BUTTON_WITH_ROLLOVER_IMAGE = "button with rollover image"; + public static final String BUTTON_WITH_NO_BORDER = "button with no border"; + public static final String CONNECT = "Connect"; + + public ButtonDemo() { + setToolTipText("Demonstrates JButton, Swing's push button component."); + initComponents(); + setOpaque(false); + } + + protected void initComponents() { + setLayout(new GridLayout(0, 1)); + + add(createSimpleButtonPanel()); + add(createCreativeButtonPanel()); + } + + protected JPanel createSimpleButtonPanel() { + JPanel panel = new JPanel(); + panel.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 8)); + panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), + "Simple Buttons")); + + //Create simple button + final JButton simpleButton = new JButton(DO_IT); + simpleButton.setToolTipText(SIMPLE_BUTTON); + // + //Add action listener using anonymous inner class + // This style is useful when the action code is tied to a + // single button instance and it's useful for simplicity + // sake to keep the action code located near the button. + // More global application actions should be implemented + // using Action classes instead. + simpleButton.addActionListener((ActionEvent event) -> { + simpleButton.setText(DO_IT_AGAIN); + // Need to force toplevel to relayout to accommodate new button size + SwingUtilities.getWindowAncestor(simpleButton).validate(); + }); + // + simpleButton.putClientProperty("snippetKey", "Create simple button"); + panel.add(simpleButton); + + //Create image button + // Image is from the Java Look and Feel Graphics Repository + JButton button = new JButton(new ImageIcon(getClass(). + getResource("resources/images/document-print.png"))); + button.setToolTipText(IMAGE_BUTTON); + // + button.putClientProperty("snippetKey", "Create image button"); + panel.add(button); + + //Create button with text and image + // Image is from the Java Look and Feel Graphics Repository + button = new JButton(FIND, + new ImageIcon(getClass(). + getResource("resources/images/edit-find.png"))); + button.setToolTipText(BUTTON_WITH_TEXT_AND_IMAGE); + button.setHorizontalTextPosition(JButton.LEADING); + button.setIconTextGap(6); + // + button.putClientProperty("snippetKey", "Create button with text and image"); + panel.add(button); + + //Create button with background color + button = new JButton(GO); + button.setBackground(Color.green); + button.setContentAreaFilled(true); + button.setOpaque(false); + button.setToolTipText(BUTTON_WITH_BACKGROUND_COLOR); + // + button.putClientProperty("snippetKey", "Create button with background color"); + panel.add(button); + + return panel; + } + + protected JPanel createCreativeButtonPanel() { + JPanel panel = new JPanel(); + panel.setLayout(new FlowLayout(FlowLayout.CENTER, 16, 8)); + panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), + "More Interesting Buttons")); + + //Create button with no border + JButton button = new JButton(); + button.setText(CONNECT); + button.setIcon(new ImageIcon(getClass().getResource("resources/images/earth_day.gif"))); + button.setPressedIcon(new ImageIcon(getClass().getResource("resources/images/earth_night.gif"))); + button.setBorderPainted(false); + button.setContentAreaFilled(false); + button.setVerticalTextPosition(JButton.BOTTOM); + button.setHorizontalTextPosition(JButton.CENTER); + button.setIconTextGap(0); + button.setToolTipText(BUTTON_WITH_NO_BORDER); + // + button.putClientProperty("snippetKey", "Create button with no border"); + panel.add(button); + + //Create image button with rollover image + button = new JButton(); + button.setBorderPainted(false); + button.setContentAreaFilled(false); + button.setIcon(new ImageIcon(getClass().getResource("resources/images/redbutton.png"))); + button.setRolloverEnabled(true); + button.setRolloverIcon(new ImageIcon(getClass().getResource("resources/images/redbutton_glow.png"))); + button.setPressedIcon(new ImageIcon(getClass().getResource("resources/images/redbutton_dark.png"))); + button.setToolTipText(BUTTON_WITH_ROLLOVER_IMAGE); + // + button.putClientProperty("snippetKey", "Create image button with rollover image"); + panel.add(button); + + //Create HTML hyperlink + JHyperlink hyperlink; + try { + hyperlink = new JHyperlink(GET_MORE_INFO, JAVA_SE_URL); + } catch (URISyntaxException use) { + use.printStackTrace(); + hyperlink = new JHyperlink(GET_MORE_INFO); + } + // + hyperlink.putClientProperty("snippetKey", "Create HTML hyperlink"); + panel.add(hyperlink); + + //Create HTML image hyperlink + try { + hyperlink = new JHyperlink( + new ImageIcon(getClass().getResource("resources/images/blogs.png")), JAVA_BLOGS_URL); + } catch (URISyntaxException use) { + use.printStackTrace(); + } + // + button.putClientProperty("snippetKey", "Create HTML image hyperlink"); + panel.add(hyperlink); + + return panel; + } + + public static void main(String args[]) { + final ButtonDemo buttonDemo = new ButtonDemo(); + + javax.swing.SwingUtilities.invokeLater(() -> { + JFrame frame = new JFrame(DEMO_TITLE); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.add(buttonDemo); + frame.pack(); + frame.setVisible(true); + }); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/ButtonDemo.html --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/ButtonDemo.html Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,36 @@ + + + + + + + +

Today's modern GUIs often use buttons which don't look like the traditional "push" button. Swing's button component, javax.swing.JButton, + can be used to create both ordinary and more creative button visuals. In the end, they all perform an action when clicked. +

+

+ To highlight the source code used to create a particular button, popup the context menu over that button. +

+ + diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/ButtonDemo.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/ButtonDemo.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/blogs.png Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/blogs.png has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/document-print.png Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/document-print.png has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/earth_day.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/earth_day.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/earth_night.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/earth_night.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/edit-find.png Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/edit-find.png has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/redbutton.png Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/redbutton.png has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/redbutton_dark.png Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/redbutton_dark.png has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/redbutton_glow.png Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/button/resources/images/redbutton_glow.png has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/ComboBoxDemo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/ComboBoxDemo.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,445 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.combobox; + +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.HashMap; +import java.util.Map; +import javax.accessibility.AccessibleRelation; +import javax.swing.*; +import javax.swing.border.BevelBorder; + +import com.sun.swingset3.demos.ResourceManager; +import com.sun.swingset3.DemoProperties; + +/** + * JComboBox Demo + * + * @author Jeff Dinkins + * @version 1.13 11/17/05 + */ +@DemoProperties( + value = "JComboBox Demo", + category = "Controls", + description = "Demonstrates JComboBox, a control which allows the user to make a selection from a popup list", + sourceFiles = { + "com/sun/swingset3/demos/combobox/ComboBoxDemo.java", + "com/sun/swingset3/demos/ResourceManager.java", + "com/sun/swingset3/demos/combobox/resources/ComboBoxDemo.properties", + "com/sun/swingset3/demos/combobox/resources/images/brenteyes.jpg", + "com/sun/swingset3/demos/combobox/resources/images/brenthair.jpg", + "com/sun/swingset3/demos/combobox/resources/images/brentmouth.jpg", + "com/sun/swingset3/demos/combobox/resources/images/ComboBoxDemo.gif", + "com/sun/swingset3/demos/combobox/resources/images/georgeseyes.jpg", + "com/sun/swingset3/demos/combobox/resources/images/georgeshair.jpg", + "com/sun/swingset3/demos/combobox/resources/images/georgesmouth.jpg", + "com/sun/swingset3/demos/combobox/resources/images/hanseyes.jpg", + "com/sun/swingset3/demos/combobox/resources/images/hanshair.jpg", + "com/sun/swingset3/demos/combobox/resources/images/hansmouth.jpg", + "com/sun/swingset3/demos/combobox/resources/images/howardeyes.jpg", + "com/sun/swingset3/demos/combobox/resources/images/howardhair.jpg", + "com/sun/swingset3/demos/combobox/resources/images/howardmouth.jpg", + "com/sun/swingset3/demos/combobox/resources/images/jameseyes.jpg", + "com/sun/swingset3/demos/combobox/resources/images/jameshair.jpg", + "com/sun/swingset3/demos/combobox/resources/images/jamesmouth.jpg", + "com/sun/swingset3/demos/combobox/resources/images/jeffeyes.jpg", + "com/sun/swingset3/demos/combobox/resources/images/jeffhair.jpg", + "com/sun/swingset3/demos/combobox/resources/images/jeffmouth.jpg", + "com/sun/swingset3/demos/combobox/resources/images/joneyes.jpg", + "com/sun/swingset3/demos/combobox/resources/images/jonhair.jpg", + "com/sun/swingset3/demos/combobox/resources/images/jonmouth.jpg", + "com/sun/swingset3/demos/combobox/resources/images/laraeyes.jpg", + "com/sun/swingset3/demos/combobox/resources/images/larahair.jpg", + "com/sun/swingset3/demos/combobox/resources/images/laramouth.jpg", + "com/sun/swingset3/demos/combobox/resources/images/larryeyes.jpg", + "com/sun/swingset3/demos/combobox/resources/images/larryhair.jpg", + "com/sun/swingset3/demos/combobox/resources/images/larrymouth.jpg", + "com/sun/swingset3/demos/combobox/resources/images/lisaeyes.jpg", + "com/sun/swingset3/demos/combobox/resources/images/lisahair.jpg", + "com/sun/swingset3/demos/combobox/resources/images/lisamouth.jpg", + "com/sun/swingset3/demos/combobox/resources/images/michaeleyes.jpg", + "com/sun/swingset3/demos/combobox/resources/images/michaelhair.jpg", + "com/sun/swingset3/demos/combobox/resources/images/michaelmouth.jpg", + "com/sun/swingset3/demos/combobox/resources/images/philipeyes.jpg", + "com/sun/swingset3/demos/combobox/resources/images/philiphair.jpg", + "com/sun/swingset3/demos/combobox/resources/images/philipmouth.jpg", + "com/sun/swingset3/demos/combobox/resources/images/scotteyes.jpg", + "com/sun/swingset3/demos/combobox/resources/images/scotthair.jpg", + "com/sun/swingset3/demos/combobox/resources/images/scottmouth.jpg" + } +) +public class ComboBoxDemo extends JPanel implements ActionListener { + + private static final Dimension VGAP15 = new Dimension(1, 15); + private static final Dimension HGAP20 = new Dimension(20, 1); + private static final Dimension VGAP20 = new Dimension(1, 20); + private static final Dimension HGAP30 = new Dimension(30, 1); + private static final Dimension VGAP30 = new Dimension(1, 30); + + private final ResourceManager resourceManager = new ResourceManager(this.getClass()); + public static final String DEMO_TITLE = ComboBoxDemo.class.getAnnotation(DemoProperties.class).value(); + + private Face face; + private JLabel faceLabel; + + private JComboBox hairCB; + private JComboBox eyesCB; + private JComboBox mouthCB; + + private JComboBox presetCB; + + private final Map parts = new HashMap<>(); + + /** + * main method allows us to run as a standalone demo. + * + * @param args + */ + public static void main(String[] args) { + JFrame frame = new JFrame(DEMO_TITLE); + + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(new ComboBoxDemo()); + frame.setPreferredSize(new Dimension(800, 600)); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + /** + * ComboBoxDemo Constructor + */ + public ComboBoxDemo() { + createComboBoxDemo(); + } + + private void createComboBoxDemo() { + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + + JPanel innerPanel = new JPanel(); + innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.X_AXIS)); + + add(Box.createRigidArea(VGAP20)); + add(innerPanel); + add(Box.createRigidArea(VGAP20)); + + innerPanel.add(Box.createRigidArea(HGAP20)); + + // Create a panel to hold buttons + JPanel comboBoxPanel = new JPanel() { + @Override + public Dimension getMaximumSize() { + return new Dimension(getPreferredSize().width, super.getMaximumSize().height); + } + }; + comboBoxPanel.setLayout(new BoxLayout(comboBoxPanel, BoxLayout.Y_AXIS)); + + comboBoxPanel.add(Box.createRigidArea(VGAP15)); + + JLabel l = (JLabel) comboBoxPanel.add(new JLabel(resourceManager.getString("ComboBoxDemo.presets"))); + l.setAlignmentX(JLabel.LEFT_ALIGNMENT); + comboBoxPanel.add(presetCB = createPresetComboBox()); + presetCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT); + l.setLabelFor(presetCB); + comboBoxPanel.add(Box.createRigidArea(VGAP30)); + + l = (JLabel) comboBoxPanel.add(new JLabel(resourceManager.getString("ComboBoxDemo.hair_description"))); + l.setAlignmentX(JLabel.LEFT_ALIGNMENT); + comboBoxPanel.add(hairCB = createHairComboBox()); + hairCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT); + l.setLabelFor(hairCB); + comboBoxPanel.add(Box.createRigidArea(VGAP15)); + + l = (JLabel) comboBoxPanel.add(new JLabel(resourceManager.getString("ComboBoxDemo.eyes_description"))); + l.setAlignmentX(JLabel.LEFT_ALIGNMENT); + comboBoxPanel.add(eyesCB = createEyesComboBox()); + eyesCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT); + l.setLabelFor(eyesCB); + comboBoxPanel.add(Box.createRigidArea(VGAP15)); + + l = (JLabel) comboBoxPanel.add(new JLabel(resourceManager.getString("ComboBoxDemo.mouth_description"))); + l.setAlignmentX(JLabel.LEFT_ALIGNMENT); + comboBoxPanel.add(mouthCB = createMouthComboBox()); + + mouthCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT); + l.setLabelFor(mouthCB); + comboBoxPanel.add(Box.createRigidArea(VGAP15)); + + // Fill up the remaining space + comboBoxPanel.add(new JPanel(new BorderLayout())); + + // Create and place the Face. + face = new Face(); + JPanel facePanel = new JPanel(); + facePanel.setLayout(new BorderLayout()); + facePanel.setBorder(new BevelBorder(BevelBorder.LOWERED)); + + faceLabel = new JLabel(face); + facePanel.add(faceLabel, BorderLayout.CENTER); + // Indicate that the face panel is controlled by the hair, eyes and + // mouth combo boxes. + Object[] controlledByObjects = new Object[3]; + controlledByObjects[0] = hairCB; + controlledByObjects[1] = eyesCB; + controlledByObjects[2] = mouthCB; + AccessibleRelation controlledByRelation + = new AccessibleRelation(AccessibleRelation.CONTROLLED_BY_PROPERTY, + controlledByObjects); + facePanel.getAccessibleContext().getAccessibleRelationSet().add(controlledByRelation); + + // Indicate that the hair, eyes and mouth combo boxes are controllers + // for the face panel. + AccessibleRelation controllerForRelation + = new AccessibleRelation(AccessibleRelation.CONTROLLER_FOR_PROPERTY, + facePanel); + hairCB.getAccessibleContext().getAccessibleRelationSet().add(controllerForRelation); + eyesCB.getAccessibleContext().getAccessibleRelationSet().add(controllerForRelation); + mouthCB.getAccessibleContext().getAccessibleRelationSet().add(controllerForRelation); + + // add buttons and image panels to inner panel + innerPanel.add(comboBoxPanel); + innerPanel.add(Box.createRigidArea(HGAP30)); + innerPanel.add(facePanel); + innerPanel.add(Box.createRigidArea(HGAP20)); + + // load up the face parts + addFace("brent", resourceManager.getString("ComboBoxDemo.brent")); + addFace("georges", resourceManager.getString("ComboBoxDemo.georges")); + addFace("hans", resourceManager.getString("ComboBoxDemo.hans")); + addFace("howard", resourceManager.getString("ComboBoxDemo.howard")); + addFace("james", resourceManager.getString("ComboBoxDemo.james")); + addFace("jeff", resourceManager.getString("ComboBoxDemo.jeff")); + addFace("jon", resourceManager.getString("ComboBoxDemo.jon")); + addFace("lara", resourceManager.getString("ComboBoxDemo.lara")); + addFace("larry", resourceManager.getString("ComboBoxDemo.larry")); + addFace("lisa", resourceManager.getString("ComboBoxDemo.lisa")); + addFace("michael", resourceManager.getString("ComboBoxDemo.michael")); + addFace("philip", resourceManager.getString("ComboBoxDemo.philip")); + addFace("scott", resourceManager.getString("ComboBoxDemo.scott")); + + // set the default face + presetCB.setSelectedIndex(0); + } + + private void addFace(String name, String i18n_name) { + ImageIcon i; + String i18n_hair = resourceManager.getString("ComboBoxDemo.hair"); + String i18n_eyes = resourceManager.getString("ComboBoxDemo.eyes"); + String i18n_mouth = resourceManager.getString("ComboBoxDemo.mouth"); + + parts.put(i18n_name, name); // i18n name lookup + parts.put(name, i18n_name); // reverse name lookup + + i = resourceManager.createImageIcon(name + "hair.jpg", i18n_name + i18n_hair); + parts.put(name + "hair", i); + + i = resourceManager.createImageIcon(name + "eyes.jpg", i18n_name + i18n_eyes); + parts.put(name + "eyes", i); + + i = resourceManager.createImageIcon(name + "mouth.jpg", i18n_name + i18n_mouth); + parts.put(name + "mouth", i); + } + + private JComboBox createHairComboBox() { + JComboBox cb = new JComboBox<>(); + fillComboBox(cb); + cb.addActionListener(this); + return cb; + } + + private JComboBox createEyesComboBox() { + JComboBox cb = new JComboBox<>(); + fillComboBox(cb); + cb.addActionListener(this); + return cb; + } + + private JComboBox createMouthComboBox() { + JComboBox cb = new JComboBox<>(); + fillComboBox(cb); + cb.addActionListener(this); + return cb; + } + + private JComboBox createPresetComboBox() { + JComboBox cb = new JComboBox<>(); + cb.addItem(resourceManager.getString("ComboBoxDemo.preset1")); + cb.addItem(resourceManager.getString("ComboBoxDemo.preset2")); + cb.addItem(resourceManager.getString("ComboBoxDemo.preset3")); + cb.addItem(resourceManager.getString("ComboBoxDemo.preset4")); + cb.addItem(resourceManager.getString("ComboBoxDemo.preset5")); + cb.addItem(resourceManager.getString("ComboBoxDemo.preset6")); + cb.addItem(resourceManager.getString("ComboBoxDemo.preset7")); + cb.addItem(resourceManager.getString("ComboBoxDemo.preset8")); + cb.addItem(resourceManager.getString("ComboBoxDemo.preset9")); + cb.addItem(resourceManager.getString("ComboBoxDemo.preset10")); + cb.addActionListener(this); + return cb; + } + + private void fillComboBox(JComboBox cb) { + cb.addItem(resourceManager.getString("ComboBoxDemo.brent")); + cb.addItem(resourceManager.getString("ComboBoxDemo.georges")); + cb.addItem(resourceManager.getString("ComboBoxDemo.hans")); + cb.addItem(resourceManager.getString("ComboBoxDemo.howard")); + cb.addItem(resourceManager.getString("ComboBoxDemo.james")); + cb.addItem(resourceManager.getString("ComboBoxDemo.jeff")); + cb.addItem(resourceManager.getString("ComboBoxDemo.jon")); + cb.addItem(resourceManager.getString("ComboBoxDemo.lara")); + cb.addItem(resourceManager.getString("ComboBoxDemo.larry")); + cb.addItem(resourceManager.getString("ComboBoxDemo.lisa")); + cb.addItem(resourceManager.getString("ComboBoxDemo.michael")); + cb.addItem(resourceManager.getString("ComboBoxDemo.philip")); + cb.addItem(resourceManager.getString("ComboBoxDemo.scott")); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == hairCB) { + String name = (String) parts.get(hairCB.getSelectedItem()); + face.setHair((ImageIcon) parts.get(name + "hair")); + faceLabel.repaint(); + } else if (e.getSource() == eyesCB) { + String name = (String) parts.get(eyesCB.getSelectedItem()); + face.setEyes((ImageIcon) parts.get(name + "eyes")); + faceLabel.repaint(); + } else if (e.getSource() == mouthCB) { + String name = (String) parts.get(mouthCB.getSelectedItem()); + face.setMouth((ImageIcon) parts.get(name + "mouth")); + faceLabel.repaint(); + } else if (e.getSource() == presetCB) { + String hair = null; + String eyes = null; + String mouth = null; + switch (presetCB.getSelectedIndex()) { + case 0: + hair = (String) parts.get("philip"); + eyes = (String) parts.get("howard"); + mouth = (String) parts.get("jeff"); + break; + case 1: + hair = (String) parts.get("jeff"); + eyes = (String) parts.get("larry"); + mouth = (String) parts.get("philip"); + break; + case 2: + hair = (String) parts.get("howard"); + eyes = (String) parts.get("scott"); + mouth = (String) parts.get("hans"); + break; + case 3: + hair = (String) parts.get("philip"); + eyes = (String) parts.get("jeff"); + mouth = (String) parts.get("hans"); + break; + case 4: + hair = (String) parts.get("brent"); + eyes = (String) parts.get("jon"); + mouth = (String) parts.get("scott"); + break; + case 5: + hair = (String) parts.get("lara"); + eyes = (String) parts.get("larry"); + mouth = (String) parts.get("lisa"); + break; + case 6: + hair = (String) parts.get("james"); + eyes = (String) parts.get("philip"); + mouth = (String) parts.get("michael"); + break; + case 7: + hair = (String) parts.get("philip"); + eyes = (String) parts.get("lisa"); + mouth = (String) parts.get("brent"); + break; + case 8: + hair = (String) parts.get("james"); + eyes = (String) parts.get("philip"); + mouth = (String) parts.get("jon"); + break; + case 9: + hair = (String) parts.get("lara"); + eyes = (String) parts.get("jon"); + mouth = (String) parts.get("scott"); + break; + } + if (hair != null) { + hairCB.setSelectedItem(hair); + eyesCB.setSelectedItem(eyes); + mouthCB.setSelectedItem(mouth); + faceLabel.repaint(); + } + } + } + + private static class Face implements Icon { + + private ImageIcon hair; + private ImageIcon eyes; + private ImageIcon mouth; + + void setHair(ImageIcon i) { + hair = i; + } + + void setEyes(ImageIcon i) { + eyes = i; + } + + void setMouth(ImageIcon i) { + mouth = i; + } + + @Override + public void paintIcon(Component c, Graphics g, int x, int y) { + int height = y; + x = c.getWidth() / 2 - getIconWidth() / 2; + + if (hair != null) { + hair.paintIcon(c, g, x, height); + height += hair.getIconHeight(); + } + + if (eyes != null) { + eyes.paintIcon(c, g, x, height); + height += eyes.getIconHeight(); + } + + if (mouth != null) { + mouth.paintIcon(c, g, x, height); + } + } + + @Override + public int getIconWidth() { + return 344; + } + + @Override + public int getIconHeight() { + return 455; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/ComboBoxDemo.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/ComboBoxDemo.properties Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,42 @@ +### ComboBox Demo ### + +ComboBoxDemo.accessible_description=This demo shows an example of using the JComboBox component. +ComboBoxDemo.tooltip=JComboBox demo +ComboBoxDemo.name=ComboBox Demo + +ComboBoxDemo.hair=hair +ComboBoxDemo.eyes=eyes +ComboBoxDemo.mouth=mouth +ComboBoxDemo.presets=Presets: + +ComboBoxDemo.preset1=Philip, Howard, Jeff +ComboBoxDemo.preset2=Jeff, Larry, Philip +ComboBoxDemo.preset3=Howard, Scott, Hans +ComboBoxDemo.preset4=Philip, Jeff, Hans +ComboBoxDemo.preset5=Brent, Jon, Scott +ComboBoxDemo.preset6=Lara, Larry, Lisa +ComboBoxDemo.preset7=James, Philip, Michael +ComboBoxDemo.preset8=Philip, Lisa, Brent +ComboBoxDemo.preset9=James, Philip, Jon +ComboBoxDemo.preset10=Lara, Jon, Scott + + +ComboBoxDemo.hair_description=Hair: +ComboBoxDemo.eyes_description=Eyes & Nose: +ComboBoxDemo.mouth_description=Mouth: + +ComboBoxDemo.amy=Amy +ComboBoxDemo.brent=Brent +ComboBoxDemo.georges=Georges +ComboBoxDemo.hans=Hans +ComboBoxDemo.howard=Howard +ComboBoxDemo.james=James +ComboBoxDemo.jeff=Jeff +ComboBoxDemo.jon=Jon +ComboBoxDemo.lara=Lara +ComboBoxDemo.larry=Larry +ComboBoxDemo.lisa=Lisa +ComboBoxDemo.michael=Michael +ComboBoxDemo.philip=Philip +ComboBoxDemo.scott=Scott + diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/ComboBoxDemo.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/ComboBoxDemo.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/brenteyes.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/brenteyes.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/brenthair.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/brenthair.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/brentmouth.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/brentmouth.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/georgeseyes.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/georgeseyes.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/georgeshair.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/georgeshair.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/georgesmouth.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/georgesmouth.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/hanseyes.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/hanseyes.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/hanshair.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/hanshair.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/hansmouth.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/hansmouth.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/howardeyes.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/howardeyes.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/howardhair.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/howardhair.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/howardmouth.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/howardmouth.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jameseyes.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jameseyes.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jameshair.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jameshair.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jamesmouth.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jamesmouth.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jeffeyes.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jeffeyes.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jeffhair.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jeffhair.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jeffmouth.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jeffmouth.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/joneyes.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/joneyes.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jonhair.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jonhair.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jonmouth.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/jonmouth.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/laraeyes.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/laraeyes.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/larahair.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/larahair.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/laramouth.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/laramouth.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/larryeyes.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/larryeyes.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/larryhair.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/larryhair.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/larrymouth.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/larrymouth.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/lisaeyes.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/lisaeyes.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/lisahair.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/lisahair.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/lisamouth.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/lisamouth.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/michaeleyes.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/michaeleyes.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/michaelhair.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/michaelhair.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/michaelmouth.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/michaelmouth.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/philipeyes.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/philipeyes.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/philiphair.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/philiphair.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/philipmouth.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/philipmouth.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/scotteyes.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/scotteyes.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/scotthair.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/scotthair.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/scottmouth.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/combobox/resources/images/scottmouth.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/ListDemo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/ListDemo.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,404 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.list; + +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.util.Vector; +import javax.swing.*; + +import com.sun.swingset3.DemoProperties; +import com.sun.swingset3.demos.ResourceManager; + +/** + * List Demo. This demo shows that it is not always necessary to have an array + * of objects as big as the size of the list stored. + * + * Indeed, in this example, there is no array kept for the list data, rather it + * is generated on the fly as only those elements are needed. + * + * @version 1.17 11/17/05 + * @author Jeff Dinkins + */ +@DemoProperties( + value = "JList Demo", + category = "Data", + description = "Demonstrates JList, a component which supports display/editing of a data list", + sourceFiles = { + "com/sun/swingset3/demos/list/ListDemo.java", + "com/sun/swingset3/demos/list/Permuter.java", + "com/sun/swingset3/demos/ResourceManager.java", + "com/sun/swingset3/demos/list/resources/ListDemo.properties", + "com/sun/swingset3/demos/list/resources/images/blue.gif", + "com/sun/swingset3/demos/list/resources/images/cyan.gif", + "com/sun/swingset3/demos/list/resources/images/gray.gif", + "com/sun/swingset3/demos/list/resources/images/green.gif", + "com/sun/swingset3/demos/list/resources/images/ListDemo.gif", + "com/sun/swingset3/demos/list/resources/images/magenta.gif", + "com/sun/swingset3/demos/list/resources/images/red.gif", + "com/sun/swingset3/demos/list/resources/images/yellow.gif" + } +) +public final class ListDemo extends JPanel { + + private static final Dimension HGAP10 = new Dimension(10, 1); + private static final Dimension VGAP10 = new Dimension(1, 10); + private static final Dimension HGAP15 = new Dimension(15, 1); + private static final Dimension HGAP30 = new Dimension(30, 1); + + private final ResourceManager resourceManager = new ResourceManager(this.getClass()); + public static final String DEMO_TITLE = ListDemo.class.getAnnotation(DemoProperties.class).value(); + + private final JList list; + + private JPanel prefixList; + private JPanel suffixList; + + private Action prefixAction; + private Action suffixAction; + + private final GeneratedListModel listModel; + + /** + * main method allows us to run as a standalone demo. + * + * @param args + */ + public static void main(String[] args) { + JFrame frame = new JFrame(DEMO_TITLE); + + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(new ListDemo()); + frame.setPreferredSize(new Dimension(800, 600)); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + /** + * ListDemo Constructor + */ + public ListDemo() { + setLayout(new BorderLayout()); + + loadImages(); + + JLabel description = new JLabel(resourceManager.getString("ListDemo.description")); + add(description, BorderLayout.NORTH); + + JPanel centerPanel = new JPanel(); + centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.X_AXIS)); + centerPanel.add(Box.createRigidArea(HGAP10)); + add(centerPanel, BorderLayout.CENTER); + + JPanel listPanel = new JPanel(); + listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.Y_AXIS)); + listPanel.add(Box.createRigidArea(VGAP10)); + + centerPanel.add(listPanel); + centerPanel.add(Box.createRigidArea(HGAP30)); + + // Create the list + list = new JList<>(); + list.setCellRenderer(new CompanyLogoListCellRenderer()); + listModel = new GeneratedListModel(); + list.setModel(listModel); + + // Set the preferred row count. This affects the preferredSize + // of the JList when it's in a scrollpane. + list.setVisibleRowCount(22); + + // Add list to a scrollpane + JScrollPane scrollPane = new JScrollPane(list); + listPanel.add(scrollPane); + listPanel.add(Box.createRigidArea(VGAP10)); + + // Add the control panel (holds the prefix/suffix list and prefix/suffix checkboxes) + centerPanel.add(createControlPanel()); + + // create prefixes and suffixes + addPrefix("Tera", true); + addPrefix("Micro", false); + addPrefix("Southern", false); + addPrefix("Net", true); + addPrefix("YoYo", true); + addPrefix("Northern", false); + addPrefix("Tele", false); + addPrefix("Eastern", false); + addPrefix("Neo", false); + addPrefix("Digi", false); + addPrefix("National", false); + addPrefix("Compu", true); + addPrefix("Meta", true); + addPrefix("Info", false); + addPrefix("Western", false); + addPrefix("Data", false); + addPrefix("Atlantic", false); + addPrefix("Advanced", false); + addPrefix("Euro", false); + addPrefix("Pacific", false); + addPrefix("Mobile", false); + addPrefix("In", false); + addPrefix("Computa", false); + addPrefix("Digital", false); + addPrefix("Analog", false); + + addSuffix("Tech", true); + addSuffix("Soft", true); + addSuffix("Telecom", true); + addSuffix("Solutions", false); + addSuffix("Works", true); + addSuffix("Dyne", false); + addSuffix("Services", false); + addSuffix("Vers", false); + addSuffix("Devices", false); + addSuffix("Software", false); + addSuffix("Serv", false); + addSuffix("Systems", true); + addSuffix("Dynamics", true); + addSuffix("Net", false); + addSuffix("Sys", false); + addSuffix("Computing", false); + addSuffix("Scape", false); + addSuffix("Com", false); + addSuffix("Ware", false); + addSuffix("Widgets", false); + addSuffix("Media", false); + addSuffix("Computer", false); + addSuffix("Hardware", false); + addSuffix("Gizmos", false); + addSuffix("Concepts", false); + } + + private JPanel createControlPanel() { + JPanel controlPanel = new JPanel() { + private final Insets insets = new Insets(0, 4, 10, 10); + + @Override + public Insets getInsets() { + return insets; + } + }; + controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.X_AXIS)); + + JPanel prefixPanel = new JPanel(); + prefixPanel.setLayout(new BoxLayout(prefixPanel, BoxLayout.Y_AXIS)); + prefixPanel.add(new JLabel(resourceManager.getString("ListDemo.prefixes"))); + + JPanel suffixPanel = new JPanel(); + suffixPanel.setLayout(new BoxLayout(suffixPanel, BoxLayout.Y_AXIS)); + suffixPanel.add(new JLabel(resourceManager.getString("ListDemo.suffixes"))); + + prefixList = new JPanel() { + private final Insets insets = new Insets(0, 4, 0, 0); + + @Override + public Insets getInsets() { + return insets; + } + }; + prefixList.setLayout(new BoxLayout(prefixList, BoxLayout.Y_AXIS)); + JScrollPane scrollPane = new JScrollPane(prefixList); + scrollPane.getVerticalScrollBar().setUnitIncrement(10); + prefixPanel.add(scrollPane); + prefixPanel.add(Box.createRigidArea(HGAP10)); + + suffixList = new JPanel() { + private final Insets insets = new Insets(0, 4, 0, 0); + + @Override + public Insets getInsets() { + return insets; + } + }; + suffixList.setLayout(new BoxLayout(suffixList, BoxLayout.Y_AXIS)); + scrollPane = new JScrollPane(suffixList); + scrollPane.getVerticalScrollBar().setUnitIncrement(10); + suffixPanel.add(scrollPane); + suffixPanel.add(Box.createRigidArea(HGAP10)); + + controlPanel.add(prefixPanel); + controlPanel.add(Box.createRigidArea(HGAP15)); + controlPanel.add(suffixPanel); + return controlPanel; + } + + private final FocusListener listFocusListener = new FocusAdapter() { + @Override + public void focusGained(FocusEvent e) { + JComponent c = (JComponent) e.getComponent(); + c.scrollRectToVisible(new Rectangle(0, 0, c.getWidth(), c.getHeight())); + } + }; + + private void addPrefix(String prefix, boolean selected) { + if (prefixAction == null) { + prefixAction = new UpdatePrefixListAction(listModel); + } + final JCheckBox cb = (JCheckBox) prefixList.add(new JCheckBox(prefix)); + cb.setSelected(selected); + cb.addActionListener(prefixAction); + if (selected) { + listModel.addPrefix(prefix); + } + cb.addFocusListener(listFocusListener); + } + + private void addSuffix(String suffix, boolean selected) { + if (suffixAction == null) { + suffixAction = new UpdateSuffixListAction(listModel); + } + final JCheckBox cb = (JCheckBox) suffixList.add(new JCheckBox(suffix)); + cb.setSelected(selected); + cb.addActionListener(suffixAction); + if (selected) { + listModel.addSuffix(suffix); + } + cb.addFocusListener(listFocusListener); + } + + private static class UpdatePrefixListAction extends AbstractAction { + + private final GeneratedListModel listModel; + + protected UpdatePrefixListAction(GeneratedListModel listModel) { + this.listModel = listModel; + } + + @Override + public void actionPerformed(ActionEvent e) { + JCheckBox cb = (JCheckBox) e.getSource(); + if (cb.isSelected()) { + listModel.addPrefix(cb.getText()); + } else { + listModel.removePrefix(cb.getText()); + } + } + } + + private static class UpdateSuffixListAction extends AbstractAction { + + private final GeneratedListModel listModel; + + protected UpdateSuffixListAction(GeneratedListModel listModel) { + this.listModel = listModel; + } + + @Override + public void actionPerformed(ActionEvent e) { + JCheckBox cb = (JCheckBox) e.getSource(); + if (cb.isSelected()) { + listModel.addSuffix(cb.getText()); + } else { + listModel.removeSuffix(cb.getText()); + } + } + } + + private static class GeneratedListModel extends AbstractListModel { + + private Permuter permuter; + + private final Vector prefix = new Vector<>(); + private final Vector suffix = new Vector<>(); + + private void update() { + permuter = new Permuter(getSize()); + fireContentsChanged(this, 0, getSize()); + } + + public void addPrefix(String s) { + if (!prefix.contains(s)) { + prefix.addElement(s); + update(); + } + } + + public void removePrefix(String s) { + prefix.removeElement(s); + update(); + } + + public void addSuffix(String s) { + if (!suffix.contains(s)) { + suffix.addElement(s); + update(); + } + } + + public void removeSuffix(String s) { + suffix.removeElement(s); + update(); + } + + @Override + public int getSize() { + return prefix.size() * suffix.size(); + } + + @Override + public String getElementAt(int index) { + if (permuter == null) { + update(); + } + // morph the index to another int -- this has the benefit of + // causing the list to look random. + int j = permuter.map(index); + int ps = prefix.size(); + int ss = suffix.size(); + return prefix.elementAt(j % ps) + suffix.elementAt((j / ps) % ss); + } + } + + private final ImageIcon[] images = new ImageIcon[7]; + + void loadImages() { + images[0] = resourceManager.createImageIcon("red.gif", resourceManager.getString("ListDemo.red")); + images[1] = resourceManager.createImageIcon("blue.gif", resourceManager.getString("ListDemo.blue")); + images[2] = resourceManager.createImageIcon("yellow.gif", resourceManager.getString("ListDemo.yellow")); + images[3] = resourceManager.createImageIcon("green.gif", resourceManager.getString("ListDemo.green")); + images[4] = resourceManager.createImageIcon("gray.gif", resourceManager.getString("ListDemo.gray")); + images[5] = resourceManager.createImageIcon("cyan.gif", resourceManager.getString("ListDemo.cyan")); + images[6] = resourceManager.createImageIcon("magenta.gif", resourceManager.getString("ListDemo.magenta")); + } + + private class CompanyLogoListCellRenderer extends DefaultListCellRenderer { + + @Override + public Component getListCellRendererComponent( + JList list, + Object value, + int index, + boolean isSelected, + boolean cellHasFocus) { + Component retValue = super.getListCellRendererComponent( + list, value, index, isSelected, cellHasFocus + ); + setIcon(images[index % 7]); + return retValue; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/Permuter.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/Permuter.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.list; + +/** + * An object that implements a cheesy pseudorandom permutation of the integers + * from zero to some user-specified value. (The permutation is a linear + * function.) + * + * @version 1.9 11/17/05 + * @author Josh Bloch + */ +class Permuter { + + /** + * The size of the permutation. + */ + private int modulus; + + /** + * Nonnegative integer less than n that is relatively prime to m. + */ + private int multiplier; + + /** + * Pseudorandom nonnegative integer less than n. + */ + private static final int ADDEND = 22; + + public Permuter(int n) { + if (n < 0) { + throw new IllegalArgumentException(); + } + modulus = n; + if (n == 1) { + return; + } + + // Initialize the multiplier and offset + multiplier = (int) Math.sqrt(n); + while (gcd(multiplier, n) != 1) { + if (++multiplier == n) { + multiplier = 1; + } + } + } + + /** + * Returns the integer to which this permuter maps the specified integer. + * The specified integer must be between 0 and n-1, and the returned integer + * will be as well. + */ + public int map(int i) { + return (multiplier * i + ADDEND) % modulus; + } + + /** + * Calculate GCD of a and b, which are assumed to be non-negative. + */ + private static int gcd(int a, int b) { + while (b != 0) { + int tmp = a % b; + a = b; + b = tmp; + } + return a; + } + + /** + * Simple test. Takes modulus on command line and prints out permutation. + */ + public static void main(String[] args) { + int modulus = Integer.parseInt(args[0]); + Permuter p = new Permuter(modulus); + for (int i = 0; i < modulus; i++) { + System.out.print(p.map(i) + " "); + } + System.out.println(); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/ListDemo.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/ListDemo.properties Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,18 @@ +### List Demo ### + +ListDemo.accessible_description=JList Demo +ListDemo.name=List Demo +ListDemo.tooltip=JList demo +ListDemo.prefixes=Prefixes +ListDemo.suffixes=Suffixes +ListDemo.count_label=Number of generated list entries: +ListDemo.all=All +ListDemo.none=None +ListDemo.red=Red Company Logo Image +ListDemo.yellow=Red Company Logo Image +ListDemo.blue=Blue Company Logo Image +ListDemo.gray=Gray Company Logo Image +ListDemo.green=Green Company Logo Image +ListDemo.magenta=Magenta Company Logo Image +ListDemo.cyan=Cyan Company Logo Image +ListDemo.description=

This demo shows how to present lists of data in two different ways. On the left is a JList component whose list items consist of the permutations of the checked prefixes and suffixes. The prefix and suffix checkbox columns on the right are created by using a JPanel with a Y Axis BoxLayout inside a JScrollPane.

diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/ListDemo.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/ListDemo.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/blue.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/blue.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/cyan.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/cyan.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/gray.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/gray.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/green.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/green.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/magenta.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/magenta.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/red.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/red.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/yellow.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/list/resources/images/yellow.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/optionpane/OptionPaneDemo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/optionpane/OptionPaneDemo.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.optionpane; + +import java.awt.*; +import java.awt.event.ActionEvent; +import java.net.URL; +import javax.swing.*; + +import com.sun.swingset3.demos.ResourceManager; +import com.sun.swingset3.DemoProperties; + +/** + * JOptionPaneDemo + * + * @author Jeff Dinkins + * @version 1.11 11/17/05 + */ +@DemoProperties( + value = "JOptionPane Demo", + category = "Choosers", + description = "Demonstrates JOptionPane, a component which displays standard message dialogs (question, warning, error, etc).", + sourceFiles = { + "com/sun/swingset3/demos/optionpane/OptionPaneDemo.java", + "com/sun/swingset3/demos/ResourceManager.java", + "com/sun/swingset3/demos/optionpane/resources/OptionPaneDemo.properties", + "com/sun/swingset3/demos/optionpane/resources/images/bottle.gif", + "com/sun/swingset3/demos/optionpane/resources/images/OptionPaneDemo.gif" + } +) +public class OptionPaneDemo extends JPanel { + + private static final Dimension VGAP15 = new Dimension(1, 15); + private static final Dimension VGAP30 = new Dimension(1, 30); + + private static final ResourceManager resourceManager = new ResourceManager(OptionPaneDemo.class); + public static final String WARNING_TITLE = resourceManager.getString("OptionPaneDemo.warningtitle"); + public static final String WARNING_TEXT = resourceManager.getString("OptionPaneDemo.warningtext"); + public static final String WARNING_BUTTON = resourceManager.getString("OptionPaneDemo.warningbutton"); + public static final String CONFIRM_NO = resourceManager.getString("OptionPaneDemo.confirmno"); + public static final String CONFIRM_YES = resourceManager.getString("OptionPaneDemo.confirmyes"); + public static final String CONFIRM_QUESTION = resourceManager.getString("OptionPaneDemo.confirmquestion"); + public static final String CONFIRM_BUTTON = resourceManager.getString("OptionPaneDemo.confirmbutton"); + public static final String MESSAGE_TEXT = resourceManager.getString("OptionPaneDemo.messagetext"); + public static final String MESSAGE_BUTTON = resourceManager.getString("OptionPaneDemo.messagebutton"); + public static final String INPUT_QUESTION = resourceManager.getString("OptionPaneDemo.inputquestion"); + public static final String INPUT_RESPONSE = ": " + resourceManager.getString("OptionPaneDemo.inputresponse"); + public static final String INPUT_BUTTON = resourceManager.getString("OptionPaneDemo.inputbutton"); + public static final String COMPONENT_R4 = resourceManager.getString("OptionPaneDemo.component_r4"); + public static final String COMPONENT_R3 = resourceManager.getString("OptionPaneDemo.component_r3"); + public static final String COMPONENT_R2 = resourceManager.getString("OptionPaneDemo.component_r2"); + public static final String COMPONENT_R1 = resourceManager.getString("OptionPaneDemo.component_r1"); + public static final String COMPONENT_TITLE = resourceManager.getString("OptionPaneDemo.componenttitle"); + public static final String COMPONENT_OP5 = resourceManager.getString("OptionPaneDemo.component_op5"); + public static final String COMPONENT_OP4 = resourceManager.getString("OptionPaneDemo.component_op4"); + public static final String COMPONENT_OP3 = resourceManager.getString("OptionPaneDemo.component_op3"); + public static final String COMPONENT_OP2 = resourceManager.getString("OptionPaneDemo.component_op2"); + public static final String COMPONENT_OP1 = resourceManager.getString("OptionPaneDemo.component_op1"); + public static final String COMPONENT_MESSAGE_2 = resourceManager.getString("OptionPaneDemo.componentmessage2"); + public static final String COMPONENT_CB3 = resourceManager.getString("OptionPaneDemo.component_cb3"); + public static final String COMPONENT_CB2 = resourceManager.getString("OptionPaneDemo.component_cb2"); + public static final String COMPONENT_CB1 = resourceManager.getString("OptionPaneDemo.component_cb1"); + public static final String COMPONENT_BUTTON = resourceManager.getString("OptionPaneDemo.componentbutton"); + public static final String COMPONENT_TEXT_FIELD = resourceManager.getString("OptionPaneDemo.componenttextfield"); + public static final String COMPONENT_MESSAGE = resourceManager.getString("OptionPaneDemo.componentmessage"); + public static final String DEMO_TITLE = OptionPaneDemo.class.getAnnotation(DemoProperties.class).value(); + + /** + * main method allows us to run as a standalone demo. + * + * @param args + */ + public static void main(String[] args) { + JFrame frame = new JFrame(DEMO_TITLE); + + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(new OptionPaneDemo()); + frame.setPreferredSize(new Dimension(800, 600)); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + /** + * OptionPaneDemo Constructor + */ + public OptionPaneDemo() { + setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); + + JPanel bp = new JPanel() { + @Override + public Dimension getMaximumSize() { + return new Dimension(getPreferredSize().width, super.getMaximumSize().height); + } + }; + bp.setLayout(new BoxLayout(bp, BoxLayout.Y_AXIS)); + + bp.add(Box.createRigidArea(VGAP30)); + bp.add(Box.createRigidArea(VGAP30)); + + bp.add(createInputDialogButton()); + bp.add(Box.createRigidArea(VGAP15)); + bp.add(createWarningDialogButton()); + bp.add(Box.createRigidArea(VGAP15)); + bp.add(createMessageDialogButton()); + bp.add(Box.createRigidArea(VGAP15)); + bp.add(createComponentDialogButton()); + bp.add(Box.createRigidArea(VGAP15)); + bp.add(createConfirmDialogButton()); + bp.add(Box.createVerticalGlue()); + + add(Box.createHorizontalGlue()); + add(bp); + add(Box.createHorizontalGlue()); + } + + private JButton createWarningDialogButton() { + Action a = new AbstractAction(WARNING_BUTTON) { + @Override + public void actionPerformed(ActionEvent e) { + JOptionPane.showMessageDialog(OptionPaneDemo.this, + WARNING_TEXT, + WARNING_TITLE, + JOptionPane.WARNING_MESSAGE + ); + } + }; + return createButton(a); + } + + private JButton createMessageDialogButton() { + Action a = new AbstractAction(MESSAGE_BUTTON) { + final URL img = getClass().getResource("resources/images/bottle.gif"); + final String imagesrc = ""; + final String message = MESSAGE_TEXT; + + @Override + public void actionPerformed(ActionEvent e) { + JOptionPane.showMessageDialog( + OptionPaneDemo.this, + "" + imagesrc + "
" + message + "

" + ); + } + }; + return createButton(a); + } + + private JButton createConfirmDialogButton() { + Action a = new AbstractAction(CONFIRM_BUTTON) { + @Override + public void actionPerformed(ActionEvent e) { + int result = JOptionPane.showConfirmDialog(OptionPaneDemo.this, CONFIRM_QUESTION); + if (result == JOptionPane.YES_OPTION) { + JOptionPane.showMessageDialog(OptionPaneDemo.this, CONFIRM_YES); + } else if (result == JOptionPane.NO_OPTION) { + JOptionPane.showMessageDialog(OptionPaneDemo.this, CONFIRM_NO); + } + } + }; + return createButton(a); + } + + private JButton createInputDialogButton() { + Action a = new AbstractAction(INPUT_BUTTON) { + @Override + public void actionPerformed(ActionEvent e) { + String result = JOptionPane.showInputDialog(OptionPaneDemo.this, INPUT_QUESTION); + if ((result != null) && (result.length() > 0)) { + JOptionPane.showMessageDialog(OptionPaneDemo.this, + result + INPUT_RESPONSE); + } + } + }; + return createButton(a); + } + + private JButton createComponentDialogButton() { + Action a = new AbstractAction(COMPONENT_BUTTON) { + @Override + public void actionPerformed(ActionEvent e) { + // In a ComponentDialog, you can show as many message components and + // as many options as you want: + + // Messages + Object[] message = new Object[4]; + message[0] = COMPONENT_MESSAGE; + message[1] = new JTextField(COMPONENT_TEXT_FIELD); + + JComboBox cb = new JComboBox<>(); + cb.addItem(COMPONENT_CB1); + cb.addItem(COMPONENT_CB2); + cb.addItem(COMPONENT_CB3); + message[2] = cb; + + message[3] = COMPONENT_MESSAGE_2; + + // Options + String[] options = { + COMPONENT_OP1, COMPONENT_OP2, COMPONENT_OP3, COMPONENT_OP4, COMPONENT_OP5}; + int result = JOptionPane.showOptionDialog( + OptionPaneDemo.this, // the parent that the dialog blocks + message, // the dialog message array + COMPONENT_TITLE, // the title of the dialog window + JOptionPane.DEFAULT_OPTION, // option type + JOptionPane.INFORMATION_MESSAGE, // message type + null, // optional icon, use null to use the default icon + options, // options string array, will be made into buttons + options[3] // option that should be made into a default button + ); + switch (result) { + case 0: // yes + JOptionPane.showMessageDialog(OptionPaneDemo.this, COMPONENT_R1); + break; + case 1: // no + JOptionPane.showMessageDialog(OptionPaneDemo.this, COMPONENT_R2); + break; + case 2: // maybe + JOptionPane.showMessageDialog(OptionPaneDemo.this, COMPONENT_R3); + break; + case 3: // probably + JOptionPane.showMessageDialog(OptionPaneDemo.this, COMPONENT_R4); + break; + default: + break; + } + + } + }; + return createButton(a); + } + + private JButton createButton(Action a) { + JButton b = new JButton() { + @Override + public Dimension getMaximumSize() { + int width = Short.MAX_VALUE; + int height = super.getMaximumSize().height; + return new Dimension(width, height); + } + }; + // setting the following client property informs the button to show + // the action text as it's name. The default is to not show the + // action text. + b.putClientProperty("displayActionText", Boolean.TRUE); + b.setAction(a); + // b.setAlignmentX(JButton.CENTER_ALIGNMENT); + return b; + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/optionpane/resources/OptionPaneDemo.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/optionpane/resources/OptionPaneDemo.properties Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,42 @@ +### OptionPane Demo ### + +OptionPaneDemo.accessible_description=The OptionPane Demo shows examples of using JOptionPane to generate different common option dialog boxes +OptionPaneDemo.tooltip=JOptionPane Demo +OptionPaneDemo.name=Option Pane Demo + +OptionPaneDemo.warningbutton=Show Warning Dialog +OptionPaneDemo.componentbutton=Show Component Dialog +OptionPaneDemo.inputbutton=Show Input Dialog +OptionPaneDemo.confirmbutton=Show Confirmation Dialog +OptionPaneDemo.messagebutton=Show Message Dialog + +OptionPaneDemo.warningtitle=Warning Dialog Example +OptionPaneDemo.warningtext=

This is a test of the Emergency Broadcast System. This is
only a test
. The webmaster of your local intranet, in voluntary
cooperation with the Federal and State authorities, have
developed this system to keep you informed in the event of an
emergency. If this had been an actual emergency, the signal you
just heard would have been followed by official information, news
or instructions. This concludes this test of the Emergency
Broadcast System
.


Developer Note: This dialog demo used HTML for text formatting.

+ +OptionPaneDemo.messagetext=Message in a Bottle (yeah) + +OptionPaneDemo.confirmquestion=Is the sun shining outside today? +OptionPaneDemo.confirmyes=Well what are you doing playing on the computer?
Get outside! Take a trip to the beach! Get a little sun! +OptionPaneDemo.confirmno=Well good thing you're inside protected from the elements! + +OptionPaneDemo.inputquestion=What is your favorite movie? +OptionPaneDemo.inputresponse=That was a pretty good movie! + +OptionPaneDemo.componenttitle=Component Dialog Example +OptionPaneDemo.componentmessage=JOptionPane can contain as many components
as you want, such as a text field: +OptionPaneDemo.componenttextfield=or a combobox: +OptionPaneDemo.component_cb1=item 1 +OptionPaneDemo.component_cb2=item 2 +OptionPaneDemo.component_cb3=item 3 +OptionPaneDemo.componentmessage2=JOptionPane can also show as many options
as you want: +OptionPaneDemo.component_op1=Yes +OptionPaneDemo.component_op2=No +OptionPaneDemo.component_op3=Maybe +OptionPaneDemo.component_op4=Probably +OptionPaneDemo.component_op5=Cancel + +OptionPaneDemo.component_r1=Upbeat and positive! I like that! Good choice. +OptionPaneDemo.component_r2=Definitely not, I wouldn't do it either. +OptionPaneDemo.component_r3= Mmmm.. yes, the situation is unclear at this
time. Check back when you know for sure.
+OptionPaneDemo.component_r4=You know you want to. I think you should
have gone for broke and pressed "Yes".
+ diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/optionpane/resources/images/OptionPaneDemo.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/optionpane/resources/images/OptionPaneDemo.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/optionpane/resources/images/bottle.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/optionpane/resources/images/bottle.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/progressbar/ProgressBarDemo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/progressbar/ProgressBarDemo.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.progressbar; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import javax.swing.*; +import javax.swing.border.BevelBorder; +import javax.swing.border.SoftBevelBorder; + +import com.sun.swingset3.DemoProperties; +import com.sun.swingset3.demos.ResourceManager; + +/** + * JProgressBar Demo + * + * @version 1.12 11/17/05 + * @author Jeff Dinkins # @author Peter Korn (accessibility support) + */ +@DemoProperties( + value = "ProgressBar Demo", + category = "Controls", + description = "Demonstrates the JProgressBar, a control which displays progress to the user", + sourceFiles = { + "com/sun/swingset3/demos/progressbar/ProgressBarDemo.java", + "com/sun/swingset3/demos/ResourceManager.java", + "com/sun/swingset3/demos/progressbar/resources/ProgressBarDemo.properties", + "com/sun/swingset3/demos/progressbar/resources/images/ProgressBarDemo.gif" + } +) +public class ProgressBarDemo extends JPanel { + + private static final ResourceManager resourceManager = new ResourceManager(ProgressBarDemo.class); + public static final String STOP_BUTTON = resourceManager.getString("ProgressBarDemo.stop_button"); + public static final String START_BUTTON = resourceManager.getString("ProgressBarDemo.start_button"); + public static final String DEMO_TITLE = ProgressBarDemo.class.getAnnotation(DemoProperties.class).value(); + + /** + * main method allows us to run as a standalone demo. + * + * @param args + */ + public static void main(String[] args) { + JFrame frame = new JFrame(DEMO_TITLE); + + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(new ProgressBarDemo()); + frame.setPreferredSize(new Dimension(800, 600)); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + /** + * ProgressBarDemo Constructor + */ + public ProgressBarDemo() { + createProgressPanel(); + } + + private final javax.swing.Timer timer = new javax.swing.Timer(18, createTextLoadAction()); + private Action loadAction; + private Action stopAction; + private JProgressBar progressBar; + private JTextArea progressTextArea; + + private void createProgressPanel() { + setLayout(new BorderLayout()); + + JPanel textWrapper = new JPanel(new BorderLayout()); + textWrapper.setBorder(new SoftBevelBorder(BevelBorder.LOWERED)); + textWrapper.setAlignmentX(LEFT_ALIGNMENT); + progressTextArea = new MyTextArea(); + + progressTextArea.getAccessibleContext().setAccessibleName( + resourceManager.getString("ProgressBarDemo.accessible_text_area_name")); + progressTextArea.getAccessibleContext().setAccessibleDescription( + resourceManager.getString("ProgressBarDemo.accessible_text_area_description")); + textWrapper.add(new JScrollPane(progressTextArea), BorderLayout.CENTER); + + add(textWrapper, BorderLayout.CENTER); + + JPanel progressPanel = new JPanel(); + add(progressPanel, BorderLayout.SOUTH); + + progressBar = new JProgressBar(JProgressBar.HORIZONTAL, 0, text.length()) { + @Override + public Dimension getPreferredSize() { + return new Dimension(300, super.getPreferredSize().height); + } + }; + progressBar.getAccessibleContext().setAccessibleName( + resourceManager.getString("ProgressBarDemo.accessible_text_loading_progress")); + + progressPanel.add(progressBar); + progressPanel.add(createLoadButton()); + progressPanel.add(createStopButton()); + } + + private JButton createLoadButton() { + loadAction = new AbstractAction(START_BUTTON) { + @Override + public void actionPerformed(ActionEvent e) { + loadAction.setEnabled(false); + stopAction.setEnabled(true); + if (progressBar.getValue() == progressBar.getMaximum()) { + progressBar.setValue(0); + textLocation = 0; + progressTextArea.setText(""); + } + timer.start(); + } + }; + return createButton(loadAction); + } + + private JButton createStopButton() { + stopAction = new AbstractAction(STOP_BUTTON) { + @Override + public void actionPerformed(ActionEvent e) { + timer.stop(); + loadAction.setEnabled(true); + stopAction.setEnabled(false); + } + }; + return createButton(stopAction); + } + + private static JButton createButton(Action a) { + JButton b = new JButton(); + // setting the following client property informs the button to show + // the action text as it's name. The default is to not show the + // action text. + b.putClientProperty("displayActionText", Boolean.TRUE); + b.setAction(a); + return b; + } + + private int textLocation = 0; + + private final String text = resourceManager.getString("ProgressBarDemo.text"); + + private Action createTextLoadAction() { + return new AbstractAction("text load action") { + @Override + public void actionPerformed(ActionEvent e) { + if (progressBar.getValue() < progressBar.getMaximum()) { + progressBar.setValue(progressBar.getValue() + 1); + progressTextArea.append(text.substring(textLocation, textLocation + 1)); + textLocation++; + } else { + timer.stop(); + loadAction.setEnabled(true); + stopAction.setEnabled(false); + } + } + }; + } + + private static class MyTextArea extends JTextArea { + + private MyTextArea() { + super(null, 0, 0); + setEditable(false); + setText(""); + } + + @Override + public float getAlignmentX() { + return LEFT_ALIGNMENT; + } + + @Override + public float getAlignmentY() { + return TOP_ALIGNMENT; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/progressbar/resources/ProgressBarDemo.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/progressbar/resources/ProgressBarDemo.properties Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,35 @@ +### ProgressBar Demo ### + +ProgressBarDemo.accessible_description=This demo shows an example of using the JProgressBar component. +ProgressBarDemo.tooltip=JProgressBar demo +ProgressBarDemo.name=ProgressBar Demo +ProgressBarDemo.start_button=Start Loading Text +ProgressBarDemo.stop_button=Stop Loading Text +ProgressBarDemo.accessible_text_loading_progress=Text loading progress +ProgressBarDemo.accessible_text_area_name=Text progressively being loaded in + +ProgressBarDemo.accessible_text_area_description=This JTextArea is being filled with text from a buffer progressively a character at a time while the progress bar a the bottom of the window shows the loading progress + +ProgressBarDemo.text=\ +The saying goes: if an infinite number of monkeys typed on an infinite number of typewriters, eventually \n\ +all the great works of mankind would emerge. Now, with today's high speed computers, we can finally test \n\ +this theory... \n\n\ +\tLzskd jfy 92y;ho4 th;qlh sd 6yty;q2 hnlj 8sdf. Djfy 92y;ho4, th;qxhz d7yty; \n\ +\tQ0hnlj 23&^ (# ljask djf y92y; fy92y; Sd6y ty;q2h nl jk la gfa harvin garvel\n\ +\tlasdfsd a83sl la8z ks8l 92y;ho4 th;qlh sd 6yty;q2 hnlj 8sdf. Djfy 92y;ho4,\n\ +\tth;qxhz d7yty; Q0hnlj 23&^ nknod mrs88 jsd79lfm#%$JLaoz6df lso7dj f2 jfls\n\ +\t67d9ol1@2fou99s 1lkj2 @l.k1 2; a89o7aljf 1l3i7ou8 d8l3 lqwerty0092 #1!\n\ +\tja9o do8lkjj139rojsd9**!l6*hd # ljasd78 l2awkjad78 3ol7asljf 3 ldif & l.js\n\ +\tLl ls ewan la8uj 23lll7u 8l 3h hhxx8 8d lsd fixx 891lkjno99sl d8l@@@!!8#8\n\ +\tdfoil jarooda mklaoorj nowai the smisthliylka jkdlfjiw ladajadra lthhheeejfjl\n\ +\tdkddooolda bub mirznod of the koojgaf!! But 2 be or not to be... that is the\n\ +\tquestion. Then when shall we three meet again In thunder, lightning, or in\n\ +\train? When the hurlyburly's done, When the battle's lost and won. That will\n\ +\tbe ere the set of sun. Where the place? Upon the heath. There to meet with\n\ +\tMacbeth. But hath forth not to want..... a banana, or to be.... a banana.\n\ +\tBanana, I knew him banana. Banana banana. Banana banana banana banana.\n\ +\n\ +\n\ +\n\ +\n\ +Well... hmm.... it seemed like a good idea... diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/progressbar/resources/images/ProgressBarDemo.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/progressbar/resources/images/ProgressBarDemo.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/ScrollPaneDemo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/ScrollPaneDemo.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.scrollpane; + +import java.awt.*; +import javax.swing.*; + +import com.sun.swingset3.DemoProperties; +import com.sun.swingset3.demos.ResourceManager; + +/** + * Scroll Pane Demo + * + * @version 1.9 11/17/05 + * @author Jeff Dinkins + */ +@DemoProperties( + value = "JScrollPane Demo", + category = "Containers", + description = "Demonstrates JScrollPane, a container for scrolling contents within a view port", + sourceFiles = { + "com/sun/swingset3/demos/scrollpane/ScrollPaneDemo.java", + "com/sun/swingset3/demos/ResourceManager.java", + "com/sun/swingset3/demos/scrollpane/resources/ScrollPaneDemo.properties", + "com/sun/swingset3/demos/scrollpane/resources/images/colheader.jpg", + "com/sun/swingset3/demos/scrollpane/resources/images/COPYRIGHT", + "com/sun/swingset3/demos/scrollpane/resources/images/crayons.jpg", + "com/sun/swingset3/demos/scrollpane/resources/images/lowerleft.jpg", + "com/sun/swingset3/demos/scrollpane/resources/images/rowheader.jpg", + "com/sun/swingset3/demos/scrollpane/resources/images/ScrollPaneDemo.gif", + "com/sun/swingset3/demos/scrollpane/resources/images/upperleft.jpg", + "com/sun/swingset3/demos/scrollpane/resources/images/upperright.jpg"} +) +public class ScrollPaneDemo extends JPanel { + + private final ResourceManager resourceManager = new ResourceManager(this.getClass()); + public static final String DEMO_TITLE = ScrollPaneDemo.class.getAnnotation(DemoProperties.class).value(); + + /** + * main method allows us to run as a standalone demo. + * + * @param args + */ + public static void main(String[] args) { + JFrame frame = new JFrame(DEMO_TITLE); + + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(new ScrollPaneDemo()); + frame.setPreferredSize(new Dimension(800, 600)); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + /** + * ScrollPaneDemo Constructor + */ + public ScrollPaneDemo() { + setLayout(new BorderLayout()); + + ImageIcon crayons = resourceManager.createImageIcon("crayons.jpg", + resourceManager.getString("ScrollPaneDemo.crayons")); + add(new ImageScroller(crayons), BorderLayout.CENTER); + } + + /** + * ScrollPane class that demonstrates how to set the various column and row + * headers and corners. + */ + private class ImageScroller extends JScrollPane { + + public ImageScroller(Icon icon) { + super(); + + // Panel to hold the icon image + JPanel p = new JPanel(new BorderLayout()); + p.add(new JLabel(icon), BorderLayout.CENTER); + getViewport().add(p); + + // Create and add a column header to the scrollpane + JLabel colHeader = new JLabel( + resourceManager.createImageIcon("colheader.jpg", resourceManager.getString("ScrollPaneDemo.colheader"))); + setColumnHeaderView(colHeader); + + // Create and add a row header to the scrollpane + JLabel rowHeaderLabel = new JLabel( + resourceManager.createImageIcon("rowheader.jpg", resourceManager.getString("ScrollPaneDemo.rowheader"))); + setRowHeaderView(rowHeaderLabel); + + // Create and add the upper left corner + JLabel cornerUL = new JLabel( + resourceManager.createImageIcon("upperleft.jpg", resourceManager.getString("ScrollPaneDemo.upperleft"))); + setCorner(UPPER_LEFT_CORNER, cornerUL); + + // Create and add the upper right corner + JLabel cornerUR = new JLabel( + resourceManager.createImageIcon("upperright.jpg", resourceManager.getString("ScrollPaneDemo.upperright"))); + setCorner(UPPER_RIGHT_CORNER, cornerUR); + + // Create and add the lower left corner + JLabel cornerLL = new JLabel( + resourceManager.createImageIcon("lowerleft.jpg", resourceManager.getString("ScrollPaneDemo.lowerleft"))); + setCorner(LOWER_LEFT_CORNER, cornerLL); + + JScrollBar vsb = getVerticalScrollBar(); + JScrollBar hsb = getHorizontalScrollBar(); + + vsb.setValue(icon.getIconHeight()); + hsb.setValue(icon.getIconWidth() / 10); + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/ScrollPaneDemo.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/ScrollPaneDemo.properties Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,11 @@ +### ScrollPane Demo ### + +ScrollPaneDemo.accessible_description=JScrollPane Demo +ScrollPaneDemo.name=Scroll Pane Demo +ScrollPaneDemo.tooltip=JScrollPane demo +ScrollPaneDemo.crayons=Lots of Crayons +ScrollPaneDemo.colheader=Column Header +ScrollPaneDemo.rowheader=Row Header +ScrollPaneDemo.upperleft=Upper Left Corner +ScrollPaneDemo.upperright=Upper Right Column Header Corner +ScrollPaneDemo.lowerleft=Lower Left Row Header Corner diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/COPYRIGHT --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/COPYRIGHT Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,2 @@ + + All images in this directory are copyright 1995 by Jeff Dinkins. diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/ScrollPaneDemo.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/ScrollPaneDemo.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/colheader.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/colheader.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/crayons.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/crayons.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/lowerleft.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/lowerleft.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/rowheader.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/rowheader.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/upperleft.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/upperleft.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/upperright.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/scrollpane/resources/images/upperright.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/JMandelbrot.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/JMandelbrot.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,328 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.spinner; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.*; +import java.awt.geom.Point2D; +import java.awt.image.BufferedImage; +import java.awt.image.DataBufferInt; +import java.util.List; + +import com.sun.swingset3.demos.ResourceManager; + +/** + * @author Mikhail Lapshin + */ +public class JMandelbrot extends JComponent { + + private static final double EPSILON = 1E-16; + private static final int MIN_WIDTH = 50; + private static final int MIN_HEIGHT = 50; + private static final double ZOOM_RATE = 3; + private static final int NUM_OF_THREADS = 4; + + private Point2D center; + public static final String CENTER_PROPERTY_NAME = "center"; + + private int maxIteration = 300; + public static final String MAX_ITERATION_PROPERTY_NAME = "maxIteration"; + + private Palette palette; + public static final String PALETTE_PROPERTY_NAME = "palette"; + + private BufferedImage buffer; + private final MandelbrotCalculator[] calculators + = new MandelbrotCalculator[NUM_OF_THREADS]; + + private double xLowLimit = -2; + private double xHighLimit = 2; + private double yLowLimit = -2; + private double yHighLimit = 2; + private double xScale = 100; + private double yScale = 100; + private int oldComponentWidth = (int) (xScale * (xHighLimit - xLowLimit)); + private int oldComponentHeight = (int) (yScale * (yHighLimit - yLowLimit)); + + public JMandelbrot(int width, int height, Palette palette, + ResourceManager resourceManager) { + setPreferredSize(new Dimension(width, height)); + setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT)); + calcConstants(width, height); + setPalette(palette); + setToolTipText(resourceManager.getString("SpinnerDemo.toolTip")); + installListeners(); + } + + private void calcConstants() { + calcConstants(getWidth(), getHeight()); + } + + private void calcConstants(int width, int height) { + if ((width >= MIN_WIDTH) && (height >= MIN_HEIGHT)) { + double oldIntervalWidth = xHighLimit - xLowLimit; + double oldIntervalHeight = yHighLimit - yLowLimit; + double newIntervalWidth + = width * oldIntervalWidth / oldComponentWidth; + double newIntervalHeight + = height * oldIntervalHeight / oldComponentHeight; + double xDiff = newIntervalWidth - oldIntervalWidth; + double yDiff = newIntervalHeight - oldIntervalHeight; + xLowLimit -= xDiff / 2; + xHighLimit += xDiff / 2; + yLowLimit -= yDiff / 2; + yHighLimit += yDiff / 2; + buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + oldComponentWidth = width; + oldComponentHeight = height; + setCenter(calcCenter()); + } + } + + private void installListeners() { + addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + int xCoord = e.getX(); + int yCoord = e.getY(); + double intervalWidth = xHighLimit - xLowLimit; + double intervalHeight = yHighLimit - yLowLimit; + double x = intervalWidth * xCoord / getWidth() + xLowLimit; + double y = intervalHeight * yCoord / getHeight() + yLowLimit; + + double newIntervalWidth; + double newIntervalHeight; + if (e.getButton() == MouseEvent.BUTTON1) { + boolean limitReached = false; + newIntervalWidth = intervalWidth / ZOOM_RATE; + if ((newIntervalWidth / getWidth()) < EPSILON) { + newIntervalWidth = intervalWidth; + limitReached = true; + } + newIntervalHeight = intervalHeight / ZOOM_RATE; + if ((newIntervalHeight / getHeight()) < EPSILON) { + newIntervalHeight = intervalHeight; + limitReached = true; + } + if (!limitReached) { + xLowLimit = x - (x - xLowLimit) / ZOOM_RATE; + yLowLimit = y - (y - yLowLimit) / ZOOM_RATE; + } + } else { + newIntervalWidth = intervalWidth * ZOOM_RATE; + newIntervalHeight = intervalHeight * ZOOM_RATE; + xLowLimit = x - (x - xLowLimit) * ZOOM_RATE; + yLowLimit = y - (y - yLowLimit) * ZOOM_RATE; + } + + xHighLimit = xLowLimit + newIntervalWidth; + yHighLimit = yLowLimit + newIntervalHeight; + + setCenter(calcCenter()); + + xScale = getWidth() / newIntervalWidth; + yScale = getHeight() / newIntervalHeight; + + calculatePicture(); + } + }); + + addComponentListener(new ComponentListener() { + @Override + public void componentResized(ComponentEvent e) { + calcConstants(); + calculatePicture(); + repaint(); + } + + @Override + public void componentMoved(ComponentEvent e) { + } + + @Override + public void componentShown(ComponentEvent e) { + } + + @Override + public void componentHidden(ComponentEvent e) { + } + }); + } + + //Use SwingWorker to asynchronously calculate parts of the picture + public void calculatePicture() { + int yStep = getHeight() / NUM_OF_THREADS; + int yStart = 0; + for (int i = 0; i < calculators.length; i++) { + if ((calculators[i] != null) && !calculators[i].isDone()) { + calculators[i].cancel(true); + } + int yEnd = i == calculators.length - 1 ? getHeight() : yStart + yStep; + calculators[i] = new MandelbrotCalculator(yStart, yEnd); + calculators[i].execute(); + yStart = yEnd; + } + } + // + + private Point2D calcCenter() { + return new Point2D.Double(xLowLimit + (xHighLimit - xLowLimit) / 2, + yLowLimit + (yHighLimit - yLowLimit) / 2); + } + + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + g.drawImage(buffer, 0, 0, null); + } + + //Use SwingWorker to asynchronously calculate parts of the picture + private class MandelbrotCalculator extends SwingWorker { + + private final int yStart; + private final int yEnd; + + public MandelbrotCalculator(int yStart, int yEnd) { + this.yStart = yStart; + this.yEnd = yEnd; + } + + @Override + protected Object doInBackground() throws Exception { + int[] data = ((DataBufferInt) buffer.getRaster().getDataBuffer()).getData(); + + double xArr[] = new double[buffer.getWidth()]; + + for (int i = 0; i < xArr.length; i++) { + xArr[i] = i / xScale + xLowLimit; + } + + double yArr[] = new double[yEnd - yStart]; + + for (int i = 0; i < yArr.length; i++) { + yArr[i] = (yStart + i) / yScale + yLowLimit; + } + + int i = yStart * buffer.getWidth(); + + for (double y : yArr) { + for (double x : xArr) { + int value = calcValue(x, y); + + data[i] = value == maxIteration ? 0 : palette.getRgbColor(value); + + i++; + } + if (Thread.currentThread().isInterrupted()) { + return null; + } + publish(); + } + return null; + } + + private int calcValue(double x, double y) { + double x0 = x; + double y0 = y; + + for (int i = 0; i < maxIteration; i++) { + double x2 = x * x; + double y2 = y * y; + + if (x2 + y2 > 4) { + return i; + } + + y = 2 * x * y + y0; + x = x2 - y2 + x0; + } + + return maxIteration; + } + + @Override + protected void process(List chunks) { + repaint(); + } + } + // + + // Getters and Setters + public int getMaxIteration() { + return maxIteration; + } + + public void setMaxIteration(int maxIteration) { + int oldValue = this.maxIteration; + this.maxIteration = maxIteration; + firePropertyChange(MAX_ITERATION_PROPERTY_NAME, oldValue, maxIteration); + palette.setSize(maxIteration); + } + + public double getXHighLimit() { + return xHighLimit; + } + + public double getXLowLimit() { + return xLowLimit; + } + + public double getYLowLimit() { + return yLowLimit; + } + + public double getYHighLimit() { + return yHighLimit; + } + + public Point2D getCenter() { + return center; + } + + public void setCenter(Point2D coords) { + Point2D oldValue = this.center; + this.center = coords; + + double width = xHighLimit - xLowLimit; + double height = yHighLimit - yLowLimit; + + xLowLimit = coords.getX() - width / 2; + xHighLimit = xLowLimit + width; + yLowLimit = coords.getY() - height / 2; + yHighLimit = yLowLimit + height; + + firePropertyChange(CENTER_PROPERTY_NAME, oldValue, coords); + } + + public Palette getPalette() { + return palette; + } + + public void setPalette(Palette palette) { + Palette oldValue = this.palette; + palette.setSize(maxIteration); + this.palette = palette; + firePropertyChange(PALETTE_PROPERTY_NAME, oldValue, palette); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/JPaletteShower.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/JPaletteShower.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.spinner; + +import javax.swing.*; +import java.awt.*; + +/** + * @author Mikhail Lapshin + */ +public class JPaletteShower extends JComponent { + + private Palette palette; + + public JPaletteShower(Palette palette, int width, int height) { + setPreferredSize(new Dimension(width, height)); + setMinimumSize(new Dimension(width, height)); + this.palette = palette; + } + + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + int w = getSize().width; + int h = getSize().height; + int maxIndex = palette.getSize() - 1; + double rate = (double) maxIndex / w; + for (int x = 0; x < w; x++) { + g.setColor(palette.getColor((int) (x * rate))); + g.fillRect(x, 0, 1, h); + } + } + + public Palette getPalette() { + return palette; + } + + public void setPalette(Palette palette) { + this.palette = palette; + repaint(); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/JSpinnerPanel.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/JSpinnerPanel.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.spinner; + +import javax.swing.*; +import java.awt.*; + +/** + * Arranges labels and spinners into two vertical columns. Labels at the left, + * spinners at the right. + * + * @author Mikhail Lapshin + */ +//Helpful component for layout of labeled spinners +public class JSpinnerPanel extends JPanel { + + private final JPanel labelPanel; + private final JPanel spinnerPanel; + + public JSpinnerPanel() { + setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); + + labelPanel = new JPanel(); + labelPanel.setLayout(new GridLayout(0, 1)); + + spinnerPanel = new JPanel(); + spinnerPanel.setLayout(new GridLayout(0, 1)); + + add(labelPanel); + add(Box.createHorizontalStrut(5)); + add(spinnerPanel); + } + + public void addSpinner(String labelText, JSpinner spinner) { + JLabel label = new JLabel(labelText); + label.setHorizontalAlignment(SwingConstants.TRAILING); + labelPanel.add(label); + + JPanel flowPanel = new JPanel(); + flowPanel.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 1)); + flowPanel.add(spinner); + spinnerPanel.add(flowPanel); + } +} +// + diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/MandelbrotControl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/MandelbrotControl.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.spinner; + +import javax.swing.*; +import java.awt.*; +import java.awt.geom.Point2D; +import javax.swing.event.ChangeListener; +import javax.swing.event.ChangeEvent; +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeEvent; + +import com.sun.swingset3.demos.ResourceManager; + +/** + * @author Mikhail Lapshin + */ +public class MandelbrotControl extends JPanel { + + private final JMandelbrot mandelbrot; + private JSpinner iterSpinner; + private CoordSpinner xSpinner; + private CoordSpinner ySpinner; + private static final double COORD_SPINNER_STEP = 0.1d; // part of width or height + private final ResourceManager resourceManager; + + public MandelbrotControl(JMandelbrot mandelbrot, + ResourceManager resourceManager) { + this.mandelbrot = mandelbrot; + this.resourceManager = resourceManager; + createUI(); + installListeners(); + } + + private void createUI() { + setLayout(new FlowLayout(FlowLayout.LEADING, 5, 0)); + setBorder(BorderFactory.createTitledBorder( + resourceManager.getString("SpinnerDemo.fractalControls"))); + JSpinnerPanel spinnerPanel = new JSpinnerPanel(); + + //Create spinner + iterSpinner = new JSpinner(new SpinnerNumberModel( + mandelbrot.getMaxIteration(), 10, 100000, 50)); + // + //Add change listener using anonymus inner class + iterSpinner.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + mandelbrot.setMaxIteration((Integer) iterSpinner.getValue()); + mandelbrot.calculatePicture(); + } + }); + // + spinnerPanel.addSpinner( + resourceManager.getString("SpinnerDemo.iterations"), iterSpinner); + + //Create spinner + final double xValue = mandelbrot.getCenter().getX(); + double width = mandelbrot.getXHighLimit() - mandelbrot.getXLowLimit(); + xSpinner = new CoordSpinner(xValue, width * COORD_SPINNER_STEP); + // + //Add change listener using anonymus inner class + xSpinner.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + Double newX = (Double) xSpinner.getValue(); + mandelbrot.setCenter(new Point2D.Double( + newX, mandelbrot.getCenter().getY())); + mandelbrot.calculatePicture(); + } + }); + // + spinnerPanel.addSpinner( + resourceManager.getString("SpinnerDemo.x"), xSpinner); + + //Create spinner + final double yValue = mandelbrot.getCenter().getY(); + double height = mandelbrot.getYHighLimit() - mandelbrot.getYLowLimit(); + ySpinner = new CoordSpinner(yValue, height * COORD_SPINNER_STEP); + // + //Add change listener using anonymus inner class + ySpinner.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + Double newY = (Double) ySpinner.getValue(); + mandelbrot.setCenter(new Point2D.Double( + mandelbrot.getCenter().getX(), newY)); + mandelbrot.calculatePicture(); + } + }); + // + spinnerPanel.addSpinner( + resourceManager.getString("SpinnerDemo.y"), ySpinner); + + add(spinnerPanel); + } + + private void installListeners() { + mandelbrot.addPropertyChangeListener( + JMandelbrot.CENTER_PROPERTY_NAME, + new PropertyChangeListener() { + @Override + public void propertyChange(PropertyChangeEvent evt) { + double width = mandelbrot.getXHighLimit() + - mandelbrot.getXLowLimit(); + double newX = mandelbrot.getCenter().getX(); + xSpinner.updateModel(newX, width * COORD_SPINNER_STEP); + double height = mandelbrot.getYHighLimit() + - mandelbrot.getYLowLimit(); + double newY = mandelbrot.getCenter().getY(); + ySpinner.updateModel(newY, height * COORD_SPINNER_STEP); + } + } + ); + } + + //Customized spinner class + // It uses special format for NumberEditor and has constant preferred width + private static class CoordSpinner extends JSpinner { + + @Override + protected JComponent createEditor(SpinnerModel model) { + return new NumberEditor(this, "#.####################"); + } + + public CoordSpinner(double value, double stepSize) { + super(new SpinnerNumberModel(value, -100, 100, stepSize)); + } + + //A useful shortcut method + public void updateModel(double value, double stepSize) { + SpinnerNumberModel model = (SpinnerNumberModel) getModel(); + model.setValue(value); + model.setStepSize(stepSize); + } + + @Override + public Dimension getPreferredSize() { + Dimension prefSize = super.getPreferredSize(); + prefSize.setSize(180, prefSize.getHeight()); + return prefSize; + } + } + // +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/Palette.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/Palette.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.spinner; + +/** + * @author Mikhail Lapshin + */ +import java.awt.*; + +public class Palette { + + private final int minColor; + private final int colorRange; + private Color[] colors; + private int[] rgbColors; + private final int rSteps; + private final int gSteps; + private final int bSteps; + private int totalRange; + private int rRange; + private int gRange; + private int bRange; + private final double rStart; + private final double gStart; + private final double bStart; + + public Palette(int totalRange, int minColor, int maxColor, double rStart, + double gStart, double bStart, int rSteps, int gSteps, int bSteps) { + this.minColor = minColor; + this.colorRange = maxColor - minColor; + this.rStart = rStart; + this.gStart = gStart; + this.bStart = bStart; + this.rSteps = rSteps; + this.gSteps = gSteps; + this.bSteps = bSteps; + setSize(totalRange); + } + + public void setSize(int newSize) { + totalRange = newSize; + rRange = totalRange / rSteps; + gRange = totalRange / gSteps; + bRange = totalRange / bSteps; + fillColorTable(); + } + + private void fillColorTable() { + colors = new Color[totalRange]; + rgbColors = new int[totalRange]; + for (int i = 0; i < totalRange; i++) { + double cosR = Math.cos(i * 2 * Math.PI / rRange + rStart); + double cosG = Math.cos(i * 2 * Math.PI / gRange + gStart); + double cosB = Math.cos(i * 2 * Math.PI / bRange + bStart); + Color color = new Color( + (int) ((cosR * colorRange) + colorRange) / 2 + minColor, + (int) ((cosG * colorRange) + colorRange) / 2 + minColor, + (int) ((cosB * colorRange) + colorRange) / 2 + minColor); + colors[i] = color; + rgbColors[i] = color.getRGB(); + } + } + + public Color getColor(int index) { + return colors[index]; + } + + public int getRgbColor(int index) { + return rgbColors[index]; + } + + public int getSize() { + return totalRange; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/PaletteChooser.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/PaletteChooser.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.spinner; + +import javax.swing.*; +import java.awt.*; +import javax.swing.event.ChangeListener; +import javax.swing.event.ChangeEvent; + +import com.sun.swingset3.demos.ResourceManager; + +/** + * @author Mikhail Lapshin + */ +public class PaletteChooser extends JPanel { + + private static final int MIN_COLOR = 50; + private static final int MAX_COLOR = 255; + private static final int R_STEPS = 5; + private static final int G_STEPS = 5; + private static final int B_STEPS = 5; + private static final int R_ANGLE = 270; + private static final int G_ANGLE = 90; + private static final int B_ANGLE = 0; + + public static final String PALETTE_PROPERTY_NAME = "palette"; + + private final ResourceManager resourceManager; + private Palette palette; + private final JPaletteShower shower; + private final ChangeListener changeListener; + + private JSpinner rsSpinner; + private JSpinner gsSpinner; + private JSpinner bsSpinner; + private JSpinner raSpinner; + private JSpinner gaSpinner; + private JSpinner baSpinner; + + public PaletteChooser(ResourceManager resourceManager) { + this.resourceManager = resourceManager; + palette = new Palette(MAX_COLOR - MIN_COLOR, MIN_COLOR, MAX_COLOR, + Math.toRadians(R_ANGLE), Math.toRadians(G_ANGLE), + Math.toRadians(B_ANGLE), R_STEPS, G_STEPS, B_STEPS); + shower = new JPaletteShower(palette, 250, 25); + + //Use single change listener for several spinners + changeListener = new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + setPalette(createPalette()); + shower.setPalette(palette); + repaint(); + } + }; + // + + setBorder(BorderFactory.createTitledBorder( + resourceManager.getString("SpinnerDemo.colorPalette"))); + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + add(shower); + add(createControlPanel()); + } + + private double toRadians(JSpinner spinner) { + return Math.toRadians(getIntValue(spinner)); + } + + private Palette createPalette() { + return new Palette(getWidth(), MIN_COLOR, MAX_COLOR, + toRadians(raSpinner), toRadians(gaSpinner), + toRadians(baSpinner), getIntValue(rsSpinner), + getIntValue(gsSpinner), getIntValue(bsSpinner)); + } + + private static int getIntValue(JSpinner spinner) { + return (Integer) spinner.getValue(); + } + + private JPanel createControlPanel() { + JPanel controlPanel = new JPanel(); + controlPanel.setLayout(new GridLayout(1, 2)); + controlPanel.add(createStepPanel()); + controlPanel.add(createStartAnglePanel()); + return controlPanel; + } + + private JPanel createStartAnglePanel() { + JSpinnerPanel startAnglePanel = new JSpinnerPanel(); + startAnglePanel.setBorder(BorderFactory.createTitledBorder( + resourceManager.getString("SpinnerDemo.startAngles"))); + + raSpinner = createAngleSpinner(R_ANGLE, "SpinnerDemo.r", startAnglePanel); + gaSpinner = createAngleSpinner(G_ANGLE, "SpinnerDemo.g", startAnglePanel); + baSpinner = createAngleSpinner(B_ANGLE, "SpinnerDemo.b", startAnglePanel); + + return startAnglePanel; + } + + private JPanel createStepPanel() { + JSpinnerPanel stepPanel = new JSpinnerPanel(); + stepPanel.setBorder(BorderFactory.createTitledBorder( + resourceManager.getString("SpinnerDemo.steps"))); + + rsSpinner = createStepSpinner(R_STEPS, "SpinnerDemo.r", stepPanel); + gsSpinner = createStepSpinner(G_STEPS, "SpinnerDemo.g", stepPanel); + bsSpinner = createStepSpinner(B_STEPS, "SpinnerDemo.b", stepPanel); + + return stepPanel; + } + + private JSpinner createAngleSpinner(int startAngle, String resourceName, + JSpinnerPanel parent) { + SpinnerModel model = new SpinnerNumberModel(startAngle, 0, 360, 10); + return createSpinner(model, resourceName, parent); + } + + private JSpinner createStepSpinner(int startSteps, String resourceName, + JSpinnerPanel parent) { + SpinnerModel model = new SpinnerNumberModel(startSteps, 1, 1000, 1); + return createSpinner(model, resourceName, parent); + } + + private JSpinner createSpinner(SpinnerModel model, String resourceName, + JSpinnerPanel parent) { + + //Create spinner + JSpinner spinner = new JSpinner(model); + // + //Use single change listener for several spinners + spinner.addChangeListener(changeListener); + // + parent.addSpinner(resourceManager.getString(resourceName), spinner); + return spinner; + } + + public Palette getPalette() { + return palette; + } + + private void setPalette(Palette palette) { + Palette oldValue = this.palette; + this.palette = palette; + firePropertyChange(PALETTE_PROPERTY_NAME, oldValue, palette); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/SpinnerDemo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/SpinnerDemo.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.spinner; + +import javax.swing.*; +import java.awt.*; +import java.beans.PropertyChangeEvent; + +import com.sun.swingset3.DemoProperties; +import com.sun.swingset3.demos.ResourceManager; + +/** + * Demonstrates JSpinner and SwingWorker + * + * @author Mikhail Lapshin + */ +@DemoProperties( + value = "Spinner Demo", + category = "Controls", + description = "Demonstrates JSpinner and SwingWorker", + sourceFiles = { + "com/sun/swingset3/demos/spinner/SpinnerDemo.java", + "com/sun/swingset3/demos/spinner/JMandelbrot.java", + "com/sun/swingset3/demos/spinner/JPaletteShower.java", + "com/sun/swingset3/demos/spinner/JSpinnerPanel.java", + "com/sun/swingset3/demos/spinner/MandelbrotControl.java", + "com/sun/swingset3/demos/spinner/Palette.java", + "com/sun/swingset3/demos/spinner/PaletteChooser.java", + "com/sun/swingset3/demos/ResourceManager.java", + "com/sun/swingset3/demos/spinner/resources/SpinnerDemo.properties", + "com/sun/swingset3/demos/spinner/resources/images/SpinnerDemo.gif" + } +) +public class SpinnerDemo extends JPanel { + + private final ResourceManager resourceManager = new ResourceManager(getClass()); + public static final String DEMO_TITLE = SpinnerDemo.class.getAnnotation(DemoProperties.class).value(); + + public static void main(String[] args) { + JFrame frame = new JFrame(DEMO_TITLE); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(new SpinnerDemo()); + frame.setPreferredSize(new Dimension(800, 600)); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + public SpinnerDemo() { + setLayout(new BorderLayout()); + + // Create main components + PaletteChooser chooser + = new PaletteChooser(resourceManager); + final JMandelbrot mandelbrot + = new JMandelbrot(400, 400, chooser.getPalette(), resourceManager); + MandelbrotControl mandelbrotControl + = new MandelbrotControl(mandelbrot, resourceManager); + + // Connect palette chooser and mandelbrot component + chooser.addPropertyChangeListener(PaletteChooser.PALETTE_PROPERTY_NAME, + (PropertyChangeEvent evt) -> { + mandelbrot.setPalette((Palette) evt.getNewValue()); + mandelbrot.calculatePicture(); + }); + + // Layout components + add(mandelbrot); + + JPanel controlPanel = new JPanel(); + controlPanel.setLayout(new BorderLayout()); + controlPanel.add(chooser, BorderLayout.NORTH); + + JPanel mandelbrotControlPanel = new JPanel(); + mandelbrotControlPanel.setLayout(new BorderLayout()); + mandelbrotControlPanel.add(mandelbrotControl, BorderLayout.NORTH); + controlPanel.add(mandelbrotControlPanel, BorderLayout.CENTER); + + add(controlPanel, BorderLayout.EAST); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/resources/SpinnerDemo.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/resources/SpinnerDemo.properties Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,15 @@ +### Spinner Demo ### + +SpinnerDemo.toolTip=Use left and right mouse buttons to zoom in and zoom out +SpinnerDemo.colorPalette=Color palette +SpinnerDemo.steps=Steps 1..1000 +SpinnerDemo.startAngles=Start angle 0..360 +SpinnerDemo.iterations=Iterations +SpinnerDemo.fractalControls=Fractal controls +SpinnerDemo.zoomRate=Zoom rate +SpinnerDemo.threads=Threads +SpinnerDemo.x=X +SpinnerDemo.y=Y +SpinnerDemo.r=R +SpinnerDemo.g=G +SpinnerDemo.b=B diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/resources/images/SpinnerDemo.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/spinner/resources/images/SpinnerDemo.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/splitpane/SplitPaneDemo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/splitpane/SplitPaneDemo.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,292 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.splitpane; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.*; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import com.sun.swingset3.DemoProperties; +import com.sun.swingset3.demos.ResourceManager; + +/** + * Split Pane demo + * + * @version 1.12 11/17/05 + * @author Scott Violet + * @author Jeff Dinkins + */ +@DemoProperties( + value = "JSplitPane Demo", + category = "Containers", + description = "Demonstrates JSplitPane, a container which lays out two components in an adjustable split view (horizontal or vertical)", + sourceFiles = { + "com/sun/swingset3/demos/splitpane/SplitPaneDemo.java", + "com/sun/swingset3/demos/ResourceManager.java", + "com/sun/swingset3/demos/splitpane/resources/SplitPaneDemo.properties", + "com/sun/swingset3/demos/splitpane/resources/images/day.jpg", + "com/sun/swingset3/demos/splitpane/resources/images/night.jpg", + "com/sun/swingset3/demos/splitpane/resources/images/SplitPaneDemo.gif" + } +) +public class SplitPaneDemo extends JPanel { + + private static final ResourceManager resourceManager = new ResourceManager(SplitPaneDemo.class); + public static final String VERTICAL_SPLIT = resourceManager.getString("SplitPaneDemo.vert_split"); + public static final String HORIZONTAL_SPLIT = resourceManager.getString("SplitPaneDemo.horz_split"); + public static final String ONE_TOUCH_EXPANDABLE = resourceManager.getString("SplitPaneDemo.one_touch_expandable"); + public static final String SECOND_COMPONENT_MIN_SIZE = resourceManager.getString("SplitPaneDemo.second_component_min_size"); + public static final String FIRST_COMPONENT_MIN_SIZE = resourceManager.getString("SplitPaneDemo.first_component_min_size"); + public static final String DIVIDER_SIZE = resourceManager.getString("SplitPaneDemo.divider_size"); + public static final String DEMO_TITLE = SplitPaneDemo.class.getAnnotation(DemoProperties.class).value(); + + private static final Insets insets = new Insets(4, 8, 4, 8); + + private final JSplitPane splitPane; + private final JLabel day; + private final JLabel night; + + private JPanel controlPanel; + private GridBagLayout gridbag; + private GridBagConstraints c; + + /** + * main method allows us to run as a standalone demo. + * + * @param args + */ + public static void main(String[] args) { + JFrame frame = new JFrame(DEMO_TITLE); + + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(new SplitPaneDemo()); + frame.setPreferredSize(new Dimension(800, 600)); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + /** + * SplitPaneDemo Constructor + */ + public SplitPaneDemo() { + setLayout(new BorderLayout()); + + //Create horizontal SplitPane with day and night + day = new JLabel(resourceManager.createImageIcon("day.jpg", + resourceManager.getString("SplitPaneDemo.day"))); + night = new JLabel(resourceManager.createImageIcon("night.jpg", + resourceManager.getString("SplitPaneDemo.night"))); + + splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, day, night); + // + + //Turn on continuous layout + splitPane.setContinuousLayout(true); + // + + //Turn on one-touch expansion + splitPane.setOneTouchExpandable(true); + // + + //Set divider location + splitPane.setDividerLocation(200); + // + + //Set minimum size for each child + day.setMinimumSize(new Dimension(20, 20)); + night.setMinimumSize(new Dimension(20, 20)); + // + + add(splitPane, BorderLayout.CENTER); + setBackground(Color.black); + + add(createSplitPaneControls(), BorderLayout.SOUTH); + } + + /** + * Creates controls to alter the JSplitPane. + * + * @return + */ + protected final JPanel createSplitPaneControls() { + + gridbag = new GridBagLayout(); + c = new GridBagConstraints(); + controlPanel = new JPanel(gridbag); + + //Create radio box to edit splitpane orientation + Box box = Box.createHorizontalBox(); + ButtonGroup group = new ButtonGroup(); + + OrientationListener orientationListener = new OrientationListener(); + + JRadioButton button = new JRadioButton(VERTICAL_SPLIT); + button.setActionCommand("vertical"); + button.addActionListener(orientationListener); + group.add(button); + box.add(button); + + button = new JRadioButton(HORIZONTAL_SPLIT); + button.setActionCommand("horizontal"); + button.setSelected(true); + button.addActionListener(orientationListener); + group.add(button); + box.add(button); + // + + addToGridbag(box, 0, 0, 1, 1, + GridBagConstraints.NONE, GridBagConstraints.WEST); + + //Create checkbox to edit continuous layout + JCheckBox checkBox = new JCheckBox(resourceManager.getString("SplitPaneDemo.cont_layout")); + checkBox.setSelected(true); + + checkBox.addChangeListener((ChangeEvent e) -> { + splitPane.setContinuousLayout( + ((JCheckBox) e.getSource()).isSelected()); + }); + // + + c.gridy++; + addToGridbag(checkBox, 0, 1, 1, 1, + GridBagConstraints.NONE, GridBagConstraints.WEST); + + //Create checkbox to edit one-touch-expandable + checkBox = new JCheckBox(ONE_TOUCH_EXPANDABLE); + checkBox.setSelected(true); + + checkBox.addChangeListener((ChangeEvent e) -> { + splitPane.setOneTouchExpandable( + ((JCheckBox) e.getSource()).isSelected()); + }); + // + + addToGridbag(checkBox, 0, 2, 1, 1, + GridBagConstraints.NONE, GridBagConstraints.WEST); + + JSeparator separator = new JSeparator(JSeparator.VERTICAL); + addToGridbag(separator, 1, 0, 1, 3, + GridBagConstraints.VERTICAL, GridBagConstraints.CENTER); + + //Create spinner to edit divider size + final JSpinner spinner = new JSpinner( + new SpinnerNumberModel(splitPane.getDividerSize(), 5, 50, 2)); + + spinner.addChangeListener((ChangeEvent event) -> { + SpinnerNumberModel model = (SpinnerNumberModel) spinner.getModel(); + splitPane.setDividerSize(model.getNumber().intValue()); + }); + // + + JLabel label = new JLabel(DIVIDER_SIZE); + label.setLabelFor(spinner); + addToGridbag(label, 2, 0, 1, 1, + GridBagConstraints.NONE, GridBagConstraints.EAST); + addToGridbag(spinner, 3, 0, 1, 1, + GridBagConstraints.NONE, GridBagConstraints.WEST); + + //Create spinners to edit day & night's minimum sizes + JSpinner minSizeSpinner = new JSpinner( + new SpinnerNumberModel(day.getMinimumSize().width, 0, 300, 10)); + + minSizeSpinner.addChangeListener(new MinimumSizeListener(day)); + // + + label = new JLabel(FIRST_COMPONENT_MIN_SIZE); + label.setLabelFor(minSizeSpinner); + addToGridbag(label, 2, 1, 1, 1, + GridBagConstraints.NONE, GridBagConstraints.EAST); + addToGridbag(minSizeSpinner, 3, 1, 1, 1, + GridBagConstraints.NONE, GridBagConstraints.WEST); + + //Create spinners to edit day & night's minimum sizes + minSizeSpinner = new JSpinner( + new SpinnerNumberModel(night.getMinimumSize().width, 0, 300, 10)); + + minSizeSpinner.addChangeListener(new MinimumSizeListener(night)); + // + + label = new JLabel(SECOND_COMPONENT_MIN_SIZE); + label.setLabelFor(minSizeSpinner); + addToGridbag(label, 2, 2, 1, 1, + GridBagConstraints.NONE, GridBagConstraints.EAST); + addToGridbag(minSizeSpinner, 3, 2, 1, 1, + GridBagConstraints.NONE, GridBagConstraints.WEST); + + return controlPanel; + } + + protected void addToGridbag(JComponent child, int gx, int gy, + int gwidth, int gheight, int fill, int anchor) { + c.insets = insets; + c.gridx = gx; + c.gridy = gy; + c.gridwidth = gwidth; + c.gridheight = gheight; + c.fill = fill; + c.anchor = anchor; + gridbag.addLayoutComponent(child, c); + controlPanel.add(child); + + } + + //Create radio box to edit splitpane orientation + private class OrientationListener implements ActionListener { + + @Override + public void actionPerformed(ActionEvent event) { + splitPane.setOrientation(event.getActionCommand().equals("vertical") + ? JSplitPane.VERTICAL_SPLIT : JSplitPane.HORIZONTAL_SPLIT); + } + + } + // + + //Create spinners to edit day & night's minimum sizes + public class MinimumSizeListener implements ChangeListener { + + private final JComponent component; + + public MinimumSizeListener(JComponent c) { + this.component = c; + } + + @Override + public void stateChanged(ChangeEvent event) { + JSpinner spinner = (JSpinner) event.getSource(); + SpinnerNumberModel model = (SpinnerNumberModel) spinner.getModel(); + int min = model.getNumber().intValue(); + component.setMinimumSize(new Dimension(min, min)); + } + } + // +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/splitpane/resources/SplitPaneDemo.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/splitpane/resources/SplitPaneDemo.properties Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,14 @@ +### SplitPane Demo ### + +SplitPaneDemo.accessible_description=JSplitPane Demo +SplitPaneDemo.name=Split Pane Demo +SplitPaneDemo.tooltip=JSplitPane demo +SplitPaneDemo.day=San Francisco by day +SplitPaneDemo.night=San Francisco by night +SplitPaneDemo.vert_split=Vertical Split +SplitPaneDemo.horz_split=Horizontal Split +SplitPaneDemo.cont_layout=Continuous Layout +SplitPaneDemo.one_touch_expandable=One-Touch expandable +SplitPaneDemo.divider_size=Divider Size +SplitPaneDemo.first_component_min_size=Day's Minimum Size +SplitPaneDemo.second_component_min_size=Night's Minimum Size diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/splitpane/resources/images/SplitPaneDemo.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/splitpane/resources/images/SplitPaneDemo.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/splitpane/resources/images/day.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/splitpane/resources/images/day.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/splitpane/resources/images/night.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/splitpane/resources/images/night.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/TabbedPaneDemo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/TabbedPaneDemo.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,257 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.tabbedpane; + +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Random; +import javax.swing.*; +import javax.swing.event.ChangeEvent; + +import com.sun.swingset3.DemoProperties; +import com.sun.swingset3.demos.ResourceManager; + +/** + * JTabbedPane Demo + * + * @version 1.11 11/17/05 + * @author Jeff Dinkins + */ +@DemoProperties( + value = "JTabbedPane Demo", + category = "Containers", + description = "Demonstrates JTabbedPane, a container which allows tabbed navigation of components", + sourceFiles = { + "com/sun/swingset3/demos/tabbedpane/TabbedPaneDemo.java", + "com/sun/swingset3/demos/ResourceManager.java", + "com/sun/swingset3/demos/tabbedpane/resources/TabbedPaneDemo.properties", + "com/sun/swingset3/demos/tabbedpane/resources/images/blake.gif", + "com/sun/swingset3/demos/tabbedpane/resources/images/brooke.gif", + "com/sun/swingset3/demos/tabbedpane/resources/images/camille.jpg", + "com/sun/swingset3/demos/tabbedpane/resources/images/david.gif", + "com/sun/swingset3/demos/tabbedpane/resources/images/ewan.gif", + "com/sun/swingset3/demos/tabbedpane/resources/images/ewan.jpg", + "com/sun/swingset3/demos/tabbedpane/resources/images/miranda.jpg", + "com/sun/swingset3/demos/tabbedpane/resources/images/matthew.gif", + "com/sun/swingset3/demos/tabbedpane/resources/images/stephen.gif", + "com/sun/swingset3/demos/tabbedpane/resources/images/TabbedPaneDemo.gif" + } +) +public class TabbedPaneDemo extends JPanel implements ActionListener { + + private static final ResourceManager resourceManager = new ResourceManager(TabbedPaneDemo.class); + public static final String BOUNCE = resourceManager.getString("TabbedPaneDemo.bounce"); + public static final String EWAN = resourceManager.getString("TabbedPaneDemo.ewan"); + public static final String MIRANDA = resourceManager.getString("TabbedPaneDemo.miranda"); + public static final String CAMILLE = resourceManager.getString("TabbedPaneDemo.camille"); + public static final String TAB_PLACEMENT = resourceManager.getString("TabbedPaneDemo.label"); + public static final String RIGHT = resourceManager.getString("TabbedPaneDemo.right"); + public static final String BOTTOM = resourceManager.getString("TabbedPaneDemo.bottom"); + public static final String LEFT = resourceManager.getString("TabbedPaneDemo.left"); + public static final String TOP = resourceManager.getString("TabbedPaneDemo.top"); + public static final String DEMO_TITLE = TabbedPaneDemo.class.getAnnotation(DemoProperties.class).value(); + + private final HeadSpin spin; + + private final JTabbedPane tabbedpane; + + private final ButtonGroup group; + + private final JRadioButton top; + private final JRadioButton bottom; + private final JRadioButton left; + private final JRadioButton right; + + /** + * main method allows us to run as a standalone demo. + * + * @param args + */ + public static void main(String[] args) { + JFrame frame = new JFrame(DEMO_TITLE); + + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(new TabbedPaneDemo()); + frame.setPreferredSize(new Dimension(800, 600)); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + /** + * TabbedPaneDemo Constructor + */ + public TabbedPaneDemo() { + setLayout(new BorderLayout()); + + // create tab position controls + JPanel tabControls = new JPanel(); + tabControls.add(new JLabel(TAB_PLACEMENT)); + top = (JRadioButton) tabControls.add(new JRadioButton(TOP)); + left = (JRadioButton) tabControls.add(new JRadioButton(LEFT)); + bottom = (JRadioButton) tabControls.add(new JRadioButton(BOTTOM)); + right = (JRadioButton) tabControls.add(new JRadioButton(RIGHT)); + add(tabControls, BorderLayout.NORTH); + + group = new ButtonGroup(); + group.add(top); + group.add(bottom); + group.add(left); + group.add(right); + + top.setSelected(true); + + top.addActionListener(this); + bottom.addActionListener(this); + left.addActionListener(this); + right.addActionListener(this); + + // create tab + tabbedpane = new JTabbedPane(); + add(tabbedpane, BorderLayout.CENTER); + + String name = CAMILLE; + JLabel pix = new JLabel(resourceManager.createImageIcon("camille.jpg", name)); + tabbedpane.add(name, pix); + + name = MIRANDA; + pix = new JLabel(resourceManager.createImageIcon("miranda.jpg", name)); + pix.setToolTipText(resourceManager.getString("TabbedPaneDemo.miranda.tooltip")); + tabbedpane.add(name, pix); + + name = EWAN; + pix = new JLabel(resourceManager.createImageIcon("ewan.jpg", name)); + tabbedpane.add(name, pix); + + name = BOUNCE; + spin = new HeadSpin(); + tabbedpane.add(name, spin); + + tabbedpane.getModel().addChangeListener((ChangeEvent e) -> { + SingleSelectionModel model = (SingleSelectionModel) e.getSource(); + if (model.getSelectedIndex() == tabbedpane.getTabCount() - 1) { + spin.go(); + } + }); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == top) { + tabbedpane.setTabPlacement(JTabbedPane.TOP); + } else if (e.getSource() == left) { + tabbedpane.setTabPlacement(JTabbedPane.LEFT); + } else if (e.getSource() == bottom) { + tabbedpane.setTabPlacement(JTabbedPane.BOTTOM); + } else if (e.getSource() == right) { + tabbedpane.setTabPlacement(JTabbedPane.RIGHT); + } + } + + private class HeadSpin extends JComponent implements ActionListener { + + private javax.swing.Timer animator; + + private final ImageIcon[] icon = new ImageIcon[6]; + + private final static int numImages = 6; + + private final double[] x = new double[numImages]; + private final double[] y = new double[numImages]; + + private final int[] xh = new int[numImages]; + private final int[] yh = new int[numImages]; + + private final double[] scale = new double[numImages]; + + private final Random rand = new Random(); + + public HeadSpin() { + setBackground(Color.black); + icon[0] = resourceManager.createImageIcon("ewan.gif", resourceManager.getString("TabbedPaneDemo.ewan")); + icon[1] = resourceManager.createImageIcon("stephen.gif", resourceManager.getString("TabbedPaneDemo.stephen")); + icon[2] = resourceManager.createImageIcon("david.gif", resourceManager.getString("TabbedPaneDemo.david")); + icon[3] = resourceManager.createImageIcon("matthew.gif", resourceManager.getString("TabbedPaneDemo.matthew")); + icon[4] = resourceManager.createImageIcon("blake.gif", resourceManager.getString("TabbedPaneDemo.blake")); + icon[5] = resourceManager.createImageIcon("brooke.gif", resourceManager.getString("TabbedPaneDemo.brooke")); + + /* + for(int i = 0; i < 6; i++) { + x[i] = (double) rand.nextInt(500); + y[i] = (double) rand.nextInt(500); + } + */ + } + + public void go() { + animator = new javax.swing.Timer(22 + 22 + 22, this); + animator.start(); + } + + @Override + public void paint(Graphics g) { + g.setColor(getBackground()); + g.fillRect(0, 0, getWidth(), getHeight()); + + for (int i = 0; i < numImages; i++) { + if (x[i] > 3 * i) { + nudge(i); + squish(g, icon[i], xh[i], yh[i], scale[i]); + } else { + x[i] += .05; + y[i] += .05; + } + } + } + + public void nudge(int i) { + x[i] += (double) rand.nextInt(1000) / 8756; + y[i] += (double) rand.nextInt(1000) / 5432; + int tmpScale = (int) (Math.abs(Math.sin(x[i])) * 10); + scale[i] = (double) tmpScale / 10; + int nudgeX = (int) (((double) getWidth() / 2) * .8); + int nudgeY = (int) (((double) getHeight() / 2) * .60); + xh[i] = (int) (Math.sin(x[i]) * nudgeX) + nudgeX; + yh[i] = (int) (Math.sin(y[i]) * nudgeY) + nudgeY; + } + + public void squish(Graphics g, ImageIcon icon, int x, int y, double scale) { + if (isVisible()) { + g.drawImage(icon.getImage(), x, y, + (int) (icon.getIconWidth() * scale), + (int) (icon.getIconHeight() * scale), + this); + } + } + + @Override + public void actionPerformed(ActionEvent e) { + if (isVisible()) { + repaint(); + } else { + animator.stop(); + } + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/TabbedPaneDemo.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/TabbedPaneDemo.properties Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,22 @@ +### TabbedPane Demo ### + +TabbedPaneDemo.accessible_description=This demo shows an example of using the JTabbedPane component. +TabbedPaneDemo.tooltip=JTabbedPane demo +TabbedPaneDemo.name=TabbedPane Demo + +TabbedPaneDemo.bounce=
Bouncing Babies!
+TabbedPaneDemo.stephen=Stephen +TabbedPaneDemo.david=David +TabbedPaneDemo.matthew=Matthew +TabbedPaneDemo.ewan=Ewan +TabbedPaneDemo.blake=Blake +TabbedPaneDemo.brooke=Brooke +TabbedPaneDemo.camille=Camille +TabbedPaneDemo.miranda=Miranda +TabbedPaneDemo.miranda.tooltip=Check out the Java code on her onesie! + +TabbedPaneDemo.label=Tab Placement: +TabbedPaneDemo.top=Top +TabbedPaneDemo.bottom=Bottom +TabbedPaneDemo.left=Left +TabbedPaneDemo.right=Right \ No newline at end of file diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/TabbedPaneDemo.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/TabbedPaneDemo.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/blake.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/blake.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/brooke.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/brooke.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/camille.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/camille.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/david.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/david.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/ewan.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/ewan.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/ewan.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/ewan.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/matthew.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/matthew.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/miranda.jpg Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/miranda.jpg has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/stephen.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tabbedpane/resources/images/stephen.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/textfield/JHistoryTextField.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/textfield/JHistoryTextField.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,265 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.textfield; + +import java.awt.*; +import java.awt.event.*; +import java.util.*; +import java.util.List; +import javax.swing.*; +import javax.swing.border.LineBorder; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; + +/** + * JHistoryTextField + * + * @author Pavel Porvatov + */ +public class JHistoryTextField extends JTextField { + + private static final int MAX_VISIBLE_ROWS = 8; + + private final List history = new ArrayList(); + + private final JPopupMenu popup = new JPopupMenu() { + @Override + public Dimension getPreferredSize() { + Dimension dimension = super.getPreferredSize(); + + dimension.width = JHistoryTextField.this.getWidth(); + + return dimension; + } + }; + + private final JList list = new JList<>(new DefaultListModel<>()); + + private String userText; + + private boolean notificationDenied; + + public JHistoryTextField() { + JScrollPane scrollPane = new JScrollPane(list, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + scrollPane.setHorizontalScrollBar(null); + scrollPane.setBorder(null); + + list.setFocusable(false); + + popup.add(scrollPane); + popup.setFocusable(false); + popup.setBorder(new LineBorder(Color.BLACK, 1)); + + getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent e) { + onTextChanged(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + onTextChanged(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + onTextChanged(); + } + }); + + list.addMouseMotionListener(new MouseAdapter() { + @Override + public void mouseMoved(MouseEvent e) { + int index = list.locationToIndex(e.getPoint()); + + if (index >= 0 && list.getSelectedIndex() != index) { + list.setSelectedIndex(index); + } + } + }); + + list.addMouseListener(new MouseAdapter() { + @Override + public void mouseReleased(MouseEvent e) { + if (SwingUtilities.isLeftMouseButton(e)) { + setTextWithoutNotification(list.getSelectedValue()); + + popup.setVisible(false); + } + } + }); + + addFocusListener(new FocusAdapter() { + @Override + public void focusLost(FocusEvent e) { + popup.setVisible(false); + } + }); + + addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (popup.isShowing()) { + switch (e.getKeyCode()) { + case KeyEvent.VK_UP: { + changeListSelectedIndex(-1); + + break; + } + + case KeyEvent.VK_PAGE_UP: { + changeListSelectedIndex(-list.getVisibleRowCount()); + + break; + } + + case KeyEvent.VK_DOWN: { + changeListSelectedIndex(1); + + break; + } + + case KeyEvent.VK_PAGE_DOWN: { + changeListSelectedIndex(list.getVisibleRowCount()); + + break; + } + + case KeyEvent.VK_ESCAPE: { + popup.setVisible(false); + + setTextWithoutNotification(userText); + + break; + } + + case KeyEvent.VK_ENTER: + case KeyEvent.VK_LEFT: + case KeyEvent.VK_RIGHT: { + popup.setVisible(false); + + break; + } + } + } else if (e.getKeyCode() == KeyEvent.VK_DOWN + || e.getKeyCode() == KeyEvent.VK_UP + || e.getKeyCode() == KeyEvent.VK_PAGE_UP + || e.getKeyCode() == KeyEvent.VK_PAGE_DOWN) { + userText = getText(); + + showFilteredHistory(); + } + } + }); + } + + private void changeListSelectedIndex(int delta) { + int size = list.getModel().getSize(); + int index = list.getSelectedIndex(); + + int newIndex; + + if (index < 0) { + newIndex = delta > 0 ? 0 : size - 1; + } else { + newIndex = index + delta; + } + + if (newIndex >= size || newIndex < 0) { + newIndex = newIndex < 0 ? 0 : size - 1; + + if (index == newIndex) { + newIndex = -1; + } + } + + if (newIndex < 0) { + list.getSelectionModel().clearSelection(); + list.ensureIndexIsVisible(0); + + setTextWithoutNotification(userText); + } else { + list.setSelectedIndex(newIndex); + list.ensureIndexIsVisible(newIndex); + + setTextWithoutNotification(list.getSelectedValue()); + } + } + + private void setTextWithoutNotification(String text) { + notificationDenied = true; + + try { + setText(text); + } finally { + notificationDenied = false; + } + } + + private void onTextChanged() { + if (!notificationDenied) { + userText = getText(); + + showFilteredHistory(); + } + } + + private void showFilteredHistory() { + list.getSelectionModel().clearSelection(); + + DefaultListModel model = (DefaultListModel) list.getModel(); + + model.clear(); + + for (String s : history) { + if (s.contains(userText)) { + model.addElement(s); + } + } + + int size = model.size(); + + if (size == 0) { + popup.setVisible(false); + } else { + list.setVisibleRowCount(size < MAX_VISIBLE_ROWS ? size : MAX_VISIBLE_ROWS); + + popup.pack(); + + if (!popup.isShowing()) { + popup.show(JHistoryTextField.this, 0, getHeight()); + } + } + } + + public List getHistory() { + return Collections.unmodifiableList(history); + } + + public void setHistory(List history) { + this.history.clear(); + this.history.addAll(history); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/textfield/TextFieldDemo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/textfield/TextFieldDemo.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.textfield; + +import java.awt.*; +import java.awt.event.ActionEvent; +import java.util.*; +import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; + +import com.sun.swingset3.demos.JGridPanel; +import com.sun.swingset3.demos.ResourceManager; +import com.sun.swingset3.DemoProperties; + +/** + * JTextField Demo + * + * @author Pavel Porvatov + */ +@DemoProperties( + value = "TextField Demo", + category = "Text", + description = "Demonstrates the JTextField, a control which allows to input text", + sourceFiles = { + "com/sun/swingset3/demos/textfield/TextFieldDemo.java", + "com/sun/swingset3/demos/textfield/JHistoryTextField.java", + "com/sun/swingset3/demos/JGridPanel.java", + "com/sun/swingset3/demos/ResourceManager.java", + "com/sun/swingset3/demos/textfield/resources/TextFieldDemo.properties", + "com/sun/swingset3/demos/textfield/resources/images/TextFieldDemo.gif" + } +) +public class TextFieldDemo extends JPanel { + + private static final ResourceManager resourceManager = new ResourceManager(TextFieldDemo.class); + public static final String DEMO_TITLE = TextFieldDemo.class.getAnnotation(DemoProperties.class).value(); + + private final JLabel lbHistoryTextField = new JLabel(resourceManager.getString("TextFieldDemo.historytextfield.text")); + + private final JHistoryTextField tfHistory = new JHistoryTextField(); + + private final JLabel lbDow = new JLabel(resourceManager.getString("TextFieldDemo.dow.text")); + + private final JFormattedTextField tfDow = new JFormattedTextField(); + + private final JButton btnGo = new JButton(GO); + public static final String GO = resourceManager.getString("TextFieldDemo.go.text"); + + private final JLabel lbDowResult = new JLabel(); + + private final JLabel lbPassword = new JLabel(resourceManager.getString("TextFieldDemo.password.text")); + + private final JPasswordField tfPassword1 = new JPasswordField(20); + + private final JPasswordField tfPassword2 = new JPasswordField(20); + + private final DocumentListener passwordListener = new DocumentListener() { + + @Override + public void insertUpdate(DocumentEvent e) { + highlightPasswords(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + highlightPasswords(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + highlightPasswords(); + } + + private void highlightPasswords() { + Color color; + + if (tfPassword1.getPassword().length > 0 + && Arrays.equals(tfPassword1.getPassword(), tfPassword2.getPassword())) { + color = Color.GREEN; + } else { + color = UIManager.getColor("TextField.background"); + } + + tfPassword1.setBackground(color); + tfPassword2.setBackground(color); + } + }; + + /** + * main method allows us to run as a standalone demo. + * + * @param args + */ + public static void main(String[] args) { + JFrame frame = new JFrame(DEMO_TITLE); + + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(new TextFieldDemo()); + frame.setPreferredSize(new Dimension(800, 600)); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + public TextFieldDemo() { + setLayout(new BorderLayout()); + + initUI(); + + tfDow.setValue(new Date()); + + btnGo.addActionListener((ActionEvent e) -> { + Calendar calendar = Calendar.getInstance(Locale.ENGLISH); + + calendar.setTime((Date) tfDow.getValue()); + + lbDowResult.setText(calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.ENGLISH)); + }); + + tfPassword1.getDocument().addDocumentListener(passwordListener); + + tfPassword2.getDocument().addDocumentListener(passwordListener); + } + + private void initUI() { + tfHistory.setHistory(Arrays.asList(resourceManager.getString("TextFieldDemo.history.words").split("\\,"))); + + JGridPanel pnDow = new JGridPanel(3, 2); + + pnDow.cell(tfDow). + cell(btnGo). + cell(lbDowResult); + + JGridPanel pnPassword = new JGridPanel(3, 2); + + pnPassword.cell(tfPassword1). + cell(tfPassword2). + cell(); + + JGridPanel pnContent = new JGridPanel(1, 0, 6); + + pnContent.setBorderEqual(10); + + pnContent.cell(lbHistoryTextField). + cell(tfHistory). + cell(lbDow, new Insets(20, 0, 0, 0)). + cell(pnDow). + cell(lbPassword, new Insets(20, 0, 0, 0)). + cell(pnPassword). + cell(); + + add(pnContent); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/textfield/resources/TextFieldDemo.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/textfield/resources/TextFieldDemo.properties Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,7 @@ +### TextField Demo ### + +TextFieldDemo.historytextfield.text = This is an example of a text field with a history. To try it in action, type "cat". +TextFieldDemo.history.words = armageddon,cars,cartoon,casanova,casino,castle,castlevania,cat,category,caterpillar,click,dog,magpie,hare,rabbit +TextFieldDemo.dow.text = Enter a date and find out what day of the week it is. +TextFieldDemo.go.text = Go +TextFieldDemo.password.text = The text fields below become highlighted when they get identical values. diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/textfield/resources/images/TextFieldDemo.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/textfield/resources/images/TextFieldDemo.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/DirectionPanel.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/DirectionPanel.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.togglebutton; + +import java.awt.event.ActionListener; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ButtonGroup; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.border.Border; + +/** + * @version 1.8 11/17/05 + * @author Jeff Dinkins + * @author Chester Rose + * @author Brian Beck + */ +public class DirectionPanel extends JPanel { + + private final ButtonGroup group; + + public DirectionPanel(boolean enable, String selection, ActionListener l) { + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + setAlignmentY(TOP_ALIGNMENT); + setAlignmentX(LEFT_ALIGNMENT); + + Box firstThree = Box.createHorizontalBox(); + Box secondThree = Box.createHorizontalBox(); + Box thirdThree = Box.createHorizontalBox(); + + if (!enable) { + selection = "None"; + } + + group = new ButtonGroup(); + DirectionButton b; + b = (DirectionButton) firstThree.add(new DirectionButton(tl_dot, tldn_dot, "NW", "Sets the orientation to the North-West", l, group, selection.equals("NW"))); + b.setEnabled(enable); + b = (DirectionButton) firstThree.add(new DirectionButton(tm_dot, tmdn_dot, "N", "Sets the orientation to the North", l, group, selection.equals("N"))); + b.setEnabled(enable); + b = (DirectionButton) firstThree.add(new DirectionButton(tr_dot, trdn_dot, "NE", "Sets the orientation to the North-East", l, group, selection.equals("NE"))); + b.setEnabled(enable); + b = (DirectionButton) secondThree.add(new DirectionButton(ml_dot, mldn_dot, "W", "Sets the orientation to the West", l, group, selection.equals("W"))); + b.setEnabled(enable); + b = (DirectionButton) secondThree.add(new DirectionButton(c_dot, cdn_dot, "C", "Sets the orientation to the Center", l, group, selection.equals("C"))); + b.setEnabled(enable); + b = (DirectionButton) secondThree.add(new DirectionButton(mr_dot, mrdn_dot, "E", "Sets the orientation to the East", l, group, selection.equals("E"))); + b.setEnabled(enable); + b = (DirectionButton) thirdThree.add(new DirectionButton(bl_dot, bldn_dot, "SW", "Sets the orientation to the South-West", l, group, selection.equals("SW"))); + b.setEnabled(enable); + b = (DirectionButton) thirdThree.add(new DirectionButton(bm_dot, bmdn_dot, "S", "Sets the orientation to the South", l, group, selection.equals("S"))); + b.setEnabled(enable); + b = (DirectionButton) thirdThree.add(new DirectionButton(br_dot, brdn_dot, "SE", "Sets the orientation to the South-East", l, group, selection.equals("SE"))); + b.setEnabled(enable); + + add(firstThree); + add(secondThree); + add(thirdThree); + } + + // Chester's way cool layout buttons + private final ImageIcon bl_dot = loadImageIcon("bl.gif", "bottom left layout button"); + private final ImageIcon bldn_dot = loadImageIcon("bldn.gif", "selected bottom left layout button"); + private final ImageIcon bm_dot = loadImageIcon("bm.gif", "bottom middle layout button"); + private final ImageIcon bmdn_dot = loadImageIcon("bmdn.gif", "selected bottom middle layout button"); + private final ImageIcon br_dot = loadImageIcon("br.gif", "bottom right layout button"); + private final ImageIcon brdn_dot = loadImageIcon("brdn.gif", "selected bottom right layout button"); + private final ImageIcon c_dot = loadImageIcon("c.gif", "center layout button"); + private final ImageIcon cdn_dot = loadImageIcon("cdn.gif", "selected center layout button"); + private final ImageIcon ml_dot = loadImageIcon("ml.gif", "middle left layout button"); + private final ImageIcon mldn_dot = loadImageIcon("mldn.gif", "selected middle left layout button"); + private final ImageIcon mr_dot = loadImageIcon("mr.gif", "middle right layout button"); + private final ImageIcon mrdn_dot = loadImageIcon("mrdn.gif", "selected middle right layout button"); + private final ImageIcon tl_dot = loadImageIcon("tl.gif", "top left layout button"); + private final ImageIcon tldn_dot = loadImageIcon("tldn.gif", "selected top left layout button"); + private final ImageIcon tm_dot = loadImageIcon("tm.gif", "top middle layout button"); + private final ImageIcon tmdn_dot = loadImageIcon("tmdn.gif", "selected top middle layout button"); + private final ImageIcon tr_dot = loadImageIcon("tr.gif", "top right layout button"); + private final ImageIcon trdn_dot = loadImageIcon("trdn.gif", "selected top right layout button"); + + private ImageIcon loadImageIcon(String filename, String description) { + String path = "resources/images/" + filename; + return new ImageIcon(getClass().getResource(path), description); + } + + private static class DirectionButton extends JRadioButton { + + /** + * A layout direction button + */ + public DirectionButton(Icon icon, Icon downIcon, String direction, + String description, ActionListener l, + ButtonGroup group, boolean selected) { + super(); + this.addActionListener(l); + setFocusPainted(false); + setHorizontalTextPosition(CENTER); + group.add(this); + setIcon(icon); + setSelectedIcon(downIcon); + setActionCommand(direction); + getAccessibleContext().setAccessibleName(direction); + getAccessibleContext().setAccessibleDescription(description); + setSelected(selected); + } + + @Override + @Deprecated + public boolean isFocusTraversable() { + return false; + } + + @Override + public void setBorder(Border b) { + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/LayoutControlPanel.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/LayoutControlPanel.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,281 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.togglebutton; + +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.*; + +import com.sun.swingset3.demos.ResourceManager; + +/* + * The LayoutControlPanel contains controls for setting an + * AbstractButton's horizontal and vertical text position and + * horizontal and vertical alignment. + */ +public final class LayoutControlPanel extends JPanel implements SwingConstants { + + private static final Dimension VGAP20 = new Dimension(1, 20); + private static final ResourceManager resourceManager = ToggleButtonDemo.resourceManager; + public static final String CONTENT_ALIGNMENT = resourceManager.getString("LayoutControlPanel.contentalignment_label"); + public static final String TEXT_POSITION = resourceManager.getString("LayoutControlPanel.textposition_label"); + private final boolean absolutePositions; + private ToggleButtonDemo demo = null; + + // private ComponentOrientChanger componentOrientChanger = null; + LayoutControlPanel(ToggleButtonDemo demo) { + this.demo = demo; + + // this.componentOrientationChanger = componentOrientationChanger; + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + setAlignmentX(LEFT_ALIGNMENT); + setAlignmentY(TOP_ALIGNMENT); + + JLabel l; + + // If SwingSet has a ComponentOrientationChanger, then include control + // for choosing between absolute and relative positioning. This will + // only happen when we're running on JDK 1.2 or above. + // + // if(componentOrientationChanger != null ) { + // l = new JLabel("Positioning:"); + // add(l); + // + // ButtonGroup group = new ButtonGroup(); + // PositioningListener positioningListener = new PositioningListener(); + // JRadioButton absolutePos = new JRadioButton("Absolute"); + // absolutePos.setMnemonic('a'); + // absolutePos.setToolTipText("Text/Content positioning is independant of line direction"); + // group.add(absolutePos); + // absolutePos.addItemListener(positioningListener); + // add(absolutePos); + // + // JRadioButton relativePos = new JRadioButton("Relative"); + // relativePos.setMnemonic('r'); + // relativePos.setToolTipText("Text/Content positioning depends on line direction."); + // group.add(relativePos); + // relativePos.addItemListener(positioningListener); + // add(relativePos); + // + // add(Box.createRigidArea(demo.VGAP20)); + // + // absolutePositions = false; + // relativePos.setSelected(true); + // + // componentOrientationChanger.addActionListener( new OrientationChangeListener() ); + //} else { + absolutePositions = true; + //} + + DirectionPanel textPosition = new DirectionPanel(true, "E", new TextPositionListener()); + DirectionPanel labelAlignment = new DirectionPanel(true, "C", new LabelAlignmentListener()); + + // Make sure the controls' text position and label alignment match + // the initial value of the associated direction panel. + for (JComponent control : demo.getCurrentControls()) { + setPosition(control, RIGHT, CENTER); + setAlignment(control, CENTER, CENTER); + } + + l = new JLabel(TEXT_POSITION); + add(l); + add(textPosition); + + add(Box.createRigidArea(VGAP20)); + + l = new JLabel(CONTENT_ALIGNMENT); + add(l); + add(labelAlignment); + + add(Box.createGlue()); + } + + // Text Position Listener + private class TextPositionListener implements ActionListener { + + @Override + public void actionPerformed(ActionEvent e) { + JRadioButton rb = (JRadioButton) e.getSource(); + if (!rb.isSelected()) { + return; + } + String cmd = rb.getActionCommand(); + int hPos, vPos; + switch (cmd) { + case "NW": + hPos = LEFT; + vPos = TOP; + break; + case "N": + hPos = CENTER; + vPos = TOP; + break; + case "NE": + hPos = RIGHT; + vPos = TOP; + break; + case "W": + hPos = LEFT; + vPos = CENTER; + break; + case "C": + hPos = CENTER; + vPos = CENTER; + break; + case "E": + hPos = RIGHT; + vPos = CENTER; + break; + case "SW": + hPos = LEFT; + vPos = BOTTOM; + break; + case "S": + hPos = CENTER; + vPos = BOTTOM; + break; + /*if(cmd.equals("SE"))*/ + default: + hPos = RIGHT; + vPos = BOTTOM; + break; + } + for (JComponent control : demo.getCurrentControls()) { + setPosition(control, hPos, vPos); + } + demo.invalidate(); + demo.validate(); + demo.repaint(); + } + } + + // Label Alignment Listener + private class LabelAlignmentListener implements ActionListener { + + @Override + public void actionPerformed(ActionEvent e) { + JRadioButton rb = (JRadioButton) e.getSource(); + if (!rb.isSelected()) { + return; + } + String cmd = rb.getActionCommand(); + int hPos, vPos; + switch (cmd) { + case "NW": + hPos = LEFT; + vPos = TOP; + break; + case "N": + hPos = CENTER; + vPos = TOP; + break; + case "NE": + hPos = RIGHT; + vPos = TOP; + break; + case "W": + hPos = LEFT; + vPos = CENTER; + break; + case "C": + hPos = CENTER; + vPos = CENTER; + break; + case "E": + hPos = RIGHT; + vPos = CENTER; + break; + case "SW": + hPos = LEFT; + vPos = BOTTOM; + break; + case "S": + hPos = CENTER; + vPos = BOTTOM; + break; + /*if(cmd.equals("SE"))*/ + default: + hPos = RIGHT; + vPos = BOTTOM; + break; + } + for (JComponent control : demo.getCurrentControls()) { + setAlignment(control, hPos, vPos); + control.invalidate(); + } + demo.invalidate(); + demo.validate(); + demo.repaint(); + } + } + + // Position + void setPosition(Component c, int hPos, int vPos) { + boolean ltr = c.getComponentOrientation().isLeftToRight(); + if (absolutePositions) { + if (hPos == LEADING) { + hPos = ltr ? LEFT : RIGHT; + } else if (hPos == TRAILING) { + hPos = ltr ? RIGHT : LEFT; + } + } else if (hPos == LEFT) { + hPos = ltr ? LEADING : TRAILING; + } else if (hPos == RIGHT) { + hPos = ltr ? TRAILING : LEADING; + } + if (c instanceof AbstractButton) { + AbstractButton x = (AbstractButton) c; + x.setHorizontalTextPosition(hPos); + x.setVerticalTextPosition(vPos); + } else if (c instanceof JLabel) { + JLabel x = (JLabel) c; + x.setHorizontalTextPosition(hPos); + x.setVerticalTextPosition(vPos); + } + } + + void setAlignment(Component c, int hPos, int vPos) { + boolean ltr = c.getComponentOrientation().isLeftToRight(); + if (absolutePositions) { + if (hPos == LEADING) { + hPos = ltr ? LEFT : RIGHT; + } else if (hPos == TRAILING) { + hPos = ltr ? RIGHT : LEFT; + } + } else if (hPos == LEFT) { + hPos = ltr ? LEADING : TRAILING; + } else if (hPos == RIGHT) { + hPos = ltr ? TRAILING : LEADING; + } + if (c instanceof AbstractButton) { + AbstractButton x = (AbstractButton) c; + x.setHorizontalAlignment(hPos); + x.setVerticalAlignment(vPos); + } else if (c instanceof JLabel) { + JLabel x = (JLabel) c; + x.setHorizontalAlignment(hPos); + x.setVerticalAlignment(vPos); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/ToggleButtonDemo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/ToggleButtonDemo.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,563 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.togglebutton; + +import java.awt.*; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.*; +import java.util.List; +import javax.swing.*; +import javax.swing.border.*; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; + +import com.sun.swingset3.DemoProperties; +import com.sun.swingset3.demos.ResourceManager; + +/** + * JButton, JRadioButton, JToggleButton, JCheckBox Demos + * + * @version 1.15 11/17/05 + * @author Jeff Dinkins + */ +@DemoProperties( + value = "ToggleButtons Demo", + category = "Controls", + description = "Demonstrates JCheckBox & JRadioButton", + sourceFiles = { + "com/sun/swingset3/demos/togglebutton/ToggleButtonDemo.java", + "com/sun/swingset3/demos/togglebutton/DirectionPanel.java", + "com/sun/swingset3/demos/togglebutton/LayoutControlPanel.java", + "com/sun/swingset3/demos/ResourceManager.java", + "com/sun/swingset3/demos/togglebutton/resources/ToggleButtonDemo.properties", + "com/sun/swingset3/demos/togglebutton/resources/images/b1.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/b1d.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/b1p.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/b1r.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/b2.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/b2d.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/b2p.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/b2r.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/b3.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/b3d.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/b3p.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/b3r.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/bl.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/bldn.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/bm.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/bmdn.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/br.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/brdn.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/c.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/cb.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/cbr.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/cbrs.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/cbs.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/cdn.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/ml.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/mldn.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/mr.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/mrdn.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/rb.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/rbp.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/rbr.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/rbrs.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/rbs.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/tl.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/tldn.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/tm.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/tmdn.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/ToggleButtonDemo.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/tr.gif", + "com/sun/swingset3/demos/togglebutton/resources/images/trdn.gif" + } +) +public class ToggleButtonDemo extends JPanel implements ChangeListener { + + private static final Dimension HGAP10 = new Dimension(10, 1); + private static final Dimension HGAP20 = new Dimension(20, 1); + private static final Dimension VGAP20 = new Dimension(1, 20); + private static final Dimension VGAP30 = new Dimension(1, 30); + + static final ResourceManager resourceManager = new ResourceManager(ToggleButtonDemo.class); + public static final String RADIO3 = resourceManager.getString("ToggleButtonDemo.radio3"); + public static final String RADIO2 = resourceManager.getString("ToggleButtonDemo.radio2"); + public static final String RADIO1 = resourceManager.getString("ToggleButtonDemo.radio1"); + public static final String IMAGE_RADIO_BUTTONS = resourceManager.getString("ToggleButtonDemo.imageradiobuttons"); + public static final String TEXT_RADIO_BUTTONS = resourceManager.getString("ToggleButtonDemo.textradiobuttons"); + public static final String CHECK3 = resourceManager.getString("ToggleButtonDemo.check3"); + public static final String CHECK2 = resourceManager.getString("ToggleButtonDemo.check2"); + public static final String CHECK1 = resourceManager.getString("ToggleButtonDemo.check1"); + public static final String CHECK_BOXES = resourceManager.getString("ToggleButtonDemo.checkboxes"); + public static final String IMAGE_CHECKBOXES = resourceManager.getString("ToggleButtonDemo.imagecheckboxes"); + public static final String TEXT_CHECKBOXES = resourceManager.getString("ToggleButtonDemo.textcheckboxes"); + public static final String CONTENT_FILLED = resourceManager.getString("ToggleButtonDemo.contentfilled"); + public static final String ENABLED = resourceManager.getString("ToggleButtonDemo.enabled"); + public static final String PAINT_FOCUS = resourceManager.getString("ToggleButtonDemo.paintfocus"); + public static final String PAINT_BORDER = resourceManager.getString("ToggleButtonDemo.paintborder"); + public static final String DISPLAY_OPTIONS = resourceManager.getString("ToggleButtonDemo.controlpanel_label"); + public static final String DEFAULT = resourceManager.getString("ToggleButtonDemo.default"); + public static final String PAD_AMOUNT = resourceManager.getString("ToggleButtonDemo.padamount_label"); + + private final JTabbedPane tab; + + private final JPanel checkboxPanel = new JPanel(); + private final JPanel radioButtonPanel = new JPanel(); + + private final List buttons = new ArrayList<>(); + private final List checkboxes = new ArrayList<>(); + private final List radiobuttons = new ArrayList<>(); + private final List togglebuttons = new ArrayList<>(); + + private List currentControls = buttons; + + private final EmptyBorder border5 = new EmptyBorder(5, 5, 5, 5); + + private ItemListener buttonDisplayListener = null; + private ItemListener buttonPadListener = null; + + private final Insets insets0 = new Insets(0, 0, 0, 0); + private final Insets insets10 = new Insets(10, 10, 10, 10); + + private final Border loweredBorder = new CompoundBorder( + new SoftBevelBorder(SoftBevelBorder.LOWERED), new EmptyBorder(5, 5, 5, 5)); + + /** + * main method allows us to run as a standalone demo. + * + * @param args + */ + public static void main(String[] args) { + JFrame frame = new JFrame(ToggleButtonDemo.class.getAnnotation(DemoProperties.class).value()); + + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(new ToggleButtonDemo()); + frame.setPreferredSize(new Dimension(800, 600)); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + /** + * ButtonDemo Constructor + */ + public ToggleButtonDemo() { + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + + tab = new JTabbedPane(); + tab.getModel().addChangeListener(this); + + add(tab); + + //addButtons(); + addRadioButtons(); + addCheckBoxes(); + //addToggleButtons(); + currentControls = checkboxes; + } + + private void addRadioButtons() { + ButtonGroup group = new ButtonGroup(); + + tab.addTab(resourceManager.getString("ToggleButtonDemo.radiobuttons"), radioButtonPanel); + radioButtonPanel.setLayout(new BoxLayout(radioButtonPanel, BoxLayout.X_AXIS)); + radioButtonPanel.setBorder(border5); + + JPanel p1 = createVerticalPanel(true); + p1.setAlignmentY(TOP_ALIGNMENT); + radioButtonPanel.add(p1); + + // Text Radio Buttons + JPanel p2 = createHorizontalPanel(false); + p1.add(p2); + p2.setBorder(new CompoundBorder( + new TitledBorder( + null, TEXT_RADIO_BUTTONS, + TitledBorder.LEFT, TitledBorder.TOP), border5) + ); + + JRadioButton radio = (JRadioButton) p2.add(new JRadioButton(RADIO1)); + group.add(radio); + radiobuttons.add(radio); + p2.add(Box.createRigidArea(HGAP10)); + + radio = (JRadioButton) p2.add(new JRadioButton(RADIO2)); + group.add(radio); + radiobuttons.add(radio); + p2.add(Box.createRigidArea(HGAP10)); + + radio = (JRadioButton) p2.add(new JRadioButton(RADIO3)); + group.add(radio); + radiobuttons.add(radio); + + // Image Radio Buttons + group = new ButtonGroup(); + p1.add(Box.createRigidArea(VGAP30)); + JPanel p3 = createHorizontalPanel(false); + p1.add(p3); + p3.setLayout(new BoxLayout(p3, BoxLayout.X_AXIS)); + p3.setBorder(new TitledBorder(null, IMAGE_RADIO_BUTTONS, + TitledBorder.LEFT, TitledBorder.TOP)); + + // image radio button 1 + String description = resourceManager.getString("ToggleButtonDemo.customradio"); + String text = RADIO1; + radio = new JRadioButton(text, resourceManager.createImageIcon("rb.gif", description)); + radio.setPressedIcon(resourceManager.createImageIcon("rbp.gif", description)); + radio.setRolloverIcon(resourceManager.createImageIcon("rbr.gif", description)); + radio.setRolloverSelectedIcon(resourceManager.createImageIcon("rbrs.gif", description)); + radio.setSelectedIcon(resourceManager.createImageIcon("rbs.gif", description)); + radio.setMargin(new Insets(0, 0, 0, 0)); + group.add(radio); + p3.add(radio); + radiobuttons.add(radio); + p3.add(Box.createRigidArea(HGAP20)); + + // image radio button 2 + text = RADIO2; + radio = new JRadioButton(text, resourceManager.createImageIcon("rb.gif", description)); + radio.setPressedIcon(resourceManager.createImageIcon("rbp.gif", description)); + radio.setRolloverIcon(resourceManager.createImageIcon("rbr.gif", description)); + radio.setRolloverSelectedIcon(resourceManager.createImageIcon("rbrs.gif", description)); + radio.setSelectedIcon(resourceManager.createImageIcon("rbs.gif", description)); + radio.setMargin(new Insets(0, 0, 0, 0)); + group.add(radio); + p3.add(radio); + radiobuttons.add(radio); + p3.add(Box.createRigidArea(HGAP20)); + + // image radio button 3 + text = RADIO3; + radio = new JRadioButton(text, resourceManager.createImageIcon("rb.gif", description)); + radio.setPressedIcon(resourceManager.createImageIcon("rbp.gif", description)); + radio.setRolloverIcon(resourceManager.createImageIcon("rbr.gif", description)); + radio.setRolloverSelectedIcon(resourceManager.createImageIcon("rbrs.gif", description)); + radio.setSelectedIcon(resourceManager.createImageIcon("rbs.gif", description)); + radio.setMargin(new Insets(0, 0, 0, 0)); + group.add(radio); + radiobuttons.add(radio); + p3.add(radio); + + // verticaly glue fills out the rest of the box + p1.add(Box.createVerticalGlue()); + + radioButtonPanel.add(Box.createHorizontalGlue()); + currentControls = radiobuttons; + radioButtonPanel.add(createControls()); + } + + private void addCheckBoxes() { + tab.addTab(CHECK_BOXES, checkboxPanel); + checkboxPanel.setLayout(new BoxLayout(checkboxPanel, BoxLayout.X_AXIS)); + checkboxPanel.setBorder(border5); + + JPanel p1 = createVerticalPanel(true); + p1.setAlignmentY(TOP_ALIGNMENT); + checkboxPanel.add(p1); + + // Text Radio Buttons + JPanel p2 = createHorizontalPanel(false); + p1.add(p2); + p2.setBorder(new CompoundBorder( + new TitledBorder( + null, TEXT_CHECKBOXES, + TitledBorder.LEFT, TitledBorder.TOP), border5) + ); + + JCheckBox checkBox1 = new JCheckBox(CHECK1); + checkboxes.add(checkBox1); + p2.add(checkBox1); + p2.add(Box.createRigidArea(HGAP10)); + + JCheckBox checkBox2 = new JCheckBox(CHECK2); + checkboxes.add(checkBox2); + p2.add(checkBox2); + p2.add(Box.createRigidArea(HGAP10)); + + JCheckBox checkBox3 = new JCheckBox(CHECK3); + checkboxes.add(checkBox3); + p2.add(checkBox3); + + // Image Radio Buttons + p1.add(Box.createRigidArea(VGAP30)); + JPanel p3 = createHorizontalPanel(false); + p1.add(p3); + p3.setLayout(new BoxLayout(p3, BoxLayout.X_AXIS)); + p3.setBorder(new TitledBorder(null, IMAGE_CHECKBOXES, + TitledBorder.LEFT, TitledBorder.TOP)); + + // image checkbox 1 + String description = resourceManager.getString("ToggleButtonDemo.customcheck"); + String text = CHECK1; + JCheckBox check = new JCheckBox(text, + resourceManager.createImageIcon("cb.gif", description)); + check.setRolloverIcon(resourceManager.createImageIcon("cbr.gif", description)); + check.setRolloverSelectedIcon(resourceManager.createImageIcon("cbrs.gif", description)); + check.setSelectedIcon(resourceManager.createImageIcon("cbs.gif", description)); + check.setMargin(new Insets(0, 0, 0, 0)); + p3.add(check); + checkboxes.add(check); + p3.add(Box.createRigidArea(HGAP20)); + + // image checkbox 2 + text = CHECK2; + check = new JCheckBox(text, resourceManager.createImageIcon("cb.gif", description)); + check.setRolloverIcon(resourceManager.createImageIcon("cbr.gif", description)); + check.setRolloverSelectedIcon(resourceManager.createImageIcon("cbrs.gif", description)); + check.setSelectedIcon(resourceManager.createImageIcon("cbs.gif", description)); + check.setMargin(new Insets(0, 0, 0, 0)); + p3.add(check); + checkboxes.add(check); + p3.add(Box.createRigidArea(HGAP20)); + + // image checkbox 3 + text = CHECK3; + check = new JCheckBox(text, resourceManager.createImageIcon("cb.gif", description)); + check.setRolloverIcon(resourceManager.createImageIcon("cbr.gif", description)); + check.setRolloverSelectedIcon(resourceManager.createImageIcon("cbrs.gif", description)); + check.setSelectedIcon(resourceManager.createImageIcon("cbs.gif", description)); + check.setMargin(new Insets(0, 0, 0, 0)); + p3.add(check); + checkboxes.add(check); + + // verticaly glue fills out the rest of the box + p1.add(Box.createVerticalGlue()); + + checkboxPanel.add(Box.createHorizontalGlue()); + currentControls = checkboxes; + checkboxPanel.add(createControls()); + } + + private JPanel createControls() { + JPanel controls = new JPanel() { + @Override + public Dimension getMaximumSize() { + return new Dimension(300, super.getMaximumSize().height); + } + }; + controls.setLayout(new BoxLayout(controls, BoxLayout.Y_AXIS)); + controls.setAlignmentY(TOP_ALIGNMENT); + controls.setAlignmentX(LEFT_ALIGNMENT); + + JPanel buttonControls = createHorizontalPanel(true); + buttonControls.setAlignmentY(TOP_ALIGNMENT); + buttonControls.setAlignmentX(LEFT_ALIGNMENT); + + JPanel leftColumn = createVerticalPanel(false); + leftColumn.setAlignmentX(LEFT_ALIGNMENT); + leftColumn.setAlignmentY(TOP_ALIGNMENT); + + JPanel rightColumn = new LayoutControlPanel(this); + + buttonControls.add(leftColumn); + buttonControls.add(Box.createRigidArea(HGAP20)); + buttonControls.add(rightColumn); + buttonControls.add(Box.createRigidArea(HGAP20)); + + controls.add(buttonControls); + + createListeners(); + + // Display Options + JLabel l = new JLabel(DISPLAY_OPTIONS); + leftColumn.add(l); + + JCheckBox bordered = new JCheckBox(PAINT_BORDER); + bordered.setActionCommand("PaintBorder"); + bordered.setToolTipText(resourceManager.getString("ToggleButtonDemo.paintborder_tooltip")); + bordered.setMnemonic(resourceManager.getMnemonic("ToggleButtonDemo.paintborder_mnemonic")); + if (currentControls == buttons) { + bordered.setSelected(true); + } + bordered.addItemListener(buttonDisplayListener); + leftColumn.add(bordered); + + JCheckBox focused = new JCheckBox(PAINT_FOCUS); + focused.setActionCommand("PaintFocus"); + focused.setToolTipText(resourceManager.getString("ToggleButtonDemo.paintfocus_tooltip")); + focused.setMnemonic(resourceManager.getMnemonic("ToggleButtonDemo.paintfocus_mnemonic")); + focused.setSelected(true); + focused.addItemListener(buttonDisplayListener); + leftColumn.add(focused); + + JCheckBox enabled = new JCheckBox(ENABLED); + enabled.setActionCommand("Enabled"); + enabled.setToolTipText(resourceManager.getString("ToggleButtonDemo.enabled_tooltip")); + enabled.setSelected(true); + enabled.addItemListener(buttonDisplayListener); + enabled.setMnemonic(resourceManager.getMnemonic("ToggleButtonDemo.enabled_mnemonic")); + leftColumn.add(enabled); + + JCheckBox filled = new JCheckBox(CONTENT_FILLED); + filled.setActionCommand("ContentFilled"); + filled.setToolTipText(resourceManager.getString("ToggleButtonDemo.contentfilled_tooltip")); + filled.setSelected(true); + filled.addItemListener(buttonDisplayListener); + filled.setMnemonic(resourceManager.getMnemonic("ToggleButtonDemo.contentfilled_mnemonic")); + leftColumn.add(filled); + + leftColumn.add(Box.createRigidArea(VGAP20)); + + l = new JLabel(PAD_AMOUNT); + leftColumn.add(l); + ButtonGroup group = new ButtonGroup(); + JRadioButton defaultPad = new JRadioButton(DEFAULT); + defaultPad.setToolTipText(resourceManager.getString("ToggleButtonDemo.default_tooltip")); + defaultPad.setMnemonic(resourceManager.getMnemonic("ToggleButtonDemo.default_mnemonic")); + defaultPad.addItemListener(buttonPadListener); + group.add(defaultPad); + defaultPad.setSelected(true); + leftColumn.add(defaultPad); + + JRadioButton zeroPad = new JRadioButton(resourceManager.getString("ToggleButtonDemo.zero")); + zeroPad.setActionCommand("ZeroPad"); + zeroPad.setToolTipText(resourceManager.getString("ToggleButtonDemo.zero_tooltip")); + zeroPad.addItemListener(buttonPadListener); + zeroPad.setMnemonic(resourceManager.getMnemonic("ToggleButtonDemo.zero_mnemonic")); + group.add(zeroPad); + leftColumn.add(zeroPad); + + JRadioButton tenPad = new JRadioButton(resourceManager.getString("ToggleButtonDemo.ten")); + tenPad.setActionCommand("TenPad"); + tenPad.setMnemonic(resourceManager.getMnemonic("ToggleButtonDemo.ten_mnemonic")); + tenPad.setToolTipText(resourceManager.getString("ToggleButtonDemo.ten_tooltip")); + tenPad.addItemListener(buttonPadListener); + group.add(tenPad); + leftColumn.add(tenPad); + + leftColumn.add(Box.createRigidArea(VGAP20)); + return controls; + } + + private void createListeners() { + buttonDisplayListener = (ItemEvent e) -> { + JCheckBox cb = (JCheckBox) e.getSource(); + String command = cb.getActionCommand(); + switch (command) { + case "Enabled": + for (JComponent control : currentControls) { + control.setEnabled(cb.isSelected()); + control.invalidate(); + } + break; + case "PaintBorder": + if (currentControls.get(0) instanceof AbstractButton) { + for (JComponent control : currentControls) { + AbstractButton b = (AbstractButton) control; + b.setBorderPainted(cb.isSelected()); + b.invalidate(); + } + } + break; + case "PaintFocus": + if (currentControls.get(0) instanceof AbstractButton) { + for (JComponent control : currentControls) { + AbstractButton b = (AbstractButton) control; + b.setFocusPainted(cb.isSelected()); + b.invalidate(); + } + } + break; + case "ContentFilled": + if (currentControls.get(0) instanceof AbstractButton) { + for (JComponent control : currentControls) { + AbstractButton b = (AbstractButton) control; + b.setContentAreaFilled(cb.isSelected()); + b.invalidate(); + } + } + break; + } + invalidate(); + validate(); + repaint(); + }; + + buttonPadListener = (ItemEvent e) -> { + // *** pad = 0 + int pad = -1; + JRadioButton rb = (JRadioButton) e.getSource(); + String command = rb.getActionCommand(); + if ("ZeroPad".equals(command) && rb.isSelected()) { + pad = 0; + } else if ("TenPad".equals(command) && rb.isSelected()) { + pad = 10; + } + + for (JComponent control : currentControls) { + AbstractButton b = (AbstractButton) control; + if (pad == -1) { + b.setMargin(null); + } else if (pad == 0) { + b.setMargin(insets0); + } else { + b.setMargin(insets10); + } + } + invalidate(); + validate(); + repaint(); + }; + } + + @Override + public void stateChanged(ChangeEvent e) { + SingleSelectionModel model = (SingleSelectionModel) e.getSource(); + if (model.getSelectedIndex() == 0) { + currentControls = buttons; + } else if (model.getSelectedIndex() == 1) { + currentControls = radiobuttons; + } else if (model.getSelectedIndex() == 2) { + currentControls = checkboxes; + } else { + currentControls = togglebuttons; + } + } + + public List getCurrentControls() { + return currentControls; + } + + private JPanel createHorizontalPanel(boolean threeD) { + JPanel p = new JPanel(); + p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS)); + p.setAlignmentY(TOP_ALIGNMENT); + p.setAlignmentX(LEFT_ALIGNMENT); + if (threeD) { + p.setBorder(loweredBorder); + } + return p; + } + + private JPanel createVerticalPanel(boolean threeD) { + JPanel p = new JPanel(); + p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); + p.setAlignmentY(TOP_ALIGNMENT); + p.setAlignmentX(LEFT_ALIGNMENT); + if (threeD) { + p.setBorder(loweredBorder); + } + return p; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/ToggleButtonDemo.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/ToggleButtonDemo.properties Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,69 @@ +### Button Demo ### + +ToggleButtonDemo.accessible_description=The ButtonDemo shows examples of using JButton, JRadioButton, JToggleButton, and JCheckBox +ToggleButtonDemo.tooltip=JButton, JRadioButton, JToggleButton, JCheckbox demos +ToggleButtonDemo.name=Button Demo + +ToggleButtonDemo.buttons=Buttons +ToggleButtonDemo.checkboxes=Check Boxes +ToggleButtonDemo.radiobuttons=Radio Buttons +ToggleButtonDemo.togglebuttons=Toggle Buttons + +ToggleButtonDemo.textbuttons=Text Buttons +ToggleButtonDemo.imagebuttons=Image Buttons +ToggleButtonDemo.textradiobuttons=Text Radio Buttons +ToggleButtonDemo.imageradiobuttons=Image Radio Buttons +ToggleButtonDemo.texttogglebuttons=Text Toggle Buttons +ToggleButtonDemo.imagetogglebuttons=Image Toggle Buttons +ToggleButtonDemo.textcheckboxes=Text CheckBoxes +ToggleButtonDemo.imagecheckboxes=Image CheckBoxes + +ToggleButtonDemo.button1=One +ToggleButtonDemo.button2=Two +ToggleButtonDemo.button3=Three! + +ToggleButtonDemo.radio1=Radio One +ToggleButtonDemo.radio2=Radio Two +ToggleButtonDemo.radio3=Radio Three +ToggleButtonDemo.radioX=Three(HTML!) + +ToggleButtonDemo.check1=One +ToggleButtonDemo.check2=Two +ToggleButtonDemo.check3=Three +ToggleButtonDemo.checkX=Three(HTML!) + +ToggleButtonDemo.customradio=A custom "chrome" radio button. +ToggleButtonDemo.customcheck=A custom lightbulb checkbox. + +ToggleButtonDemo.phone=Phone +ToggleButtonDemo.write=Write +ToggleButtonDemo.peace=Peace + +ToggleButtonDemo.controlpanel_label=Display Options: +ToggleButtonDemo.paintborder=Paint Border +ToggleButtonDemo.paintborder_tooltip=Click here to turn border painting on or off. +ToggleButtonDemo.paintborder_mnemonic=b +ToggleButtonDemo.paintfocus=Paint Focus +ToggleButtonDemo.paintfocus_tooltip=Click here to turn focus painting on or off. +ToggleButtonDemo.paintfocus_mnemonic=f +ToggleButtonDemo.enabled=Enabled +ToggleButtonDemo.enabled_tooltip=Click here to enable or disable the buttons. +ToggleButtonDemo.enabled_mnemonic=e +ToggleButtonDemo.contentfilled=Content Filled +ToggleButtonDemo.contentfilled_tooltip=Click here to control the filling of the content area. +ToggleButtonDemo.contentfilled_mnemonic=i + +ToggleButtonDemo.padamount_label=Pad Amount: +ToggleButtonDemo.default=Default +ToggleButtonDemo.default_tooltip=Uses the default padding between the border and label. +ToggleButtonDemo.default_mnemonic=d +ToggleButtonDemo.zero=0 +ToggleButtonDemo.zero_mnemonic=0 +ToggleButtonDemo.zero_tooltip=Uses no padding between the border and label. +ToggleButtonDemo.ten=10 +ToggleButtonDemo.ten_mnemonic=1 +ToggleButtonDemo.ten_tooltip=Uses a 10 pixel pad between the border and label. + +LayoutControlPanel.textposition_label=Text Position: +LayoutControlPanel.contentalignment_label=Content Alignment: + diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/ToggleButtonDemo.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/ToggleButtonDemo.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b1.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b1.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b1d.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b1d.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b1p.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b1p.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b1r.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b1r.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b2.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b2.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b2d.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b2d.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b2p.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b2p.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b2r.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b2r.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b3.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b3.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b3d.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b3d.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b3p.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b3p.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b3r.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/b3r.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/bl.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/bl.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/bldn.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/bldn.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/bm.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/bm.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/bmdn.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/bmdn.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/br.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/br.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/brdn.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/brdn.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/c.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/c.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/cb.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/cb.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/cbr.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/cbr.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/cbrs.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/cbrs.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/cbs.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/cbs.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/cdn.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/cdn.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/ml.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/ml.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/mldn.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/mldn.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/mr.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/mr.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/mrdn.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/mrdn.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/rb.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/rb.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/rbp.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/rbp.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/rbr.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/rbr.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/rbrs.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/rbrs.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/rbs.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/rbs.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/tl.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/tl.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/tldn.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/tldn.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/tm.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/tm.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/tmdn.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/tmdn.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/tr.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/tr.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/trdn.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/togglebutton/resources/images/trdn.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tree/TreeDemo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tree/TreeDemo.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.tree; + +import java.awt.*; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import javax.swing.*; +import javax.swing.tree.DefaultMutableTreeNode; + +import com.sun.swingset3.DemoProperties; +import com.sun.swingset3.demos.ResourceManager; + +/** + * JTree Demo + * + * @version 1.13 11/17/05 + * @author Jeff Dinkins + */ +@DemoProperties( + value = "JTree Demo", + category = "Data", + description = "Demonstrates JTree, a component which supports display/editing of hierarchical data", + sourceFiles = { + "com/sun/swingset3/demos/tree/TreeDemo.java", + "com/sun/swingset3/demos/ResourceManager.java", + "com/sun/swingset3/demos/tree/resources/tree.txt", + "com/sun/swingset3/demos/tree/resources/TreeDemo.properties", + "com/sun/swingset3/demos/tree/resources/images/TreeDemo.gif" + } +) +public class TreeDemo extends JPanel { + + private final ResourceManager resourceManager = new ResourceManager(this.getClass()); + public static final String DEMO_TITLE = TreeDemo.class.getAnnotation(DemoProperties.class).value(); + + /** + * main method allows us to run as a standalone demo. + * + * @param args + */ + public static void main(String[] args) { + JFrame frame = new JFrame(DEMO_TITLE); + + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.getContentPane().add(new TreeDemo()); + frame.setPreferredSize(new Dimension(800, 600)); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + /** + * TreeDemo Constructor + */ + public TreeDemo() { + setLayout(new BorderLayout()); + + add(new JScrollPane(createTree()), BorderLayout.CENTER); + } + + private JTree createTree() { + DefaultMutableTreeNode top = new DefaultMutableTreeNode(resourceManager.getString("TreeDemo.music")); + DefaultMutableTreeNode catagory = null; + DefaultMutableTreeNode artist = null; + DefaultMutableTreeNode record = null; + + // open tree data + URL url = getClass().getResource("resources/tree.txt"); + + try { + // convert url to buffered string + InputStream is = url.openStream(); + InputStreamReader isr = new InputStreamReader(is, "UTF-8"); + BufferedReader reader = new BufferedReader(isr); + + // read one line at a time, put into tree + String line = reader.readLine(); + while (line != null) { + // System.out.println("reading in: ->" + line + "<-"); + char linetype = line.charAt(0); + switch (linetype) { + case 'C': + catagory = new DefaultMutableTreeNode(line.substring(2)); + top.add(catagory); + break; + case 'A': + if (catagory != null) { + catagory.add(artist = new DefaultMutableTreeNode(line.substring(2))); + } + break; + case 'R': + if (artist != null) { + artist.add(record = new DefaultMutableTreeNode(line.substring(2))); + } + break; + case 'S': + if (record != null) { + record.add(new DefaultMutableTreeNode(line.substring(2))); + } + break; + default: + break; + } + line = reader.readLine(); + } + } catch (IOException ignored) { + } + + JTree tree = new JTree(top) { + @Override + public Insets getInsets() { + return new Insets(5, 5, 5, 5); + } + }; + + tree.setEditable(true); + + return tree; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tree/resources/TreeDemo.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tree/resources/TreeDemo.properties Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,8 @@ +### Tree Demo ### + +TreeDemo.accessible_description=This demo shows shows a sample usage of a JTree component. +TreeDemo.tooltip=JTree demo +TreeDemo.name=Tree Demo +TreeDemo.music=Music + + diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tree/resources/images/TreeDemo.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tree/resources/images/TreeDemo.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tree/resources/tree.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/tree/resources/tree.txt Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,628 @@ +################################################################################ +# Note: do not add blank lines, the data parser in TreeDemo.java cannot # +# handle them. # +# # +# Key: # +# Popular / Classical # +# ---------------------------- # +# A = Artist / Composer # +# R = Record / Style # +# S = Song Name / Composition # +# C = Catagory # +# # +################################################################################ +C Classical +A Beethoven +R concertos +S No. 1 - C +S No. 2 - B-Flat Major +S No. 3 - C Minor +S No. 4 - G Major +S No. 5 - E-Flat Major +R Quartets +S Six String Quartets +S Three String Quartets +S Grosse Fugue for String Quartets +R Sonatas +S Sonata in A Minor +S Sonata in F Major +R Symphonies +S No. 1 - C Major +S No. 2 - D Major +S No. 3 - E-Flat Major +S No. 4 - B-Flat Major +S No. 5 - C Minor +S No. 6 - F Major +S No. 7 - A Major +S No. 8 - F Major +S No. 9 - D Minor +A Brahms +R Concertos +S Violin Concerto +S Double Concerto - A Minor +S Piano Concerto No. 1 - D Minor +S Piano Concerto No. 2 - B-Flat Major +R Quartets +S Piano Quartet No. 1 - G Minor +S Piano Quartet No. 2 - A Major +S Piano Quartet No. 3 - C Minor +S String Quartet No. 3 - B-Flat Minor +R Sonatas +S Two Sonatas for Clarinet - F Minor +S Two Sonatas for Clarinet - E-Flat Major +R Symphonies +S No. 1 - C Minor +S No. 2 - D Minor +S No. 3 - F Major +S No. 4 - E Minor +A Mozart +R Concertos +S Piano Concerto No. 12 +S Piano Concerto No. 17 +S Clarinet Concerto +S Violin Concerto No. 5 +S Violin Concerto No. 4 +C Jazz +A Albert Ayler +R My Name is Albert Ayler +S Bye Bye Blackbird +S Billie's Bounce +S Summertime +S On Green Dolphin Street +S C.T. +R Swing Low Sweet Spiritual +S Goin' Home +S Old Man River +S When The Saints Go Marching In +S Deep River +S Down By The Riverside +S Spirits +S Witches and Devils +S Holy, Holy +S Saints +R Prophesy +S Spirits +S Wizard +S Ghosts +S Prophecy +R New Grass +S Free At Last +S Everybody's Movin' +S New Generation +S Heart Love +S Sun Watcher +A Chet Baker +R Sings and Plays +S Let's Get Lost +S This Is Always +S Long Ago and Far Away +S I Wish I Knew +S Daybreak +S Grey December +S I Remember You +R My Funny Valentine +S My Funny Valentine +S Someone To Watch Over Me +S Moonlight Becomes You +S I'm Glad There is You +S This is Always +S Time After Time +S Sweet Lorraine +S It's Always You +S Moon Love +S Like Someone In Love +S I've Never Been In Love Before +S Isn't it Romantic +S I Fall In Love Too Easily +R Grey December +S Grey December +S I Wish I Knew +S Someone To Watch Over Me +S Headline +S Bockhanal +S A Dandy Line +S Pro Defunctus +S Little Old Lady +S Goodbye +R The Route +S Tynan Time +S The Route +S Minor Yours +S Little Girl +S Ol' Croix +S The Great Lie +S Sweet Lorrain +S If I Should Lose You +A John Coltrane +R Blue Train +S Blue Train +S Moment's Notice +S Locomotion +S I'm Old Fashioned +S Lazy Bird +R Giant Steps +S Giant Steps +S Cousin Mary Steps +S Countdown +S Spiral +S Syeeda's Song Flute +S Naima +S Mr. P.C. +R My Favorite Things +S My Favorite Things +S Everytime We Say Goodbye +S Summertime +S But Not For Me +R Crescent +S Crescent +S Wise One +S Bessie's Blues +S Lonnie's Lament +S The Drum Thing +R Interstellar Space +S Mars +S Leo +S Venus +S Jupiter Variation +S Jupiter +S Saturn +A Miles Davis +R Transition +S Autumn Leaves +S Two Bass Hit +S Love, I've Found You +S I Thought About You +S All Blues +S Seven Steps To Heaven +R Quiet Nights +S Once Upon a Summertime +S Aos Pes Da Cruz +S Wait Till You See Her +S Corcovado +S Summer Nights +R My Funny Valentine +S All of You +S Stella By Starlight +S All Blues +S I Thought About You +R Voodoo Down +S Automn Leaves +S Footprints +S Directions +S Bitches Brew +S Hush +C Rock +A The Beatles +R A Hard Day's Night +S A Hard Day's Night +S I Should Have Known Better +S If I Fell +S I'm Happy Just To Dance With You +S And I Love Her +S Tell Me Why +S Can't Buy Me Love +S Any Time At All +S I'll Cry Instead +S Things We Said Today +S When I Get Home +S You Can't Do That +R Beatles For Sale +S No Reply +S I'm a Loser +S Baby's In Black +S Rock And Roll Music +S I'll Follow the Sun +S Mr. Moonlight +S Kansas City/Hey Hey Hey Hey +S Eight Days a Week +S Words Of Love +S Honey Don't +S Every Little Thing +S I Don't Want To Spoil the Party +S What You're Doing +S Everybody's Trying To Be My Baby +R Help! +S Help! +S The Night Before +S You've Got To Hide Your Love Away +S I Need You +S Another Girl +S You're Going To Lose That Girl +S Ticket To Ride +S Act Naturally +S It's Only Love +S You Like Me Too Much +S Tell Me What You See +S I've Just Seen a Face +S Yesterday +S Dizzy Miss Lizzie +R Rubber Soul +S Drive My Car +S Norwegian Wood +S You Won't See Me +S Nowhere Man +S Think For Yourself +S The Word +S Michelle +S What Goes On? +S Girl +S I'm Looking Through You +S In My Life +S Wait +S If I Needed Someone +S Run For Your Life +R Revolver +S Taxman +S Rigby +S I'm Only Sleeping +S For You To +S Here There And Everywhere +S Yellow Submarine +S She Said She Said +S Good Day Sunshine +S And Your Bird Can Sing +S For No One +S Doctor Robert +S I Want To Tell You +S Got To Get You Into My Life +S Tomorrow Never Knows +R Sgt. Pepper's Lonely Hearts Club Band +S Sgt. Pepper's Lonely Hearts Club Band +S With a Little Help From My Friends +S Lucy in the Sky With Diamonds +S Getting Better +S Fixing a Hole +S She's Leaving Home +S Being For the Benefit of Mr. Kite +S Within You Without You +S When I'm Sixty Four +S Lovely Rita +S Good Morning +S Sgt. Pepper's Reprise +S A Day In The Life +R Magical Mystery Tour +S Magical Mystery Tour +S Fool on the Hill +S Flying +S Blue Jay Way +S Your Mother Should Know +S I Am The Walrus +S Hello Goodbye +S Strawberry Fields Forever +S Penny Lane +S Baby You're a Rich Man +S All You Need Is Love +R The White Album +S Back in the USSR +S Dear Prudence +S Glass Onion +S Wild Honey Pie +S Bungalow Bill +S While My Guitar Gently Weeps +S Martha My Dear +S I'm So Tired +S Blackbird +S Piggies +S Rocky Raccoon +S Don't Pass Me By +S Why Don't We Do It In The Road +S I Will +S Julia +S Birthday +S Yer Blues +S Mother Nature's Son +S Sexy Sadie +S Helter Skelter +S Long Long Long +S Revolution 1 +S Honey Pie +S Savoy Truffle +S Cry Baby Cry +S Revolution 9 +S Good Night +R Abbey Road +S Come Together +S Something +S Maxwell's Silver Hammer +S Octopus's Garden +S She's So Heavy +S Here Comes The Sun +S Because +S You Never Give Me Your Money +S Sun King +S Mean Mr. Mustard +S Polythene Pam +S She Came In Through The Bathroom Window +S Golden Slumbers +S Carry That Weight +S The End +S Her Majesty +R Let It Be +S Two of Us +S Dig A Pony +S Across the Universe +S I Me Mine +S Dig It +S Let It Be +S Maggie Mae +S I've Got A Feeling +S One After 909 +S The Long and Winding Road +S For You Blue +S Get Back +A Crowded House +R Crowded House +S Mean To Me +S World Where You Live +S Now We're Getting Somewhere +S Don't Dream It's Over +S Love You Til The Day I Die +S Something So Strong +S Hole In The River +S Can't Carry On +S I Walk Away +S Tombstone +S That's What I Call Live +R Temple of Low Men +S I Feel Possessed +S Kill Eye +S Into Temptation +S Mansion In The Slums +S When You Come +S Never Be The Same +S Love This Life +S Sister Madly +S In The Lowlands +S Better Be Home Soon +R Woodface +S Chocolate Cake +S It's Only Natural +S Fall At Your Feet +S Tall Trees +S Weather With You +S Whispers and Moans +S Four Seasons in One Day +S There Goes God +S Fame Is +S All I Ask +S As Sure As I Am +S Italian Plastic +S She Goes On +S How Will You Go +R Together Alone +S Kare Kare +S In My Command +S Nails In My Feet +S Black & White Boy +S Fingers of Love +S Pineapple Head +S Locked Out +S Private Universe +S Walking on the Spot +S Distant Sun +S Catherine Wheels +S Skin Feeling +S Together Alone +A The Fixx +R Shuttered Room +S Some People +S Stand or Fall +S Cameras In Paris +S Shuttered Room +S The Fool +S Lost Planes +S I Live +S Sinking Island +S Time in a Glass +S Red Skies +R Reach The Beach +S One Thing Leads To Another +S The Sign of Fire +S Running +S Saved By Zero +S Opinions +S Reach The Beach +S Changing +S Liner +S Privilege +S Outside +R Phantoms +S Lose Face +S Less Cities, More Moving People +S Sunshine in the Shade +S Woman on a Train +S Wish +S Lost in Battle Overseas +S Question +S In Suspense +S Facing the Wind +S Are We Ourselves +S I Will +S Phantom Living +R Walkabout +S Secret Separation +S Built for the Future +S Treasure It +S Can't Finish +S Walkabout +S One Look Up +S Read Between The Lines +S Sense The Adventure +S Camphor +S Peace On Earth/Do What You Can +R Calm Animals +S I'm Life +S Driven Out +S Subterranean +S Precious Stone +S Gypsy Feet +S Calm Animals +S Shred of Evidence +S The Flow +S World Weary +S Caused To Be Alarmed +R Ink +S All is Fair +S How much Is Enough +S No One Has To Cry +S Crucified +S Falling In Love +S Shut It Out +S Still Around +S All The Best Things +S Yesterday, Today +S One Jungle +S Climb The Hill +S Make No Plans +R Elemental +S Two Different Views +S Going Without +S Is That It? +S Happy Landings +S Silent House +S Fatal Shore +S Ocean Blue +S You Know Me +S We Once Held Hands +S Life's What's Killing Me +A Harvin Garvel +R Harvin Garvel I +S Body +S What You Said +S All Rights Reserved +S High Purity +S Lies +S Get Real +S Gradma Cries +S First Feel +S Somethings wrong +S Shoes +S Spice Rack +S Dark Feel +S Tug of War +S Ant Song +R Harvin Garvel II +S We Ain't Through +S Trash and Spend +S Kick +S The Garden +S One & Only +S Squid Frenzy +S Soul In Soul +S The Desert +S He Grew Up +S Talk +S Image +S Tomorrow +S R70 +R Full Grown Dog +S I Am +S Say +S Is This Real +S What She Said +S Mirror Lies +S Girls +S Your Will +S Slow Motion Sunday +S Simple Life +S The Road Song +S The Same Way +S Stop Tryin +R Persia +S Exonic +S Drift +S Cruise +S MugWump +S Smear +S Everything +S Keep +S Circle +R Sensative Beak +S Whatcha Gotta Do +S Somewhere In This World +S Awaken +S Just A Dog +S I Can Dance +S Tomorrow +S Love Who? +S Is There Something +S I Like It +S Easy Chair +S As We Are One +S Far Away +S Leaving Science +S What A Life +A Komeda +R Plan 714 Till +S Fuego De La Vida +S Herbamore +S Som I Fjol +S En Spricka I Taket +R Genius Of +S More Is More +S Fire +S Rocket Plane (Music On The Moon) +S Boogie Woogie/Rock 'N' Roll +S Disko +S Top Star +S Light O' My Life +S If +S Frolic +S In Orbit +S Arbogast +S New New No +R What Makes It Go +S Binario +S It's Alright, Baby +S Curious +S Cul de Sac +S Living Things +S Flabbergast +S Campfire +S Happyment +S Our Hospitality +S Focus +S A Simple Formality +A Steve Miller Band +R Circle Of Love +S Heart Like A Wheel +S Get On Home +S Baby Wanna Dance +S Circle Of Love +S Macho City +R Fly Like An Eagle +S Space Intro +S Fly Like An Eagle +S Wild Mountain Honey +S Serenade +S Dance, Dance, Dance +S Mercury Blues +S Take the Money and Run +S Rockin' Me +S You Send Me +S Blue Odyssey +S Sweet Maree +S The Window +R Book Of Dreams +S Threshold +S Jet Airliner +S Winter Time +S Swingtown +S True Fine Love +S Wish Upon A Star +S Jungle Love +S Electrolux Imbroglio +S Sacrifice +S The Stake +S My Own Space +S Babes In The Wood +R Joker +S Sugar, Babe +S Mary Lou +S Shu Ba Da Du Ma +S Your Cash Ain't Nothin' But Trash +S The Joker +S The Lovin' Cup +S Come On In My Kitchen +S Evil +S Something To Believe In diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/window/WindowDemo.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/window/WindowDemo.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package com.sun.swingset3.demos.window; + +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.*; +import javax.swing.border.EmptyBorder; +import javax.swing.border.LineBorder; + +import com.sun.swingset3.DemoProperties; +import com.sun.swingset3.demos.DemoUtilities; + +/** + * @author aim + */ +@DemoProperties( + value = "JWindow Demo", + category = "Toplevel Containers", + description = "Demonstrates JWindow, a toplevel container with no system border.", + sourceFiles = { + "com/sun/swingset3/demos/window/WindowDemo.java", + "com/sun/swingset3/demos/DemoUtilities.java", + "com/sun/swingset3/demos/window/resources/WindowDemo.html", + "com/sun/swingset3/demos/window/resources/images/WindowDemo.gif" + } +) +public final class WindowDemo extends JPanel { + + public static final String SHOW_J_WINDOW = "Show JWindow..."; + public static final String I_HAVE_NO_SYSTEM_BORDER = "I have no system border."; + + private JWindow window; + + private JComponent windowSpaceholder; + + public WindowDemo() { + initComponents(); + } + + protected void initComponents() { + window = createWindow(); + + setLayout(new BorderLayout()); + add(createControlPanel(), BorderLayout.WEST); + windowSpaceholder = createWindowSpaceholder(window); + add(windowSpaceholder, BorderLayout.CENTER); + } + + protected JComponent createControlPanel() { + Box controlPanel = Box.createVerticalBox(); + controlPanel.setBorder(new EmptyBorder(8, 8, 8, 8)); + + // Create button to control visibility of frame + JButton showButton = new JButton(SHOW_J_WINDOW); + showButton.addActionListener(new ShowActionListener()); + controlPanel.add(showButton); + + return controlPanel; + } + + private static JComponent createWindowSpaceholder(JWindow window) { + JPanel windowPlaceholder = new JPanel(); + Dimension prefSize = window.getPreferredSize(); + prefSize.width += 12; + prefSize.height += 12; + windowPlaceholder.setPreferredSize(prefSize); + + return windowPlaceholder; + } + + private static JWindow createWindow() { + + //Create window + JWindow window = new JWindow(); + // + + //Add a border to the window + window.getRootPane().setBorder(new LineBorder(Color.BLACK, 1)); + // + + //Add window's content + JLabel label = new JLabel(I_HAVE_NO_SYSTEM_BORDER); + label.setHorizontalAlignment(JLabel.CENTER); + label.setPreferredSize(new Dimension(250, 200)); + window.add(label); + // + + //Initialize window's size + // which will shrink-to-fit its contents + window.pack(); + // + + return window; + } + + public void start() { + DemoUtilities.setToplevelLocation(window, windowSpaceholder, SwingConstants.CENTER); + showWindow(); + } + + public void stop() { + //Hide window + window.setVisible(false); + // + } + + public void showWindow() { + //Show window + // if window already visible, then bring to the front + if (window.isShowing()) { + window.toFront(); + } else { + window.setVisible(true); + } + // + } + + private class ShowActionListener implements ActionListener { + + @Override + public void actionPerformed(ActionEvent actionEvent) { + showWindow(); + } + } + + public static void main(String args[]) { + EventQueue.invokeLater(() -> { + JFrame frame = new JFrame(); + WindowDemo demo = new WindowDemo(); + frame.add(demo); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.pack(); + frame.setVisible(true); + demo.start(); + }); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/window/resources/WindowDemo.html --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/window/resources/WindowDemo.html Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,36 @@ + + + + + + +

+ Show how Swing's top-level container, + JWindow, can be used to create areas on the screen which + do not have system-supplied borders and therefore cannot be moved or resized + by the user like frames or dialogs. JWindow is commonly used to implement menus, + tooltips, and popups. +

+ + diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/window/resources/images/WindowDemo.gif Binary file jdk/test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/window/resources/images/WindowDemo.gif has changed diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/README --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/README Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,3 @@ +This src folder contains a copy of Jemmy 2 library sources from https://jemmy.java.net/. + +Do NOT modify files in it. \ No newline at end of file diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Action.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Action.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy; + +/** + * + * Defines an action to be executed by {@code ActionProducer} instance. + * + * @see org.netbeans.jemmy.ActionProducer + * + * @author Alexandre Iline (alexandre.iline@oracle.com) + */ +public interface Action { + + /** + * Executes this action. + * + * @param obj action argument. This argument might be the method parameter + * in an invocation of {@code ActionProducer.produceAction(Object)}. + * @return action result. + */ + public R launch(P obj); + + /** + * Returns the description value. + * + * @return Action description. + */ + public String getDescription(); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/ActionProducer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/ActionProducer.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,335 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy; + +import java.util.Optional; + +/** + * + * 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@oracle.com) + */ +public class ActionProducer extends Thread + implements Action, Waitable, P>, Timeoutable { + + private final static long ACTION_TIMEOUT = 10000; + + private Action action; + private boolean needWait = true; + private P parameter; + private boolean finished; + private R result = null; + private Timeouts timeouts; + private Waiter, P> 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 {@code 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. {@code 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. {@code produceAction} must be overridden. + * + * @param nw Defines if {@code 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 + */ + @Override + 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 + */ + @Override + 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 | SecurityException e) { + e.printStackTrace(); + } + } + + /** + * Get the result of a launched action. + * + * @return a launched action's result. without waiting in case if + * {@code getFinished()} + * @see #getFinished() + */ + public R getResult() { + return result; + } + + /** + * Check if a launched action has finished. + * + * @return {@code true} if the launched action has completed, either + * normally or with an exception; {@code 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 + * {@code java.lang.String[]} that lists a test's command line + * arguments. + * @return An object - result of the action. + * @see org.netbeans.jemmy.Action + */ + @Override + public R launch(P obj) { + return null; + } + + /** + * @return this {@code ActionProducer}'s description. + * @see Action + */ + @Override + 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 + * {@code launch(Object)} method. This parameter might be a + * {@code java.lang.String[]} that lists a test's command line + * arguments. + * @param actionTimeOrigin is used for timeout reporting, if non-null. + * @return {@code launch(Object)} result. + * @throws TimeoutExpiredException + * @exception InterruptedException + */ + public R produceAction(P obj, String actionTimeOrigin) throws InterruptedException { + parameter = obj; + synchronized (this) { + finished = false; + } + start(); + if (needWait) { + waiter.setTimeoutsToCloneOf(timeouts, "ActionProducer.MaxActionTime", actionTimeOrigin); + 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 {@code getFinished()} and {@code getResult} to + * answer questions about test completion and return value, respectively. + * + * @see #getFinished() + * @see #getResult() + * @see java.lang.Runnable + */ + @Override + 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 + */ + @Override + public final Optional actionProduced(P obj) { + synchronized (this) { + if (finished) { + return Optional.ofNullable(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 + * {@code ActionProducer} puts into execution. + * @return the return value of the action. + */ + private R launchAction(P obj) { + if (action != null) { + return action.launch(obj); + } else { + return launch(obj); + } + } + + @Override + public String toString() { + return "ActionProducer{" + "action=" + action + ", needWait=" + needWait + ", parameter=" + parameter + ", finished=" + finished + ", result=" + result + ", exception=" + exception + '}'; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Bundle.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Bundle.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,147 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 + * {@code name=value} format. + * + * @see org.netbeans.jemmy.BundleManager + * + * @author Alexandre Iline (alexandre.iline@oracle.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 { + try (FileInputStream fileInputStream = new FileInputStream(fileName)) { + load(fileInputStream); + } + } + + /** + * 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 { + try (JarFile jFile = new JarFile(fileName); + InputStream inputStream = jFile.getInputStream(jFile.getEntry(entryName))) { + load(inputStream); + } + } + + /** + * 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 { + try (ZipFile zFile = new ZipFile(fileName); + InputStream inputStream = zFile.getInputStream(zFile.getEntry(entryName))) { + load(inputStream); + } + } + + /** + * 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); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/BundleManager.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/BundleManager.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,292 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class BundleManager { + + private Hashtable bundles; + + /** + * Bundle manager constructor. + */ + public BundleManager() { + bundles = new Hashtable<>(); + try { + load(); + } catch (IOException ignored) { + } + } + + /** + * 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 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 + * {@code 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 = 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 = 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 (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; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/CharBindingMap.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/CharBindingMap.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 {@code CharBindingMap} communicate what modifiers and + * primary key are required to generate a given symbol. + * + * @see org.netbeans.jemmy.DefaultCharBindingMap + * + * @author Alexandre Iline (alexandre.iline@oracle.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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/ClassReference.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/ClassReference.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,227 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 {@code main(java.lang.String[])} method with a + * zero-length {@code 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 {@code main(java.lang.String[])} method. + * + * @param params The {@code java.lang.String} array to pass to + * {@code 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 | 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 {@code method_name} method is void, {@code null} is + * returned.
+ * If {@code 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 {@code 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; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/ComponentChooser.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/ComponentChooser.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public interface ComponentChooser { + + /** + * Check if the component argument meets the search criteria. + * + * @param comp Component to check. + * @return {@code true} when the component conforms to the search + * criteria; {@code false} otherwise. + */ + public boolean checkComponent(Component comp); + + /** + * Returns searched component description. + * + * @return a String representing the description value + */ + public String getDescription(); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/ComponentIsNotFocusedException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/ComponentIsNotFocusedException.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class ComponentIsNotFocusedException extends JemmyInputException { + + private static final long serialVersionUID = 42L; + + /** + * Constructs a ComponentIsNotFocusedException object. + * + * @param comp a Component. + */ + public ComponentIsNotFocusedException(Component comp) { + super("Component do not have focus", comp); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/ComponentIsNotVisibleException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/ComponentIsNotVisibleException.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class ComponentIsNotVisibleException extends JemmyInputException { + + private static final long serialVersionUID = 42L; + + /** + * Constructs a ComponentIsNotVisibleException object. + * + * @param comp a Component. + */ + public ComponentIsNotVisibleException(Component comp) { + super("Component is not visible", comp); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/ComponentSearcher.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/ComponentSearcher.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,255 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy; + +import java.awt.Component; +import java.awt.Container; +import java.util.Vector; + +/** + * + * Contains methods to search for components below a a given + * {@code java.awt.Container} in the display containment hierarchy. Uses a + * {@code ComponentChooser} interface implementation to find a component. + * + * @see ComponentChooser + * + * @author Alexandre Iline (alexandre.iline@oracle.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 {@code ComponentChooser} implementation whose + * {@code checkComponent(Component)} method returns {@code 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; + } + + @Override + public boolean checkComponent(Component comp) { + return true; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public String toString() { + return "TrueChooser{" + "description=" + 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 + */ + @Override + 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 + */ + @Override + 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" + : queueTool.invokeSmoothly( + new QueueTool.QueueAction("container.toString()") { + @Override + public String launch() { + return container.toString(); + } + } + ); + } + return containerToString; + } + + /** + * Searches for a component. The search for the component proceeds + * recursively in the component hierarchy rooted in this + * {@code ComponentChooser}'s container. + * + * @param chooser ComponentChooser instance, defining and applying the + * search criteria. + * @param index Ordinal component index. Indices start at 0. + * @return the {@code index}'th component from among those components + * for which the chooser's {@code checkComponent(Component)} method + * returns {@code true}. A {@code null} reference is returned if + * there are fewer than {@code index-1} components meeting the search + * criteria exist in the component hierarchy rooted in this + * {@code ComponentChooser}'s container. + */ + public Component findComponent(ComponentChooser chooser, int index) { + ordinalIndex = 0; + final Component result = findComponentInContainer(container, chooser, index, null); + if (result != null) { + // get result.toString() - run in dispatch thread + String resultToString = queueTool.invokeSmoothly( + new QueueTool.QueueAction("result.toString()") { + @Override + public String 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 + * {@code ComponentChooser}'s container. + * + * @param chooser ComponentChooser instance, defining and applying the + * search criteria. + * @return the first component for which the chooser's + * {@code checkComponent(Component)} method returns {@code true}. + * A {@code null} reference is returned if no component meeting the + * search criteria exist in the component hierarchy rooted in this + * {@code ComponentChooser}'s container. + */ + public Component findComponent(ComponentChooser chooser) { + return findComponent(chooser, 0); + } + + /** + * Searches for all components. The search for the components proceeds + * recursively in the component hierarchy rooted in this + * {@code ComponentChooser}'s container. + * + * @param chooser ComponentChooser instance, defining and applying the + * search criteria. + * @return the components for which the chooser's + * {@code checkComponent(Component)} method returns {@code true}. + * An empty array is returned if no component meeting the search criteria + * exists in the component hierarchy rooted in this + * {@code ComponentChooser}'s container. + */ + public Component[] findComponents(ComponentChooser chooser) { + Vector allSeen = new Vector<>(); + findComponentInContainer(container, chooser, 0, allSeen); + Component[] result = new Component[allSeen.size()]; + for (int i = 0, n = allSeen.size(); i < n; i++) { + result[i] = allSeen.get(i); + } + return result; + } + + private Component findComponentInContainer(final Container cont, final ComponentChooser chooser, final int index, + final Vector allSeen) { + return queueTool.invokeSmoothly(new QueueTool.QueueAction("findComponentInContainer with " + chooser.getDescription()) { + + @Override + public Component launch() throws Exception { + Component[] components = cont.getComponents(); + Component target; + for (Component component : components) { + if (component != null) { + if (chooser.checkComponent(component)) { + if (allSeen != null) { + allSeen.add(component); + } else if (ordinalIndex == index) { + return component; + } else { + ordinalIndex++; + } + } + if (component instanceof Container) { + if ((target = findComponentInContainer((Container) component, + chooser, index, allSeen)) != null) { + return target; + } + } + } + } + return null; + } + }); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/DefaultCharBindingMap.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/DefaultCharBindingMap.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,201 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 + */ + @Override + 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 + */ + @Override + 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 = chars.get(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] = keys.nextElement(); + } + return charArray; + } + + /** + * Removes a char from supported. + * + * @param c Symbol code. + */ + public void removeChar(char c) { + chars.remove(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(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 (Field field : fields) { + String name = field.getName(); + if ((field.getModifiers() & Modifier.PUBLIC) != 0 + && (field.getModifiers() & Modifier.STATIC) != 0 + && field.getType() == Integer.TYPE + && name.startsWith("VK_") + && name.length() == 4) { + String latter = name.substring(3, 4); + try { + int key = field.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) { + throw new AssertionError("Never could happen!", e); + } + } + } + //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; + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/DialogWaiter.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/DialogWaiter.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,672 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 Dialog 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 + * displayed
+ * + * @see org.netbeans.jemmy.Timeouts + * + * @author Alexandre Iline (alexandre.iline@oracle.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 + * {@code 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 {@code 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 {@code index+1}'th dialog that meets the criteria + * defined and applied by the {@code 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 {@code index+1}'th dialog that is showing + * and that meets the search criteria. If there are fewer than + * {@code index+1} dialogs, a {@code 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 {@code true} and the search is case sensitive, then a + * match occurs when the {@code title} argument is a substring of a + * dialog title. If {@code false} and the search is case sensitive, + * then the {@code title} argument and the dialog title must be the + * same. If {@code true} and the search is case insensitive, then a + * match occurs when the {@code title} argument is a substring of the + * dialog title after changing both to upper case. If {@code false} and + * the search is case insensitive, then a match occurs when the + * {@code title} argument is a substring of the dialog title after + * changing both to upper case. + * @param cc If {@code 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 {@code 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 + * {@code index+1}'th dialog among the currently showing dialogs that + * possess a suitable title. + * + * @param title Dialog title or subtitle. + * @param ce If {@code true} and the search is case sensitive, then a + * match occurs when the {@code title} argument is a substring of a + * dialog title. If {@code false} and the search is case sensitive, + * then the {@code title} argument and the dialog title must be the + * same. If {@code true} and the search is case insensitive, then a + * match occurs when the {@code title} argument is a substring of the + * dialog title after changing both to upper case. If {@code false} and + * the search is case insensitive, then a match occurs when the + * {@code title} argument is a substring of the dialog title after + * changing both to upper case. + * @param cc If {@code true} the search is case sensitive; otherwise, + * the search is case insensitive. + * @param index Ordinal index between appropriate dialogs + * @return a reference to the {@code index+1}'th dialog that is showing + * and that has a suitable title. If there are fewer than + * {@code index+1} dialogs, a {@code 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 {@code java.awt.Window} + * {@code owner} and that meets the search criteria applied by the + * {@code 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 {@code 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 {@code index+1}'th dialog that is both owned by the + * {@code java.awt.Window} {@code owner} and that meets the + * criteria defined and applied by the {@code 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 {@code index+1}'th dialog that is + * showing, has the proper window ownership, and that meets the search + * criteria. If there are fewer than {@code index+1} dialogs, a + * {@code 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 {@code java.awt.Window} + * {@code 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 {@code true} and the search is case sensitive, then a + * match occurs when the {@code title} argument is a substring of a + * dialog title. If {@code false} and the search is case sensitive, + * then the {@code title} argument and the dialog title must be the + * same. If {@code true} and the search is case insensitive, then a + * match occurs when the {@code title} argument is a substring of the + * dialog title after changing both to upper case. If {@code false} and + * the search is case insensitive, then a match occurs when the + * {@code title} argument is a substring of the dialog title after + * changing both to upper case. + * @param cc If {@code 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 + * {@code 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 + * {@code index+1}'th dialog among the currently showing dialogs that + * are owned by the {@code java.awt.Window} {@code owner} and that + * have a suitable title. + * + * @param owner ?title? Dialog title or subtitle. + * @param title ?ce? If {@code true} and the search is case sensitive, + * then a match occurs when the {@code title} argument is a substring + * of a dialog title. If {@code false} and the search is case + * sensitive, then the {@code title} argument and the dialog title must + * be the same. If {@code true} and the search is case insensitive, + * then a match occurs when the {@code title} argument is a substring + * of the dialog title after changing both to upper case. If + * {@code false} and the search is case insensitive, then a match + * occurs when the {@code title} argument is a substring of the dialog + * title after changing both to upper case. + * @param ce ?cc? If {@code 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 {@code index+1}'th dialog that is + * showing, has the proper window ownership, and a suitable title. If there + * are fewer than {@code index+1} dialogs, a {@code 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 + */ + @Override + 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 + */ + @Override + 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 + */ + @Override + 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 + */ + @Override + public TestOut getOutput() { + return output; + } + + /** + * Waits for a dialog to show. Wait for the {@code index+1}'th dialog + * that meets the criteria defined and applied by the + * {@code 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 {@code index+1}'th dialog that shows and + * that meets the search criteria. If fewer than {@code index+1} + * dialogs show up in the allotted time period then a {@code 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 {@code 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 {@code 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 {@code index+1}'th dialog + * to show with a suitable title. + * + * @param title Dialog title or subtitle. + * @param compareExactly If {@code true} and the search is case + * sensitive, then a match occurs when the {@code title} argument is a + * substring of a dialog title. If {@code false} and the search is case + * sensitive, then the {@code title} argument and the dialog title must + * be the same. If {@code true} and the search is case insensitive, + * then a match occurs when the {@code title} argument is a substring + * of the dialog title after changing both to upper case. If + * {@code false} and the search is case insensitive, then a match + * occurs when the {@code title} argument is a substring of the dialog + * title after changing both to upper case. + * @param compareCaseSensitive If {@code 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 {@code 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 {@code 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 {@code true} and the search is case + * sensitive, then a match occurs when the {@code title} argument is a + * substring of a dialog title. If {@code false} and the search is case + * sensitive, then the {@code title} argument and the dialog title must + * be the same. If {@code true} and the search is case insensitive, + * then a match occurs when the {@code title} argument is a substring + * of the dialog title after changing both to upper case. If + * {@code false} and the search is case insensitive, then a match + * occurs when the {@code title} argument is a substring of the dialog + * title after changing both to upper case. + * @param compareCaseSensitive If {@code 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 + * {@code 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 {@code index+1}'th dialog + * to show that is both owned by the {@code java.awt.Window} + * {@code owner} and that meets the criteria defined and applied by the + * {@code 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 {@code index+1}'th dialog to show that + * has the proper window ownership, and that meets the search criteria. If + * there are fewer than {@code index+1} dialogs, a {@code 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 {@code java.awt.Window} {@code owner} and + * that meets the criteria defined and applied by the + * {@code 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 {@code 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 {@code 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 {@code true} and the search is case + * sensitive, then a match occurs when the {@code title} argument is a + * substring of a dialog title. If {@code false} and the search is case + * sensitive, then the {@code title} argument and the dialog title must + * be the same. If {@code true} and the search is case insensitive, + * then a match occurs when the {@code title} argument is a substring + * of the dialog title after changing both to upper case. If + * {@code false} and the search is case insensitive, then a match + * occurs when the {@code title} argument is a substring of the dialog + * title after changing both to upper case. + * @param compareCaseSensitive If {@code true} the search is case + * sensitive; otherwise, the search is case insensitive. + * @param index Ordinal index between appropriate dialogs + * @return a reference to the {@code 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 {@code 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 {@code true} and the search is case + * sensitive, then a match occurs when the {@code title} argument is a + * substring of a dialog title. If {@code false} and the search is case + * sensitive, then the {@code title} argument and the dialog title must + * be the same. If {@code true} and the search is case insensitive, + * then a match occurs when the {@code title} argument is a substring + * of the dialog title after changing both to upper case. If + * {@code false} and the search is case insensitive, then a match + * occurs when the {@code title} argument is a substring of the dialog + * title after changing both to upper case. + * @param compareCaseSensitive If {@code 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 {@code 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() + */ + @Override + 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. + */ + @Override + protected String getTimeoutExpiredMessage(long spendedTime) { + return ("Dialog \"" + getComponentChooser().getDescription() + "\" has not been opened in " + + spendedTime + " 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. + */ + @Override + protected String getActionProducedMessage(long spendedTime, final Object result) { + String resultToString; + if (result instanceof Component) { + // run toString in dispatch thread + resultToString = new QueueTool().invokeSmoothly( + new QueueTool.QueueAction("result.toString()") { + @Override + public String launch() { + return result.toString(); + } + } + ); + } else { + resultToString = result.toString(); + } + return ("Dialog \"" + getComponentChooser().getDescription() + "\" has been opened in " + + spendedTime + " milliseconds" + + "\n " + resultToString); + } + + /** + * @see org.netbeans.jemmy.Waiter#getGoldenWaitingStartedMessage() + */ + @Override + protected String getGoldenWaitingStartedMessage() { + return "Start to wait dialog \"" + getComponentChooser().getDescription() + "\" opened"; + } + + /** + * @see org.netbeans.jemmy.Waiter#getGoldenTimeoutExpiredMessage() + */ + @Override + protected String getGoldenTimeoutExpiredMessage() { + return "Dialog \"" + getComponentChooser().getDescription() + "\" has not been opened"; + } + + /** + * @see org.netbeans.jemmy.Waiter#getGoldenActionProducedMessage() + */ + @Override + 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; + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof Dialog) { + return ((FIND_INVISIBLE_WINDOWS || (comp.isShowing() && comp.isVisible())) + && chooser.checkComponent(comp)); + } else { + return false; + } + } + + @Override + public String getDescription() { + return chooser.getDescription(); + } + + @Override + public String toString() { + return "DialogSubChooser{" + "chooser=" + chooser + '}'; + } + } + + 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; + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof Dialog) { + if ((FIND_INVISIBLE_WINDOWS || (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.contains(contextToComp); + } + } + } + return false; + } + + @Override + public String getDescription() { + return title; + } + + @Override + public String toString() { + return "DialogByTitleChooser{" + "title=" + title + ", compareExactly=" + compareExactly + ", compareCaseSensitive=" + compareCaseSensitive + '}'; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/EventDispatcher.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/EventDispatcher.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1134 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 {@code 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@oracle.com) + * + */ +public class EventDispatcher implements Outputable, Timeoutable { + + private static final long WAIT_QUEUE_EMPTY_TIMEOUT = 180000; + private static final long ROBOT_AUTO_DELAY = 10; + private static final long WAIT_COMPONENT_UNDER_MOUSE_TIMEOUT = 60000; + + private static Field[] keyFields; + private static volatile MotionListener motionListener = null; + + /** + * Component to dispatch events to. + */ + protected Component component; + private TestOut output; + private Timeouts timeouts; + private final ClassReference reference; + private int model; + private ClassReference robotReference = null; + private boolean outsider = false; + private final 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 {@code 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 {@code 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 {@code 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 {@code 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 ({@code KeyEvent.VK_*} value) + * @return the KeyEvent field name. + */ + public static String getKeyDescription(int keyCode) { + for (Field keyField : keyFields) { + try { + if (keyField.getName().startsWith("VK_") + && keyField.getInt(null) == keyCode) { + return keyField.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 ({@code 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 {@code java.awt.Robot} + * to generate mouse events. If a mouse press occurs at a position not + * occupied by a known Java component then a + * {@code NoComponentUnderMouseException} will be thrown. + * + * @param yesOrNo if {@code 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 + */ + @Override + 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 + */ + @Override + 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 + */ + @Override + 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 = {(int) timeouts.getTimeout("EventDispatcher.RobotAutoDelay")}; + Class[] paramClasses = {Integer.TYPE}; + robotReference.invokeMethod("setAutoDelay", params, paramClasses); + } catch (InvocationTargetException + | IllegalStateException + | NoSuchMethodException + | 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 + */ + @Override + 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 + | IllegalStateException + | NoSuchMethodException + | 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 {@code AWTEvent} to component passed in constructor. If + * {@code (getDispatchingModel & JemmyProperties.QUEUE_MODEL_MASK) == 0} + * dispatched event directly, otherwise uses + * {@code 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 = queueTool.invokeSmoothly( + new QueueTool.QueueAction("event.toString()") { + @Override + public String 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 {@code MouseEvent.MOUSE_*} value + * @param mods {@code InputEvent.MOUSE1/2/3_BUTTON} | (modifiers value) + * @param clickCount Click count + * @param x Horizontal click point coordinate. + * @param y vertical click point coordinate. + * @param popup Defines if mouse event is a 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 {@code MouseEvent.MOUSE_*} value + * @param mods {@code 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 {@code WindowEvent.WINDOW_*} value + */ + public void dispatchWindowEvent(int id) { + WindowEvent event = new WindowEvent((Window) component, id); + dispatchEvent(event); + } + + /** + * Dispatches KeyEvent. + * + * @see #dispatchEvent(AWTEvent) + * @param id {@code KeyEvent.KEY_PRESSED} or + * {@code KeyEvent.KEY_RELEASED} value. + * @param mods Modifiers. + * @param keyCode Key code, + */ + @Deprecated + 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 {@code 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 = {(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 = {getAbsoluteX(x), 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 = {button}; + Class[] paramClasses = {Integer.TYPE}; + makeRobotOperation("mousePress", params, paramClasses); + } + + /** + * Press mouse button with 0 modifiers. + * + * @param button Mouse button ({@code 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 ({@code 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 = {button}; + Class[] paramClasses = {Integer.TYPE}; + makeRobotOperation("mouseRelease", params, paramClasses); + robotReleaseModifiers(modifiers); + } + + /** + * Releases mouse button with 0 modifiers. + * + * @param button Mouse button ({@code InputEvent.MOUSE1/2/3_BUTTON} + * value) + * @see #robotReleaseMouse(int, int) + */ + public void robotReleaseMouse(int button) { + robotReleaseMouse(button, 0); + } + + /** + * Press a key using {@code java.awt.Robot}. + * + * @param keyCode Key ({@code 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 = {keyCode}; + Class[] paramClasses = {Integer.TYPE}; + makeRobotOperation("keyPress", params, paramClasses); + } + + /** + * Press key with no modifiers using {@code java.awt.Robot}. + * + * @param keyCode Key ({@code KeyEvent.VK_*} value) + * @see #robotPressKey(int, int) + */ + public void robotPressKey(int keyCode) { + robotPressKey(keyCode, 0); + } + + /** + * Releases key by robot. + * + * @param keyCode Key ({@code 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 = {keyCode}; + Class[] paramClasses = {Integer.TYPE}; + makeRobotOperation("keyRelease", params, paramClasses); + robotReleaseModifiers(modifiers); + } + + /** + * Releases key with 0 modifiers. + * + * @param keyCode Key ({@code KeyEvent.VK_*} value) + * @see #robotPressKey(int, int) + */ + public void robotReleaseKey(int keyCode) { + robotReleaseKey(keyCode, 0); + } + + /** + * Invokes component method through + * {@code 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) { + Exception ex = invk.getException(); + if (ex != null) { + if (ex instanceof InvocationTargetException) { + InvocationTargetException ite = (InvocationTargetException) ex; + ite.addSuppressed(e); + throw ite; + } else if (ex instanceof IllegalStateException) { + IllegalStateException ise = (IllegalStateException) ex; + ise.addSuppressed(e); + throw ise; + } else if (ex instanceof NoSuchMethodException) { + NoSuchMethodException nsme = (NoSuchMethodException) ex; + nsme.addSuppressed(e); + throw nsme; + } else if (ex instanceof IllegalAccessException) { + IllegalAccessException iae = (IllegalAccessException) ex; + iae.addSuppressed(e); + throw iae; + } else { + e.addSuppressed(ex); + } + } + throw (e); + } + } + + /** + * Gets component field value through + * {@code 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) { + Exception ex = gtr.getException(); + if (ex != null) { + if (ex instanceof InvocationTargetException) { + InvocationTargetException ite = (InvocationTargetException) ex; + ite.addSuppressed(e); + throw ite; + } else if (ex instanceof IllegalStateException) { + IllegalStateException ise = (IllegalStateException) ex; + ise.addSuppressed(e); + throw ise; + } else if (ex instanceof NoSuchFieldException) { + NoSuchFieldException nsfe = (NoSuchFieldException) ex; + nsfe.addSuppressed(e); + throw nsfe; + } else if (ex instanceof IllegalAccessException) { + IllegalAccessException iae = (IllegalAccessException) ex; + iae.addSuppressed(e); + throw iae; + } else { + e.addSuppressed(ex); + } + } + throw (e); + } + } + + /** + * Sets component field value through + * {@code 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) { + Exception ex = str.getException(); + if (ex != null) { + if (ex instanceof InvocationTargetException) { + InvocationTargetException ite = (InvocationTargetException) ex; + ite.addSuppressed(e); + throw ite; + } else if (ex instanceof IllegalStateException) { + IllegalStateException ise = (IllegalStateException) ex; + ise.addSuppressed(e); + throw ise; + } else if (ex instanceof NoSuchFieldException) { + NoSuchFieldException nsfe = (NoSuchFieldException) ex; + nsfe.addSuppressed(e); + throw nsfe; + } else if (ex instanceof IllegalAccessException) { + IllegalAccessException iae = (IllegalAccessException) ex; + iae.addSuppressed(e); + throw iae; + } else { + e.addSuppressed(ex); + } + } + throw (e); + } + } + + /** + * Invokes component method through + * {@code 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 + | IllegalStateException + | NoSuchMethodException + | IllegalAccessException e) { + out.printStackTrace(e); + } + return null; + } + + /** + * Gets component field value through + * {@code 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 + | IllegalStateException + | NoSuchFieldException + | IllegalAccessException e) { + out.printStackTrace(e); + } + return null; + } + + /** + * Sets component field value through + * {@code 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 + | IllegalStateException + | NoSuchFieldException + | IllegalAccessException e) { + out.printStackTrace(e); + } + } + + /** + * Invokes component method through + * {@code 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 + * {@code 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 + * {@code 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, newValue, 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 + | InstantiationException + | InvocationTargetException + | IllegalStateException + | NoSuchMethodException + | IllegalAccessException e) { + output.printStackTrace(e); + } + } + + private void waitMouseOver() { + try { + Waiter wt = new Waiter<>(new Waitable() { + @Override + public String actionProduced(Component obj) { + if (motionListener.getComponent() != null) { + return ""; + } else { + return null; + } + } + + @Override + public String getDescription() { + return "Mouse over component"; + } + + @Override + public String toString() { + return "waitMouseOver.Waiter{" + getDescription() + '}'; + } + }); + 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 + | IllegalStateException + | NoSuchMethodException + | 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() { + synchronized(EventDispatcher.class) { + 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] = getAbsoluteX(-1); + params[1] = getAbsoluteX(-1); + makeRobotOperation("mouseMove", params, paramClasses); + params[0] = getAbsoluteX(0); + params[1] = 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; + } + + @Override + public R 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; + } + + @Override + 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; + } + + @Override + 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; + } + + @Override + public Object launch() + throws InvocationTargetException, NoSuchFieldException, IllegalAccessException { + reference.setField(fieldName, newValue); + return null; + } + } + + private static class MotionListener implements AWTEventListener { + + private volatile Component mouseComponent; + + @Override + 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; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/EventTool.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/EventTool.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,538 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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. + * {@code 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. + * {@code 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 + * {@code removeListeners()} first, so any event history is lost. + * + * @param eventMask Mask to listen events under. + * {@code 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 + * {@code 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 {@code addListeners(long)} + * method. In case if {@code addListeners()} method was used last, + * {@code 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 {@code AWTEvent.*_EVENT_MASK} fields.. + * + * @return a combination of all {@code 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 + */ + @Override + 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 + */ + @Override + 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 + */ + @Override + 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 + */ + @Override + public TestOut getOutput() { + return output; + } + + /** + * Waits for the first event under mask. Waits during + * {@code EventTool.WaitEventTimeout} milliseconds. + * + * @param eventMask Mask to wait events under. + * {@code 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 + * {@code 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. + * {@code 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 {@code EventTool.WaitNoEventTimeout} time waits for true + * result of checkNoEvent(long, long) method. + * + * @param eventMask Mask to wait events under. + * {@code 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 {@code EventTool.WaitNoEventTimeout} time waits for true + * result of {@code 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 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; + } + + @Override + public void eventDispatched(AWTEvent event) { + eventRef = new WeakReference<>(event); + eventTime = System.currentTimeMillis(); + } + + public AWTEvent getEvent() { + return 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 (Field field : fields) { + if ((field.getModifiers() + & (Modifier.PUBLIC | Modifier.STATIC)) != 0 + && field.getType().equals(Long.TYPE) + && field.getName().endsWith("_EVENT_MASK")) { + eventMask = (Long) field.get(null); + eventTypes.add(new EventType(eventMask)); + theWholeMask = theWholeMask | eventMask; + } + } + } catch (ClassNotFoundException | IllegalAccessException e) { + JemmyProperties.getCurrentOutput().printStackTrace(e); + } + } + + public void addListeners(long eventMask) { + Toolkit dtk = Toolkit.getDefaultToolkit(); + for (EventType et : eventTypes) { + if ((et.getEventMask() & eventMask) != 0) { + dtk.addAWTEventListener(et, et.getEventMask()); + } + } + } + + public void addListeners() { + addListeners(getTheWholeMask()); + } + + public void removeListeners() { + Toolkit dtk = Toolkit.getDefaultToolkit(); + for (EventType eventType : eventTypes) { + dtk.removeAWTEventListener(eventType); + } + } + + 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 (EventType et : eventTypes) { + if ((eventMask & et.getEventMask()) != 0 + && et.getTime() > maxTime) { + maxType = et; + maxTime = maxType.getTime(); + } + } + return maxType; + } + } + + private static class EventWaiter extends Waiter { + + long eventMask; + long startTime; + + public EventWaiter(long eventMask) { + this.eventMask = eventMask; + startTime = getLastEventTime(eventMask); + } + + @Override + public AWTEvent actionProduced(Void obj) { + EventType et = listenerSet.getLastEventType(eventMask); + if (et != null + && et.getTime() > startTime) { + return et.getEvent(); + } else { + return null; + } + } + + @Override + public String getDescription() { + return ("Last event under " + + Long.toString(eventMask, 2) + " event mask"); + } + + @Override + public String toString() { + return "EventWaiter{" + "eventMask=" + Long.toString(eventMask, 2) + ", startTime=" + startTime + '}'; + } + } + + private class NoEventWaiter extends Waiter { + + long eventMask; + long waitTime; + + public NoEventWaiter(long eventMask, long waitTime) { + this.eventMask = eventMask; + this.waitTime = waitTime; + } + + @Override + public String actionProduced(Void obj) { + return (checkNoEvent(eventMask, waitTime, TestOut.getNullOutput()) + ? "Reached!" + : null); + } + + @Override + public String getDescription() { + return ("No event under " + + Long.toString(eventMask, 2) + + " event mask during " + + Long.toString(waitTime) + + " milliseconds"); + } + + @Override + public String toString() { + return "NoEventWaiter{" + "eventMask=" + Long.toString(eventMask, 2) + ", waitTime=" + waitTime + '}'; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/FrameWaiter.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/FrameWaiter.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,465 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 + * {@code 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 {@code 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 {@code index+1}'th Frame that meets the criteria + * defined and applied by the {@code 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 {@code index+1}'th Frame that is showing + * and that meets the search criteria. If there are fewer than + * {@code index+1} Frames, a {@code 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 {@code true} and the search is case sensitive, then a + * match occurs when the {@code title} argument is a substring of a + * Frame title. If {@code false} and the search is case sensitive, then + * the {@code title} argument and the Frame title must be the same. If + * {@code true} and the search is case insensitive, then a match occurs + * when the {@code title} argument is a substring of the Frame title + * after changing both to upper case. If {@code false} and the search + * is case insensitive, then a match occurs when the {@code title} + * argument is a substring of the Frame title after changing both to upper + * case. + * @param cc If {@code 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 {@code 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 + * {@code index+1}'th Frame among the currently showing Frames that + * possess a suitable title. + * + * @param title Frame title or subtitle. + * @param ce If {@code true} and the search is case sensitive, then a + * match occurs when the {@code title} argument is a substring of a + * Frame title. If {@code false} and the search is case sensitive, then + * the {@code title} argument and the Frame title must be the same. If + * {@code true} and the search is case insensitive, then a match occurs + * when the {@code title} argument is a substring of the Frame title + * after changing both to upper case. If {@code false} and the search + * is case insensitive, then a match occurs when the {@code title} + * argument is a substring of the Frame title after changing both to upper + * case. + * @param cc If {@code 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 {@code index+1}'th Frame that is showing + * and that has a suitable title. If there are fewer than + * {@code index+1} Frames, a {@code 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 + */ + @Override + 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 + */ + @Override + 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 + */ + @Override + 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 + */ + @Override + public TestOut getOutput() { + return output; + } + + /** + * Waits for a Frame to show. Wait for the {@code index+1}'th Frame + * that meets the criteria defined and applied by the + * {@code 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 {@code index+1}'th Frame that shows and + * that meets the search criteria. If fewer than {@code index+1} Frames + * show up in the allotted time period then a {@code 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 {@code 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 {@code 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 {@code index+1}'th Frame to + * show with a suitable title. + * + * @param title Frame title or subtitle. + * @param compareExactly If {@code true} and the search is case + * sensitive, then a match occurs when the {@code title} argument is a + * substring of a Frame title. If {@code false} and the search is case + * sensitive, then the {@code title} argument and the Frame title must + * be the same. If {@code true} and the search is case insensitive, + * then a match occurs when the {@code title} argument is a substring + * of the Frame title after changing both to upper case. If + * {@code false} and the search is case insensitive, then a match + * occurs when the {@code title} argument is a substring of the Frame + * title after changing both to upper case. + * @param compareCaseSensitive If {@code 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 {@code 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 {@code 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 {@code true} and the search is case + * sensitive, then a match occurs when the {@code title} argument is a + * substring of a Frame title. If {@code false} and the search is case + * sensitive, then the {@code title} argument and the Frame title must + * be the same. If {@code true} and the search is case insensitive, + * then a match occurs when the {@code title} argument is a substring + * of the Frame title after changing both to upper case. If + * {@code false} and the search is case insensitive, then a match + * occurs when the {@code title} argument is a substring of the Frame + * title after changing both to upper case. + * @param compareCaseSensitive If {@code 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 + * {@code 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() + */ + @Override + 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) + */ + @Override + protected String getTimeoutExpiredMessage(long timeSpent) { + return ("Frame \"" + getComponentChooser().getDescription() + "\" has not been opened in " + + timeSpent + " 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) + */ + @Override + protected String getActionProducedMessage(long timeSpent, final Object result) { + String resultToString = null; + if (result instanceof Component) { + // run toString in dispatch thread + resultToString = new QueueTool().invokeSmoothly( + new QueueTool.QueueAction("result.toString()") { + @Override + public String launch() { + return result.toString(); + } + } + ); + } else { + resultToString = result.toString(); + } + return ("Frame \"" + getComponentChooser().getDescription() + "\" has been opened in " + + timeSpent + " milliseconds" + + "\n " + resultToString); + } + + /** + * @see Waiter#getGoldenWaitingStartedMessage() + */ + @Override + protected String getGoldenWaitingStartedMessage() { + return "Start to wait frame \"" + getComponentChooser().getDescription() + "\" opened"; + } + + /** + * @see Waiter#getGoldenTimeoutExpiredMessage() + */ + @Override + protected String getGoldenTimeoutExpiredMessage() { + return "Frame \"" + getComponentChooser().getDescription() + "\" has not been opened"; + } + + /** + * @see Waiter#getGoldenActionProducedMessage() + */ + @Override + 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; + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof Frame) { + return ((FIND_INVISIBLE_WINDOWS || (comp.isShowing() && comp.isVisible())) + && chooser.checkComponent(comp)); + } else { + return false; + } + } + + @Override + public String getDescription() { + return chooser.getDescription(); + } + + @Override + public String toString() { + return "FrameSubChooser{" + "chooser=" + chooser + '}'; + } + } + + 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; + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof Frame) { + if ((FIND_INVISIBLE_WINDOWS || (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.contains(contextToComp); + } + } + } + return false; + } + + @Override + public String getDescription() { + return title; + } + + @Override + public String toString() { + return "FrameByTitleChooser{" + "title=" + title + ", compareExactly=" + compareExactly + ", compareCaseSensitive=" + compareCaseSensitive + '}'; + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/JemmyException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/JemmyException.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,161 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class JemmyException extends RuntimeException { + + private static final long serialVersionUID = 42L; + 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() + */ + @Deprecated + 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. + */ + @Override + public void printStackTrace() { + printStackTrace(System.out); + } + + /** + * Prints stack trace. + * + * @param ps PrintStream to print stack trace into. + */ + @Override + 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. + * + */ + @Override + 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()); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/JemmyInputException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/JemmyInputException.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy; + +import java.awt.Component; + +/** + * + * Exception can be thrown as a result of incorrect input operations. + * + * @author Alexandre Iline (alexandre.iline@oracle.com) + */ +public class JemmyInputException extends JemmyException { + + private static final long serialVersionUID = 42L; + + /** + * 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(); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/JemmyProperties.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/JemmyProperties.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,985 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + * + */ +public class JemmyProperties { + + /** + * The event queue model mask. + * + * @see #getCurrentDispatchingModel() + * @see #setCurrentDispatchingModel(int) + */ + public static final int QUEUE_MODEL_MASK = 1; + + /** + * The robot using model mask. + * + * @see #getCurrentDispatchingModel() + * @see #setCurrentDispatchingModel(int) + */ + public static final int ROBOT_MODEL_MASK = 2; + + /** + * Event shorcutting model mask. Should not be used together with robot + * mask. + * + * @see #getCurrentDispatchingModel() + * @see #setCurrentDispatchingModel(int) + */ + public static final int SHORTCUT_MODEL_MASK = 4; + + /** + * The robot using model mask. + * + * @see #getCurrentDispatchingModel() + * @see #setCurrentDispatchingModel(int) + */ + public static final int SMOOTH_ROBOT_MODEL_MASK = 8; + + private static final int DEFAULT_DRAG_AND_DROP_STEP_LENGTH = 100; + private static final Stack propStack = new Stack<>(); + + 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", getDefaultDispatchingModel()); + setProperty("drag_and_drop.step_length", 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 = 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.empty()) { + propStack.add(new JemmyProperties()); + } + return propStack.peek(); + } + + /** + * Prints full version into standard 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]; + System.arraycopy(argv, 1, newArgv, 0, argv.length - 1); + 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 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(); + try (FileInputStream fileStream = new FileInputStream(prop_file)) { + props.load(fileStream); + } + 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"); + } + + 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 + | IllegalAccessException + | NoSuchMethodException + | InstantiationException + | 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", model); + } + + /** + * 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"); + } + + /** + * 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", length); + } + + /** + * 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] = 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 (String key : keys) { + properties.setProperty(key, getProperty(key)); + } + //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.trim().equals(varName)) { + return token.nextToken().trim(); + } + } + return ""; + } catch (IOException e) { + getCurrentOutput().printStackTrace(e); + return ""; + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/NoComponentUnderMouseException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/NoComponentUnderMouseException.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class NoComponentUnderMouseException extends RuntimeException { + + private static final long serialVersionUID = 42L; + + /** + * Constructor. + */ + public NoComponentUnderMouseException() { + super("No component under the mouse!"); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/ObjectBrowser.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/ObjectBrowser.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,159 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 + */ + @Override + 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 + */ + @Override + 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 {@code 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 (Field field : fields) { + output.printLine(Modifier.toString(field.getModifiers()) + " " + + field.getType().getName() + " " + + field.getName()); + Object value = "Inaccessible"; + try { + value = field.get(object); + } catch (IllegalAccessException ignored) { + } + 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 (Method method : methods) { + output.printLine(Modifier.toString(method.getModifiers()) + " " + + method.getReturnType().getName() + " " + + method.getName()); + Class[] params = method.getParameterTypes(); + for (Class param : params) { + output.printLine(" " + param.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(); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Outputable.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Outputable.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/QueueTool.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/QueueTool.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,818 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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() { + @Override + public String actionProduced(Void obj) { + return locker.isLocked() ? "" : null; + } + + @Override + public String getDescription() { + return "Event queue to be locked"; + } + + @Override + public String toString() { + return "QueueTool.Waiter{" + getDescription() + '}'; + } + }); + setOutput(JemmyProperties.getProperties().getOutput()); + setTimeouts(JemmyProperties.getProperties().getTimeouts()); + } + + /** + * Returns system EventQueue. + * + * @return system EventQueue. + */ + public static EventQueue getQueue() { + return Toolkit.getDefaultToolkit().getSystemEventQueue(); + } + + /** + * Map to {@code EventQueue.isDispatchThread()}. + * + * @return true if this thread is the AWT dispatching thread. + */ + public static boolean isDispatchThread() { + return EventQueue.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 + * {@code ((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 + */ + @Override + 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 + */ + @Override + 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 + */ + @Override + 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 + */ + @Override + 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() { + @Override + public String actionProduced(Void obj) { + if (checkEmpty()) { + return "Empty"; + } + return null; + } + + @Override + public String getDescription() { + return "Wait event queue empty"; + } + + @Override + public String toString() { + return "waitEmpty.Waiter{" + getDescription() + '}'; + } + }); + 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" : invokeSmoothly( + new QueueTool.QueueAction("event.toString()") { + @Override + public String 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 {@code 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" : invokeSmoothly( + new QueueTool.QueueAction("event.toString()") { + @Override + public String 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 {@code action.launch(Object)} method parameter. + * @return QueueAction instance which can be use for execution monitoring. + * @see QueueTool.QueueAction + */ + public QueueAction invoke(Action action, P 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 {@code action.launch()} + * method directly. + * + * @param action anaction to be executed. + * @return Action result. + */ + public R invokeSmoothly(QueueAction action) { + if (!EventQueue.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 {@code runnable.run()} + * method directly. + * + * @param runnable a runnable to be executed. + */ + public void invokeSmoothly(Runnable runnable) { + if (!EventQueue.isDispatchThread()) { + invokeAndWait(runnable); + } else { + runnable.run(); + } + } + + /** + * Being executed outside of AWT dispatching thread, invokes an action + * through the event queue. Otherwise executes + * {@code action.launch(Object)} method directly. + * + * @param action anaction to be executed. + * @param param an action parameter + * @return Action result. + */ + public R invokeSmoothly(Action action, P param) { + if (!EventQueue.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 R invokeAndWait(QueueAction action) { + + class JemmyInvocationLock { + } + Object lock = new JemmyInvocationLock(); + InvocationEvent event + = new JemmyInvocationEvent(Toolkit.getDefaultToolkit(), + action, + lock, + true); + try { + synchronized (lock) { + getQueue().postEvent(event); + while (!action.getFinished()) { + 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(); + } + + public static final class JemmyInvocationEvent extends InvocationEvent { + + private static final long serialVersionUID = 42L; + + public JemmyInvocationEvent(Object source, Runnable runnable, + Object notifier, boolean catchThrowables) { + super(source, runnable, notifier, catchThrowables); + } + } + + /** + * 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 R invokeAndWait(Action action, P 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 executed through event queue. Even if it was executed without + * waiting by {@code invoke(QueueAction)} execution process can be + * monitored by {@code getResult()}, {@code getException()}, + * {@code getFinished()} methods. + */ + public static abstract class QueueAction implements Runnable { + + private volatile boolean finished; + private Exception exception; + private R 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 R launch() + throws Exception; + + /** + */ + @Override + public final void run() { + finished = false; + exception = null; + result = null; + try { + result = launch(); + } catch (Exception e) { + exception = e; + } finally { + 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 R getResult() { + return result; + } + + /** + * Returns exception occured during action execution (if any). + * + * @return the Exception happened inside {@code 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; + } + + @Override + public String toString() { + return "QueueAction{description=" + description + ", result=" + result + ", finished=" + finished + ", exception=" + exception + '}'; + } + } + + private static class JemmyQueue extends EventQueue { + + private boolean installed = false; + + public void shortcutEvent(AWTEvent event) { + super.dispatchEvent(event); + } + + @Override + 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; + } + + @Override + 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; + } + + @Override + public String actionProduced(Void obj) { + try { + EventWaiter eventWaiter = new EventWaiter(emptyTime); + EventQueue.invokeAndWait(eventWaiter); + if (eventWaiter.empty + && timeFromStart() <= super.getTimeouts().getTimeout("Waiter.WaitingTime")) { + return "Reached"; + } + } catch (InterruptedException | InvocationTargetException e) { + output.printStackTrace(e); + } + return null; + } + + @Override + public String getDescription() { + return "Wait event queue staying empty for " + emptyTime; + } + + @Override + public String toString() { + return "StayingEmptyWaiter{" + "emptyTime=" + emptyTime + '}'; + } + } + + private class ActionRunnable extends QueueAction { + + Action action; + P param; + + public ActionRunnable(Action action, P param) { + super(action.getDescription()); + this.action = action; + this.param = param; + } + + @Override + public R launch() throws Exception { + return action.launch(param); + } + } + + private class RunnableRunnable extends QueueAction { + + Runnable action; + + public RunnableRunnable(Runnable action) { + super("Runnable"); + this.action = action; + } + + @Override + public Void launch() throws Exception { + action.run(); + return null; + } + } + + private class Locker extends QueueAction { + + volatile boolean locked = false; + long wholeTime, deltaTime; + boolean expired; + + public Locker() { + super("Event queue locking"); + } + + @Override + public Void 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; + } + + @Override + public void run() { + new Timeout("", time).sleep(); + unlock(); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Scenario.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Scenario.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 {@code java.lang.Object} to it's {@code runIt} method. + * + * @see Test + * + * @author Alexandre Iline (alexandre.iline@oracle.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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Test.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Test.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,441 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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:
+ * {@code 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
+ * {@code new Test([test class name]).startTest([test args]);}
+ * + *

Timeouts used:
+ * Test.WholeTestTimeout - time for the whole test
+ * + * @author Alexandre Iline (alexandre.iline@oracle.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; + + /** + * Constructor for tests requiring only a class instance. Creates a subclass + * of {@code ActionProducer} and {@code 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 {@code ActionProducer} and + * {@code 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 {@code Test} + * class. Creates a subclass of {@code ActionProducer} and + * {@code 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 {@code 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; + 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 {@code 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 {@code Scenario} to launch. + * @see org.netbeans.jemmy.Scenario + */ + public Scenario testForName(String testName) { + try { + return ((Scenario) (Class.forName(testName). + getConstructor(new Class[0]). + newInstance())); + } 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 {@code Test}. + * + * @param timeouts A collection of timeout assignments. + * @see org.netbeans.jemmy.Timeoutable + * @see org.netbeans.jemmy.Timeouts + * @see #getTimeouts + */ + @Override + 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 {@code Test}. + * + * @see org.netbeans.jemmy.Timeoutable + * @see org.netbeans.jemmy.Timeouts + * @see #setTimeouts + */ + @Override + 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 + */ + @Override + 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 + */ + @Override + 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, "Test.WholeTestTimeout")).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 + * {@code Scenario}. + * + * @param obj An argument object that controls test execution. This might be + * a {@code java.lang.String[]} containing command line arguments. + * @see org.netbeans.jemmy.Action + * @return an Integer containing test status. + */ + @Override + 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 e.getStatus(); + } catch (Throwable e) { + output.printStackTrace(e); + return SCENARIO_EXCEPTION_STATUS; + } + return 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 + */ + @Override + public final String getDescription() { + return "Test " + scenario.getClass().getName() + " finished"; + } + + @Override + public String toString() { + return "Test{" + "scenario=" + scenario + '}'; + } + + /** + * Defines a way to execute this {@code 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 + */ + @Override + public int runIt(Object param) { + return 0; + } + + /** + * Sleeps. + * + * @param time The sleep time in milliseconds. + */ + protected void doSleep(long time) { + try { + Thread.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; + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/TestCompletedException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/TestCompletedException.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,75 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy; + +/** + * + * Exception is throught as a result of test. either test failed or passed. + * + * @author Alexandre Iline (alexandre.iline@oracle.com) + */ +public class TestCompletedException extends JemmyException { + + private static final long serialVersionUID = 42L; + + 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; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/TestOut.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/TestOut.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,351 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Timeout.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Timeout.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,109 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy; + +/** + * Represents one timeout. + * + * @author Alexandre Iline (alexandre.iline@oracle.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.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!")); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/TimeoutExpiredException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/TimeoutExpiredException.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy; + +/** + * + * Exception is supposed to be used to notice that some waiting was expired. + * + * @author Alexandre Iline (alexandre.iline@oracle.com) + */ +public class TimeoutExpiredException extends JemmyException { + + private static final long serialVersionUID = 42L; + + /** + * Constructor. + * + * @param description Waiting description. + */ + public TimeoutExpiredException(String description) { + super(description); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Timeoutable.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Timeoutable.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Timeouts.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Timeouts.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,424 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class Timeouts { + + 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 ignored) { + } + } + + /** + * 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, 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 = timeouts.get(name); + 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 = 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.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(); + } + + /** + * Prints all defined timeouts. + * + * @param pw PrintWriter to print into. + */ + public void print(PrintWriter pw) { + Enumeration e = timeouts.keys(); + String name = ""; + while (e.hasMoreElements()) { + name = e.nextElement(); + pw.println(name + " = " + Long.toString(getTimeout(name))); + } + pw.println("Default values:"); + e = defaults.timeouts.keys(); + name = ""; + while (e.hasMoreElements()) { + name = 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; + String propName = null; + while (propNames.hasMoreElements()) { + propName = (String) propNames.nextElement(); + propValue = Long.parseLong(props.getProperty(propName)); + 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 { + try (FileInputStream fileInputStream = new FileInputStream(fileName)) { + load(fileInputStream); + } + } + + /** + * 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; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Waitable.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Waitable.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy; + +/** + * + * Defines criteria for waiting. + * + * @see org.netbeans.jemmy.Waiter + * + * @author Alexandre Iline (alexandre.iline@oracle.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 R actionProduced(P obj); + + /** + * Returns description. + * + * @return a description of the wait criteria. + */ + public String getDescription(); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Waiter.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/Waiter.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,352 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 final Waitable waitable; + private long startTime = 0; + private long endTime = -1; + private R result; + private Timeouts timeouts; + private String waitingTimeOrigin; + private TestOut out; + + /** + * Replace the fine-grained timeouts with a global flag which can be set, + * for instance, by a separate thread when a global timeout runs out. + */ + public static volatile boolean USE_GLOBAL_TIMEOUT = false; + public static volatile boolean globalTimeoutExpired = false; + + /** + * Constructor. + * + * @param w Waitable object defining waiting criteria. + */ + public Waiter(Waitable w) { + super(); + if (w == null) { + throw new NullPointerException("Waitable cannot be null"); + } + setTimeouts(JemmyProperties.getProperties().getTimeouts()); + setOutput(JemmyProperties.getProperties().getOutput()); + waitable = w; + } + + /** + * Can be used from subclass. actionProduced() method must be overriden in + * a class that uses this super constructor. actionProduced() method in + * Waiter will throw UnsupportedOperationException whenever invoked. + */ + protected Waiter() { + super(); + setTimeouts(JemmyProperties.getProperties().getTimeouts()); + setOutput(JemmyProperties.getProperties().getOutput()); + waitable = null; + } + + 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 + */ + @Override + 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". + * @param waitingTimeOrigin overrides {@code useAsWaitingTime} in timeout + * reporting if non-null. + * @return the cloned timeouts. + */ + public Timeouts setTimeoutsToCloneOf(Timeouts timeouts, + String useAsWaitingTime, String waitingTimeOrigin) { + Timeouts t = timeouts.cloneThis(); + t.setTimeout("Waiter.WaitingTime", t.getTimeout(useAsWaitingTime)); + setTimeouts(t); + setWaitingTimeOrigin((null != waitingTimeOrigin) ? waitingTimeOrigin : useAsWaitingTime); + return t; + } + + /** + * @see #setTimeoutsToCloneOf(Timeouts, String, String) + */ + public Timeouts setTimeoutsToCloneOf(Timeouts timeouts, + String useAsWaitingTime) { + return setTimeoutsToCloneOf(timeouts, useAsWaitingTime, null); + } + + /** + * 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 + */ + @Override + 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 + */ + @Override + 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 + */ + @Override + 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 R waitAction(P waitableObject) + throws InterruptedException { + startTime = System.currentTimeMillis(); + out.printTrace(getWaitingStartedMessage()); + out.printGolden(getGoldenWaitingStartedMessage()); + long timeDelta = timeouts.getTimeout("Waiter.TimeDelta"); + while ((result = actionProduced(waitableObject)) == null) { + Thread.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.sleep(timeouts.getTimeout("Waiter.AfterWaitingTime")); + return result; + } + + /** + * This method delegates call to the waitable passed in constructor. If a + * subclass was created using protected no-parameters constructor, it should + * implement its own actionProduced method() as this one will throw an + * UnsupportedOperationException. + * @see Waitable + * @param obj + */ + @Override + public R actionProduced(P obj) { + if (waitable != null) { + return waitable.actionProduced(obj); + } else { + throw new UnsupportedOperationException("actionProduced() return " + + "value is not defined. It used to return Boolean.TRUE " + + "in previous versions of Jemmy."); + } + } + + /** + * @see Waitable + */ + @Override + public String getDescription() { + return "Unknown waiting"; + } + + @Override + public String toString() { + return "Waiter{" + "description = " + getDescription() + ", waitable=" + waitable + ", startTime=" + startTime + ", endTime=" + endTime + ", result=" + result + ", waitingTimeOrigin=" + waitingTimeOrigin + '}'; + } + + /** + * 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 " + + timeSpent + " 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 = new QueueTool().invokeSmoothly( + new QueueTool.QueueAction("result.toString()") { + @Override + public String launch() { + return result.toString(); + } + } + ); + } else { + resultToString = result.toString(); + } + return ("\"" + getActualDescription() + "\" action has been produced in " + + timeSpent + " 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 String getActualDescription() { + final String suffix = (null == waitingTimeOrigin) ? "" : " (" + waitingTimeOrigin + ")"; + if (waitable != null) { + return waitable.getDescription() + suffix; + } else { + return getDescription() + suffix; + } + } + + private boolean timeoutExpired() { + if (USE_GLOBAL_TIMEOUT) { + return globalTimeoutExpired; + } + return timeFromStart() > timeouts.getTimeout("Waiter.WaitingTime"); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/WindowWaiter.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/WindowWaiter.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,483 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class WindowWaiter extends Waiter implements Timeoutable { + + public static boolean FIND_INVISIBLE_WINDOWS = false; + + 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 {@code index+1}'th window that is both owned by the + * {@code java.awt.Window} {@code owner} and that meets the + * criteria defined and applied by the {@code 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 {@code index+1}'th window that is + * showing, has the proper window ownership, and that meets the search + * criteria. If there are fewer than {@code index+1} windows, a + * {@code 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 {@code java.awt.Window} + * {@code owner} and that meets the search criteria applied by the + * {@code 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 {@code 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 {@code index+1}'th window that meets the criteria + * defined and applied by the {@code 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 {@code index+1}'th window that is showing + * and that meets the search criteria. If there are fewer than + * {@code index+1} windows, a {@code 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 + * {@code 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 {@code 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 + */ + @Override + 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 + */ + @Override + 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 {@code org.netbeans.jemmy.ComponentChooser}. + * + * @param obj Not used. + * @return the window waited upon. If a window cannot be found then a + * {@code null} reference is returned. + * @see org.netbeans.jemmy.Action + */ + @Override + public Window actionProduced(Void obj) { + return WindowWaiter.getWindow(owner, chooser, index); + } + + /** + * Waits for a window to show. Wait for the {@code index+1}'th window + * that meets the criteria defined and applied by the + * {@code 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 {@code index+1}'th window that shows and + * that meets the search criteria. If fewer than {@code index+1} + * windows show up in the allotted time period then a {@code 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 {@code 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 {@code 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 {@code index+1}'th window + * to show that is both owned by the {@code java.awt.Window} + * {@code o} and that meets the criteria defined and applied by the + * {@code 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 {@code index+1}'th window to show that + * has the proper window ownership, and that meets the search criteria. If + * there are fewer than {@code index+1} windows, a {@code 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 waitAction(null); + } + + /** + * Waits for a window to show. Wait for the first window to show that is + * both owned by the {@code java.awt.Window} {@code o} and that + * meets the criteria defined and applied by the + * {@code 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 {@code 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); + } + + @Override + public String getDescription() { + return chooser.getDescription(); + } + + @Override + public String toString() { + return "WindowWaiter{" + "chooser=" + chooser + ", owner=" + owner + ", index=" + index + '}'; + } + + /** + * 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() + */ + @Override + 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. + */ + @Override + protected String getTimeoutExpiredMessage(long timeSpent) { + return ("Window \"" + chooser.getDescription() + "\" has not been opened in " + + timeSpent + " 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. + */ + @Override + protected String getActionProducedMessage(long timeSpent, final Object result) { + String resultToString; + if (result instanceof Component) { + // run toString in dispatch thread + resultToString = new QueueTool().invokeSmoothly( + new QueueTool.QueueAction("result.toString()") { + @Override + public String launch() { + return result.toString(); + } + } + ); + } else { + resultToString = result.toString(); + } + return ("Window \"" + chooser.getDescription() + "\" has been opened in " + + timeSpent + " milliseconds" + + "\n " + resultToString); + } + + /** + * @return a message. + * @see org.netbeans.jemmy.Waiter#getGoldenWaitingStartedMessage() + */ + @Override + protected String getGoldenWaitingStartedMessage() { + return "Start to wait window \"" + chooser.getDescription() + "\" opened"; + } + + /** + * @return a message. + * @see org.netbeans.jemmy.Waiter#getGoldenTimeoutExpiredMessage() + */ + @Override + protected String getGoldenTimeoutExpiredMessage() { + return "Window \"" + chooser.getDescription() + "\" has not been opened"; + } + + /** + * @return a message. + * @see org.netbeans.jemmy.Waiter#getGoldenActionProducedMessage() + */ + @Override + 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 (Window window : windows) { + if (cc.checkComponent(window)) { + return window; + } + if ((result = WindowWaiter.getWindow(window, cc)) != null) { + return result; + } + } + return null; + } + } + + private static Window getAWindow(ComponentChooser cc) { + Window result = null; + Frame[] frames = Frame.getFrames(); + for (Frame frame : frames) { + if (cc.checkComponent(frame)) { + return frame; + } + if ((result = WindowWaiter.getWindow(frame, cc)) != null) { + return result; + } + } + return null; + } + + private Window waitWindow() + throws InterruptedException { + return 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; + } + + @Override + public boolean checkComponent(Component comp) { + if ((FIND_INVISIBLE_WINDOWS || (comp.isShowing() && comp.isVisible())) + && chooser.checkComponent(comp)) { + if (curIndex == index) { + return true; + } + curIndex++; + } + return false; + } + + @Override + public String getDescription() { + return chooser.getDescription(); + } + + @Override + public String toString() { + return "IndexChooser{" + "curIndex=" + curIndex + ", index=" + index + ", chooser=" + chooser + '}'; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/accessibility/AccessibilityChooser.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/accessibility/AccessibilityChooser.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 { + + @Override + 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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/accessibility/AccessibleDescriptionChooser.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/accessibility/AccessibleDescriptionChooser.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 { + + private final String description; + private final StringComparator comparator; + + public AccessibleDescriptionChooser(String description, StringComparator comparator) { + this.description = description; + this.comparator = comparator; + } + + public AccessibleDescriptionChooser(String description) { + this(description, Operator.getDefaultStringComparator()); + } + + @Override + public final boolean checkContext(AccessibleContext context) { + return comparator.equals(context.getAccessibleDescription(), description); + } + + @Override + public String getDescription() { + return "JComponent with \"" + description + "\" accessible description"; + } + + @Override + public String toString() { + return "AccessibleDescriptionChooser{" + "description=" + description + ", comparator=" + comparator + '}'; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/accessibility/AccessibleNameChooser.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/accessibility/AccessibleNameChooser.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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()); + } + + @Override + public final boolean checkContext(AccessibleContext context) { + return comparator.equals(context.getAccessibleName(), name); + } + + @Override + public String getDescription() { + return "JComponent with \"" + name + "\" accessible name"; + } + + @Override + public String toString() { + return "AccessibleNameChooser{" + "name=" + name + ", comparator=" + comparator + '}'; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/debug.timeouts --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/debug.timeouts Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,19 @@ +AbstractButtonOperator.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 diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/APIDriverInstaller.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/APIDriverInstaller.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,171 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 ? new QueueJMenuDriver() : new DefaultJMenuDriver()), + ((System.getProperty("apple.laf.useScreenMenuBar") != null + && System.getProperty("apple.laf.useScreenMenuBar").equals("true")) ? new AppleMenuDriver() + : (shortcutEvents ? new QueueJMenuDriver() : new DefaultJMenuDriver())), + new JTableHeaderDriver()}); + } + + /** + * Constructs a DefaultDriverInstaller object with shortcut mode flag taken + * from {@code 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() { + @Override + public String[] getSupported() { + return new String[]{Object.class.getName()}; + } + }); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/ArrayDriverInstaller.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/ArrayDriverInstaller.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.drivers; + +/** + * Auxiliary class making driver registration easier. + * + * @author Alexandre Iline (alexandre.iline@oracle.com) + */ +public class ArrayDriverInstaller implements DriverInstaller { + + String[] ids; + Object[] drivers; + + /** + * Constructs an ArrayDriverInstaller object. Both parameter arrays mush + * have same length, {@code 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. + */ + @Override + public void install() { + for (int i = 0; i < ids.length; i++) { + DriverManager.setDriver(ids[i], drivers[i]); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/ButtonDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/ButtonDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/DefaultDriverInstaller.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/DefaultDriverInstaller.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,166 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 ? new QueueJMenuDriver() : new DefaultJMenuDriver()), + new JTableHeaderDriver()}); + } + + /** + * Constructs a DefaultDriverInstaller object with shortcut mode flag taken + * from {@code 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() { + @Override + public String[] getSupported() { + return new String[]{Object.class.getName()}; + } + }); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/DescriptablePathChooser.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/DescriptablePathChooser.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.drivers; + +/** + * Specifies an interface for objects defining path searching criteria. + * + * @author Alexandre Iline(alexandre.iline@oracle.com) + */ +public interface DescriptablePathChooser extends PathChooser { + + /** + * Gives path description. + */ + public String getDescription(); + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/Driver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/Driver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/DriverInstaller.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/DriverInstaller.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.drivers; + +/** + * + * @author Alexandre Iline (alexandre.iline@oracle.com) + */ +public interface DriverInstaller { + + public void install(); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/DriverManager.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/DriverManager.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,810 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 {@code 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 (Class aSupported : supported) { + setDriver(id, driver, aSupported); + } + } + + /** + * 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 (String aSupported : supported) { + setDriver(id, driver, aSupported); + } + } + + /** + * 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 (Class operatorClass : operatorClasses) { + removeDriver(id, operatorClass); + } + } + + /** + * 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 (String operatorClassName : operatorClassNames) { + removeDriver(id, operatorClassName); + } + } + + /** + * Removes driver for all supported classes. + * + * @param id Driver type to remove. + */ + public static void removeDrivers(String id) { + String[] keys = JemmyProperties.getCurrentKeys(); + for (String key : keys) { + if (key.startsWith(id)) { + JemmyProperties. + removeCurrentProperty(key); + } + } + } + + /** + * Returns {@code 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 {@code 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 {@code TREE_DRIVER_ID} driver. + * + * @param driver a driver + * @see #getTreeDriver + */ + public static void setTreeDriver(TreeDriver driver) { + setDriver(TREE_DRIVER_ID, driver); + } + + /** + * Returns {@code 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 {@code 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 {@code TEXT_DRIVER_ID} driver. + * + * @param driver a driver + * @see #getTextDriver + */ + public static void setTextDriver(TextDriver driver) { + setDriver(TEXT_DRIVER_ID, driver); + } + + /** + * Returns {@code 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 {@code 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 {@code KEY_DRIVER_ID} driver. + * + * @param driver a driver + * @see #getKeyDriver + */ + public static void setKeyDriver(KeyDriver driver) { + setDriver(KEY_DRIVER_ID, driver); + } + + /** + * Returns {@code 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 {@code 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 {@code MOUSE_DRIVER_ID} driver. + * + * @param driver a driver + * @see #getMouseDriver + */ + public static void setMouseDriver(MouseDriver driver) { + setDriver(MOUSE_DRIVER_ID, driver); + } + + /** + * Returns {@code 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 {@code 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 {@code SCROLL_DRIVER_ID} driver. + * + * @param driver a driver + * @see #getScrollDriver + */ + public static void setScrollDriver(ScrollDriver driver) { + setDriver(SCROLL_DRIVER_ID, driver); + } + + /** + * Returns {@code 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 {@code 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 {@code BUTTON_DRIVER_ID} driver. + * + * @param driver a driver + * @see #getButtonDriver + */ + public static void setButtonDriver(ButtonDriver driver) { + setDriver(BUTTON_DRIVER_ID, driver); + } + + /** + * Returns {@code 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 {@code 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 {@code LIST_DRIVER_ID} driver. + * + * @param driver a driver + * @see #getListDriver + */ + public static void setListDriver(ListDriver driver) { + setDriver(LIST_DRIVER_ID, driver); + } + + /** + * Returns {@code 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 {@code 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 {@code MULTISELLIST_DRIVER_ID} driver. + * + * @param driver a driver + * @see #getMultiSelListDriver + */ + public static void setMultiSelListDriver(MultiSelListDriver driver) { + setDriver(MULTISELLIST_DRIVER_ID, driver); + } + + /** + * Returns {@code 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 {@code 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 {@code ORDEREDLIST_DRIVER_ID} driver. + * + * @param driver a driver + * @see #getOrderedListDriver + */ + public static void setOrderedListDriver(OrderedListDriver driver) { + setDriver(ORDEREDLIST_DRIVER_ID, driver); + } + + /** + * Returns {@code 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 {@code 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 {@code TABLE_DRIVER_ID} driver. + * + * @param driver a driver + * @see #getTableDriver + */ + public static void setTableDriver(TableDriver driver) { + setDriver(TABLE_DRIVER_ID, driver); + } + + /** + * Returns {@code 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 {@code 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 {@code WINDOW_DRIVER_ID} driver. + * + * @param driver a driver + * @see #getWindowDriver + */ + public static void setWindowDriver(WindowDriver driver) { + setDriver(WINDOW_DRIVER_ID, driver); + } + + /** + * Returns {@code 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 {@code 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 {@code FRAME_DRIVER_ID} driver. + * + * @param driver a driver + * @see #getFrameDriver + */ + public static void setFrameDriver(FrameDriver driver) { + setDriver(FRAME_DRIVER_ID, driver); + } + + /** + * Returns {@code 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 {@code 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 {@code INTERNAL_FRAME_DRIVER_ID} driver. + * + * @param driver a driver + * @see #getInternalFrameDriver + */ + public static void setInternalFrameDriver(InternalFrameDriver driver) { + setDriver(INTERNAL_FRAME_DRIVER_ID, driver); + } + + /** + * Returns {@code 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 {@code 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 {@code FOCUS_DRIVER_ID} driver. + * + * @param driver a driver + * @see #getFocusDriver + */ + public static void setFocusDriver(FocusDriver driver) { + setDriver(FOCUS_DRIVER_ID, driver); + } + + /** + * Returns {@code 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 {@code 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 {@code 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(); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/EditorDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/EditorDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/FocusDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/FocusDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/FrameDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/FrameDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/InputDriverInstaller.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/InputDriverInstaller.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,158 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 {@code 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 {@code 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.getInnerThrowable() 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/InternalFrameDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/InternalFrameDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/KeyDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/KeyDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 ({@code KeyEvent.VK_*} value) + * @param modifiers a combination of {@code InputEvent.*_MASK} fields. + */ + public void pressKey(ComponentOperator oper, int keyCode, int modifiers); + + /** + * Typed a key. + * + * @param oper Component operator. + * @param keyChar Symbol to be typed. + * @param modifiers a combination of {@code InputEvent.*_MASK} fields. + */ + public void typedKey(ComponentOperator oper, int keyCode, char keyChar, int modifiers); + + /** + * Releases a key. + * + * @param oper Component operator. + * @param keyCode Key code ({@code KeyEvent.VK_*} value) + * @param modifiers a combination of {@code InputEvent.*_MASK} fields. + */ + public void releaseKey(ComponentOperator oper, int keyCode, int modifiers); + + /** + * Pushes a key. + * + * @param oper Component operator. + * @param keyCode Key code ({@code KeyEvent.VK_*} value) + * @param modifiers a combination of {@code 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 ({@code KeyEvent.VK_*} value) + * @param keyChar Symbol to be typed. + * @param modifiers a combination of {@code InputEvent.*_MASK} fields. + * @param pushTime Time between pressing and releasing. + */ + public void typeKey(ComponentOperator oper, int keyCode, char keyChar, int modifiers, Timeout pushTime); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/LightDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/LightDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/LightSupportiveDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/LightSupportiveDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 {@code 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. + */ + @Override + public String[] getSupported() { + return supported; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/ListDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/ListDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/MenuDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/MenuDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.drivers; + +import org.netbeans.jemmy.operators.ComponentOperator; + +/** + * Defines how to work with menus. + * + * @author Alexandre Iline (alexandre.iline@oracle.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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/MouseDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/MouseDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,123 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 ({@code InputEvent.BUTTON*_MASK} + * field) + * @param modifiers a combination of {@code 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 ({@code InputEvent.BUTTON*_MASK} + * field) + * @param modifiers a combination of {@code 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 ({@code InputEvent.BUTTON*_MASK} + * field) + * @param modifiers a combination of {@code 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 ({@code InputEvent.BUTTON*_MASK} + * field) + * @param modifiers a combination of {@code 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 ({@code InputEvent.BUTTON*_MASK} + * field) + * @param modifiers a combination of {@code 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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/MultiSelListDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/MultiSelListDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,39 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/OrderedListDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/OrderedListDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/PathChooser.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/PathChooser.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.drivers; + +/** + * Specifies an interface for objects defining path searching criteria. + * + * @author Alexandre Iline(alexandre.iline@oracle.com) + */ +public interface PathChooser { + + /** + * Checks if {@code 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(); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/ScrollDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/ScrollDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 + * {@code javax.swing.JScrollBar}, {@code javax.swing.JScrollPane}, + * {@code javax.swing.JSlider}, ... + * + * @author Alexandre Iline (alexandre.iline@oracle.com) + */ +public interface ScrollDriver { + + /** + * Changes value to a minimum. + * + * @param oper Scroller operator. + * @param orientation {@code java.awt.Adjustable.HORIZONTAL} or + * {@code java.awt.Adjustable.VERTICAL} + */ + public void scrollToMinimum(ComponentOperator oper, int orientation); + + /** + * Changes value to a maximum. + * + * @param oper Scroller operator. + * @param orientation {@code java.awt.Adjustable.HORIZONTAL} or + * {@code 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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/SupportiveDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/SupportiveDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 {@code 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. + */ + @Override + public Class[] getSupported() { + return supported; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/TableDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/TableDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/TextDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/TextDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,82 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.drivers; + +import org.netbeans.jemmy.operators.ComponentOperator; + +/** + * Defines how to work with text components. + * + * @author Alexandre Iline (alexandre.iline@oracle.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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/TreeDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/TreeDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/UnsupportedOperatorException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/UnsupportedOperatorException.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,83 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class UnsupportedOperatorException extends JemmyException { + + private static final long serialVersionUID = 42L; + + /** + * 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 (Class aSupported : supported) { + if (aSupported.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 (String aSupported : supported) { + if (opClass.getName().equals(aSupported)) { + return; + } + } + } while ((opClass = opClass.getSuperclass()) != null); + throw (new UnsupportedOperatorException(driver, operator)); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/WindowDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/WindowDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,79 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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. + */ + @Deprecated + 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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/buttons/ButtonMouseDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/buttons/ButtonMouseDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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; +import org.netbeans.jemmy.operators.Operator; + +/** + * Driver to push a button by mouse click. + * + * @author Alexandre Iline(alexandre.iline@oracle.com) + */ +public class ButtonMouseDriver extends LightSupportiveDriver implements ButtonDriver { + + public ButtonMouseDriver() { + super(new String[]{"org.netbeans.jemmy.operators.ComponentOperator"}); + } + + @Override + public void press(ComponentOperator oper) { + MouseDriver mdriver = DriverManager.getMouseDriver(oper); + mdriver.moveMouse(oper, + oper.getCenterXForClick(), + oper.getCenterYForClick()); + mdriver.pressMouse(oper, + oper.getCenterXForClick(), + oper.getCenterYForClick(), + Operator.getDefaultMouseButton(), + 0); + } + + @Override + public void release(ComponentOperator oper) { + DriverManager. + getMouseDriver(oper). + releaseMouse(oper, + oper.getCenterXForClick(), + oper.getCenterYForClick(), + Operator.getDefaultMouseButton(), + 0); + } + + @Override + public void push(ComponentOperator oper) { + DriverManager. + getMouseDriver(oper). + clickMouse(oper, + oper.getCenterXForClick(), + oper.getCenterYForClick(), + 1, + Operator.getDefaultMouseButton(), + 0, + oper.getTimeouts(). + create("ComponentOperator.MouseClickTimeout")); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/buttons/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/buttons/package-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/** + *

Button drivers

+ * Different drivers to push a button.
+ * + * @since 4/17/2002 + *
+ */ +package org.netbeans.jemmy.drivers.buttons; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/focus/APIFocusDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/focus/APIFocusDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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(); + } + + @Override + public void giveFocus(ComponentOperator operator) { + operator.requestFocus(); + eDriver.dispatchEvent(operator.getSource(), + new FocusEvent(operator.getSource(), + FocusEvent.FOCUS_GAINED)); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/focus/MouseFocusDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/focus/MouseFocusDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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; +import org.netbeans.jemmy.operators.Operator; + +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(); + } + + @Override + public void giveFocus(final ComponentOperator oper) { + if (!oper.hasFocus()) { + queueTool.invokeSmoothly(new QueueTool.QueueAction("Mouse click to get focus") { + @Override + public Void launch() { + DriverManager.getMouseDriver(oper). + clickMouse(oper, oper.getCenterXForClick(), oper.getCenterYForClick(), + 1, Operator.getDefaultMouseButton(), 0, + oper.getTimeouts().create("ComponentOperator.MouseClickTimeout")); + return null; + } + }); + oper.waitHasFocus(); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/focus/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/focus/package-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/** + *

Focus drivers.

+ * Different drivers to give input focus to a component.
+ *
+ */ +package org.netbeans.jemmy.drivers.focus; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/input/EventDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/input/EventDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,104 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class EventDriver extends LightSupportiveDriver { + + /** + * Constructs an EventDriver object. + * + * @param supported an array of supported class names + */ + public EventDriver(String[] supported) { + super(supported); + } + + /** + * 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; + } + + @Override + public Void launch() { + checkVisibility(component); + component.dispatchEvent(event); + return null; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/input/KeyEventDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/input/KeyEventDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,123 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); + } + + @Override + public void pressKey(ComponentOperator oper, int keyCode, int modifiers) { + pressKey(findNativeParent(oper.getSource()), keyCode, modifiers); + } + + @Override + public void typedKey(ComponentOperator oper, int keyCode, char keyChar, int modifiers) { + typedKey(findNativeParent(oper.getSource()), keyChar, modifiers); + } + + @Override + public void releaseKey(ComponentOperator oper, int keyCode, int modifiers) { + releaseKey(findNativeParent(oper.getSource()), keyCode, modifiers); + } + + @Override + 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); + } + + @Override + public void typeKey(ComponentOperator oper, int keyCode, char keyChar, int modifiers, Timeout pushTime) { + Component nativeContainer = findNativeParent(oper.getSource()); + pressKey(nativeContainer, keyCode, modifiers); + pushTime.sleep(); + typedKey(nativeContainer, keyChar, modifiers); + releaseKey(nativeContainer, keyCode, modifiers); + } + + @Deprecated + private void pressKey(Component nativeContainer, int keyCode, int modifiers) { + dispatchEvent(nativeContainer, + new KeyEvent(nativeContainer, + KeyEvent.KEY_PRESSED, + System.currentTimeMillis(), + modifiers, keyCode)); + } + + private void typedKey(Component nativeContainer, char keyChar, int modifiers) { + dispatchEvent(nativeContainer, + new KeyEvent(nativeContainer, + KeyEvent.KEY_TYPED, + System.currentTimeMillis(), + modifiers, KeyEvent.VK_UNDEFINED, keyChar)); + } + + @Deprecated + 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; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/input/KeyRobotDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/input/KeyRobotDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,95 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class KeyRobotDriver extends RobotDriver implements KeyDriver { + + /** + * Constructs a KeyRobotDriver object. + * + * @param autoDelay Time for {@code Robot.setAutoDelay(long)} method. + */ + public KeyRobotDriver(Timeout autoDelay) { + super(autoDelay); + } + + /** + * Constructs a KeyRobotDriver object. + * + * @param autoDelay Time for {@code Robot.setAutoDelay(long)} method. + * @param supported an array of supported class names + */ + public KeyRobotDriver(Timeout autoDelay, String[] supported) { + super(autoDelay, supported); + } + + @Override + public void pushKey(ComponentOperator oper, int keyCode, int modifiers, Timeout pushTime) { + pressKey(oper, keyCode, modifiers); + pushTime.sleep(); + releaseKey(oper, keyCode, modifiers); + } + + @Override + 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 ({@code KeyEventVK_*} field. + * @param modifiers a combination of {@code InputEvent.*_MASK} fields. + */ + @Override + public void pressKey(ComponentOperator oper, int keyCode, int modifiers) { + pressKey(keyCode, modifiers); + } + + @Override + public void typedKey(ComponentOperator oper, int keyCode, char keyChar, int modifiers) { + releaseKey(oper, keyCode, modifiers); + } + + /** + * Releases a key. + * + * @param oper Operator to release a key on. + * @param keyCode Key code ({@code KeyEventVK_*} field. + * @param modifiers a combination of {@code InputEvent.*_MASK} fields. + */ + @Override + public void releaseKey(ComponentOperator oper, int keyCode, int modifiers) { + releaseKey(keyCode, modifiers); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/input/MouseEventDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/input/MouseEventDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,186 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); + } + + @Override + public void pressMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers) { + dispatchEvent(oper.getSource(), + MouseEvent.MOUSE_PRESSED, + modifiers, x, y, 1, + mouseButton); + } + + @Override + public void releaseMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers) { + dispatchEvent(oper.getSource(), + MouseEvent.MOUSE_RELEASED, + modifiers, x, y, 1, + mouseButton); + } + + @Override + public void moveMouse(ComponentOperator oper, int x, int y) { + dispatchEvent(oper.getSource(), + MouseEvent.MOUSE_MOVED, + 0, x, y, 0, + Operator.getDefaultMouseButton()); + } + + @Override + 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); + } + + @Override + public void dragMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers) { + dispatchEvent(oper.getSource(), + MouseEvent.MOUSE_DRAGGED, + modifiers, x, y, 1, + mouseButton); + } + + @Override + 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); + } + + @Override + public void enterMouse(ComponentOperator oper) { + dispatchEvent(oper.getSource(), + MouseEvent.MOUSE_ENTERED, + 0, oper.getCenterX(), oper.getCenterY(), 0, + Operator.getDefaultMouseButton()); + } + + @Override + 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 {@code 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)); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/input/MouseRobotDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/input/MouseRobotDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,142 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class MouseRobotDriver extends RobotDriver implements MouseDriver { + + /** + * Constructs a MouseRobotDriver object. + * + * @param autoDelay Time for {@code Robot.setAutoDelay(long)} method. + */ + public MouseRobotDriver(Timeout autoDelay) { + super(autoDelay); + } + + /** + * Constructs a MouseRobotDriver object. + * + * @param autoDelay Time for {@code 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 {@code 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 {@code 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); + } + + @Override + public void pressMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers) { + pressMouse(mouseButton, modifiers); + } + + @Override + public void releaseMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers) { + releaseMouse(mouseButton, modifiers); + } + + @Override + public void moveMouse(ComponentOperator oper, int x, int y) { + moveMouse(getAbsoluteX(oper, x), getAbsoluteY(oper, y)); + } + + @Override + 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); + } + + @Override + public void dragMouse(ComponentOperator oper, int x, int y, int mouseButton, int modifiers) { + moveMouse(getAbsoluteX(oper, x), getAbsoluteY(oper, y)); + } + + @Override + 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); + } + + @Override + public void enterMouse(ComponentOperator oper) { + moveMouse(oper, oper.getCenterXForClick(), oper.getCenterYForClick()); + } + + @Override + 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; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/input/RobotDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/input/RobotDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,340 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 {@code 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 {@code 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[]{mouseButton}, + new Class[]{Integer.TYPE}); + } + + public void releaseMouse(int mouseButton, int modifiers) { + makeAnOperation("mouseRelease", + new Object[]{mouseButton}, + new Class[]{Integer.TYPE}); + releaseModifiers(modifiers); + } + + public void moveMouse(int x, int y) { + if (!smooth) { + makeAnOperation("mouseMove", + new Object[]{x, 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[]{ + (int) Math.round(currX), + (int) Math.round(currY)}, + new Class[]{Integer.TYPE, Integer.TYPE}); + } + } else { + makeAnOperation("mouseMove", new Object[]{ + (int) Math.round(targetX), + (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[]{mouseButton}, new Class[]{Integer.TYPE}); + for (int i = 1; i < clickCount; i++) { + makeAnOperation("mouseRelease", new Object[]{mouseButton}, new Class[]{Integer.TYPE}); + makeAnOperation("mousePress", new Object[]{mouseButton}, new Class[]{Integer.TYPE}); + } + mouseClick.sleep(); + makeAnOperation("mouseRelease", new Object[]{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 ({@code KeyEventVK_*} field. + * @param modifiers a combination of {@code InputEvent.*_MASK} fields. + */ + public void pressKey(int keyCode, int modifiers) { + pressModifiers(modifiers); + makeAnOperation("keyPress", + new Object[]{keyCode}, + new Class[]{Integer.TYPE}); + } + + /** + * Releases a key. + * + * @param keyCode Key code ({@code KeyEventVK_*} field. + * @param modifiers a combination of {@code InputEvent.*_MASK} fields. + */ + public void releaseKey(int keyCode, int modifiers) { + releaseModifiers(modifiers); + makeAnOperation("keyRelease", + new Object[]{keyCode}, + new Class[]{Integer.TYPE}); + } + + /** + * Performs a single operation. + * + * @param method a name of {@code 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 + | IllegalStateException + | NoSuchMethodException + | IllegalAccessException e) { + throw (new JemmyException("Exception during java.awt.Robot accessing", e)); + } + } + + /** + * Calls {@code java.awt.Robot.waitForIdle()} method. + */ + protected void synchronizeRobot() { + if (!QueueTool.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 {@code 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 {@code 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 (QueueTool.isDispatchThread()) { + doInitRobot(); + } else { + qtool.invokeAndWait(new Runnable() { + @Override + 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[]{(int) ((autoDelay != null) + ? autoDelay.getValue() + : 0)}, + new Class[]{Integer.TYPE}); + } catch (InvocationTargetException + | IllegalStateException + | NoSuchMethodException + | IllegalAccessException + | ClassNotFoundException + | InstantiationException e) { + throw (new JemmyException("Exception during java.awt.Robot accessing", e)); + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/input/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/input/package-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/** + *

Mouse and keyboard drivers

+ * Contains low-level drivers to perform user input.
+ * + * @since 17 Apr 2002 + *
+ */ +package org.netbeans.jemmy.drivers.input; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/ChoiceDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/ChoiceDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,88 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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; +import org.netbeans.jemmy.operators.Operator; + +/** + * List driver for java.awt.Choice component type. + * + * @author Alexandre Iline(alexandre.iline@oracle.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"}); + } + + @Override + 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, Operator.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); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/JComboMouseDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/JComboMouseDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,79 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); + } + + @Override + 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); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/JListMouseDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/JListMouseDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,101 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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; +import org.netbeans.jemmy.operators.Operator; + +/** + * List driver for javax.swing.JList component type. + * + * @author Alexandre Iline(alexandre.iline@oracle.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(); + } + + @Override + public void selectItem(ComponentOperator oper, int index) { + clickOnItem((JListOperator) oper, index); + } + + @Override + 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 {@code 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") { + @Override + public Void launch() { + Rectangle rect = oper.getCellBounds(index, index); + DriverManager.getMouseDriver(oper). + clickMouse(oper, + rect.x + rect.width / 2, + rect.y + rect.height / 2, + 1, Operator.getDefaultMouseButton(), modifiers, + oper.getTimeouts().create("ComponentOperator.MouseClickTimeout")); + return null; + } + }); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/JTabAPIDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/JTabAPIDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); + } + + @Override + public void selectItem(final ComponentOperator oper, final int index) { + if (index != -1) { + queueTool.invokeSmoothly(new QueueTool.QueueAction("Selecting tab " + index + " by setting selectedIndex") { + @Override + public Void launch() { + ((JTabbedPaneOperator) oper).setSelectedIndex(index); + return null; + } + }); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/JTabMouseDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/JTabMouseDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,75 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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; +import org.netbeans.jemmy.operators.Operator; + +/** + * List driver for javax.swing.JTabbedPane component type. + * + * @author Alexandre Iline(alexandre.iline@oracle.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(); + } + + @Override + public void selectItem(final ComponentOperator oper, final int index) { + if (index != -1) { + queueTool.invokeSmoothly(new QueueTool.QueueAction("Selecting tab " + index + " using mouse") { + @Override + public Void 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, Operator.getDefaultMouseButton(), 0, + oper.getTimeouts().create("ComponentOperator.MouseClickTimeout")); + return null; + } + }); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/JTableHeaderDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/JTableHeaderDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,105 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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; +import org.netbeans.jemmy.operators.Operator; + +/** + * List driver for javax.swing.table.JTableHeader component type. + * + * @author Alexandre Iline(alexandre.iline@oracle.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(); + } + + @Override + public void selectItem(ComponentOperator oper, int index) { + clickOnHeader((JTableHeaderOperator) oper, index); + } + + @Override + 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); + } + } + + @Override + 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 {@code InputEvent.*_MASK} fields. + */ + protected void clickOnHeader(final JTableHeaderOperator oper, final int index, final int modifiers) { + queueTool.invokeSmoothly(new QueueTool.QueueAction("Column selecting") { + @Override + public Void launch() { + Point toClick = oper.getPointToClick(index); + DriverManager.getMouseDriver(oper). + clickMouse(oper, + toClick.x, + toClick.y, + 1, Operator.getDefaultMouseButton(), modifiers, + oper.getTimeouts().create("ComponentOperator.MouseClickTimeout")); + return null; + } + }); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/ListAPIDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/ListAPIDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class ListAPIDriver extends LightSupportiveDriver implements MultiSelListDriver { + + /** + * Constructs a ListAPIDriver. + */ + public ListAPIDriver() { + super(new String[]{"org.netbeans.jemmy.operators.ListOperator"}); + } + + @Override + public void selectItem(ComponentOperator oper, int index) { + ListOperator loper = (ListOperator) oper; + clearSelection(loper); + loper.select(index); + } + + @Override + public void selectItems(ComponentOperator oper, int[] indices) { + ListOperator loper = (ListOperator) oper; + clearSelection(loper); + for (int indice : indices) { + loper.select(indice); + } + } + + private void clearSelection(ListOperator loper) { + for (int i = 0; i < loper.getItemCount(); i++) { + loper.deselect(i); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/ListKeyboardDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/ListKeyboardDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class ListKeyboardDriver extends ListAPIDriver implements MultiSelListDriver { + + /** + * Constructs a ListKeyboardDriver. + */ + public ListKeyboardDriver() { + super(); + } + + @Override + 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); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/lists/package-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/** + *

List drivers

+ * Different drivers to perform a list operations.
+ * + * @since 4/17/2002 + *
+ */ +package org.netbeans.jemmy.drivers.lists; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/menus/APIJMenuDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/menus/APIJMenuDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,122 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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)); + } + mio.doClick(); + ((JMenuOperator) oper).setPopupMenuVisible(false); + waitNoPopupMenu(oper); + return item; + } + } + + protected void waitNoPopupMenu(final ComponentOperator oper) { + oper.waitState(new ComponentChooser() { + @Override + public boolean checkComponent(Component comp) { + return !((JMenuOperator) oper).isPopupMenuVisible(); + } + + @Override + public String getDescription() { + return ((JMenuOperator) oper).getText() + "'s popup"; + } + + @Override + public String toString() { + return "waitNoPopupMenu.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/menus/AppleMenuDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/menus/AppleMenuDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,140 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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"}); + } + + @Override + 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 (MenuElement subElement : subElements) { + if (subElement instanceof JMenu + && ((JMenu) subElement).isSelected()) { + return subElement; + } else if (subElement instanceof JMenuItem + && ((JMenuItem) subElement).isSelected()) { + return subElement; + } + } + return null; + } + + private static int getDesiredElementIndex(MenuElement bar, PathChooser chooser, int depth) { + MenuElement[] subElements = bar.getSubElements()[0].getSubElements(); + int realIndex = 0; + for (MenuElement subElement : subElements) { + // do not count invisible and disabled menu items + if (subElement instanceof JMenuItem && ((JMenuItem) subElement).isVisible() && ((JMenuItem) subElement).isEnabled()) { + if (chooser.checkPathComponent(depth, subElement)) { + return realIndex; + } + realIndex++; + } + } + return -1; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/menus/DefaultJMenuDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/menus/DefaultJMenuDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,265 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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"}); + } + + @Override + 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 { + itemOper = new JMenuItemOperator(item); + } + 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() { + @Override + public boolean checkComponent(Component comp) { + return (comp == ((JMenuOperator) oper).getPopupMenu() + && comp.isShowing()); + } + + @Override + public String getDescription() { + return ((JMenuOperator) oper).getText() + "'s popup"; + } + + @Override + public String toString() { + return "waitPopupMenu.ComponentChooser{description = " + getDescription() + '}'; + } + }).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 (MenuElement subElement : subElements) { + if (subElement instanceof JMenu + && ((JMenu) subElement).isPopupMenuVisible()) { + return subElement; + } + } + return null; + } + + private static 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; + } + + @Override + public MenuElement actionProduced(Void obj) { + if (!((Component) cont).isShowing()) { + return null; + } + MenuElement[] subElements = cont.getSubElements(); + for (MenuElement subElement : subElements) { + if (((Component) subElement).isShowing() && ((Component) subElement).isEnabled() + && chooser.checkPathComponent(depth, subElement)) { + return subElement; + } + } + return null; + } + + @Override + public String getDescription() { + return ""; + } + + @Override + public String toString() { + return "JMenuItemWaiter{" + "cont=" + cont + ", chooser=" + chooser + ", depth=" + depth + '}'; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/menus/QueueJMenuDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/menus/QueueJMenuDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,325 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); + } + + @Override + 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) { + @Override + 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); + } + } + + @Override + 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); + } + } + + @Override + protected void process(MenuElement element) { + super.process(element); + } + + @Override + public MenuElement getMenuElement() { + return (MenuElement) oper.getSource(); + } + }; + } else if (oper instanceof JPopupMenuOperator) { + action = new OneReleaseAction(chooser, 0, oper, false) { + @Override + public MenuElement getMenuElement() { + return (MenuElement) oper.getSource(); + } + }; + } else { + DriverManager.getButtonDriver(oper).press(oper); + action = new OneReleaseAction(chooser, 0, oper, false) { + @Override + public MenuElement launch() { + process((MenuElement) oper.getSource()); + return (MenuElement) oper.getSource(); + } + + @Override + public MenuElement getMenuElement() { + return null; + } + }; + } + queueTool.waitEmpty(10); + queueTool.waitEmpty(10); + queueTool.waitEmpty(10); + 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) { + @Override + public MenuElement getMenuElement() { + Window win = JPopupMenuOperator.findJPopupWindow(popupChooser); + if (win != null && win.isShowing()) { + return JPopupMenuOperator.findJPopupMenu(win, popupChooser); + } else { + return null; + } + } + }; + result = 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() { + @Override + public MenuElement actionProduced(Void param) { + return queueTool.invokeSmoothly(action); + } + + @Override + public String getDescription() { + return description; + } + + @Override + public String toString() { + return "runAction.Waiter{description = " + getDescription() + '}'; + } + }); + 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 (MenuElement subElement : subElements) { + if (subElement instanceof JMenu + && ((JMenu) subElement).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")); + } + } + + @Override + public MenuElement launch() { + MenuElement element = getMenuElement(); + if (element != null) { + MenuElement[] subElements = element.getSubElements(); + for (MenuElement subElement : subElements) { + if (((Component) subElement).isShowing() + && ((Component) subElement).isEnabled() + && chooser.checkPathComponent(depth, subElement)) { + process(subElement); + return subElement; + } + if (stopped) { + return null; + } + } + } + return null; + } + + public abstract MenuElement getMenuElement(); + + private void stop() { + stopped = true; + } + } + + private static class PopupMenuChooser implements ComponentChooser { + + JMenu menu; + + public PopupMenuChooser(JMenu menu) { + this.menu = menu; + } + + @Override + public boolean checkComponent(Component comp) { + return (comp == menu.getPopupMenu() + && comp.isShowing() && comp.isEnabled()); + } + + @Override + public String getDescription() { + return menu.getText() + "'s popup"; + } + + @Override + public String toString() { + return "PopupMenuChooser{" + "menu=" + menu + '}'; + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/menus/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/menus/package-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/** + *

Menu drivers.

+ * Different drivers to perform a menu operations.
+ *
+ */ +package org.netbeans.jemmy.drivers.menus; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/package-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/** + *

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 + *
+ */ +package org.netbeans.jemmy.drivers; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/AWTScrollDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/AWTScrollDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,165 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); + } + + @Override + protected void step(final ComponentOperator oper, final ScrollAdjuster adj) { + if (adj.getScrollDirection() != ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION) { + queueTool.invokeSmoothly(new QueueTool.QueueAction("Scrolling by clicking with mouse") { + @Override + public Void 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; + } + }); + } + } + + @Override + protected void jump(ComponentOperator oper, ScrollAdjuster adj) { + } + + @Override + protected void startPushAndWait(final ComponentOperator oper, final int direction, final int orientation) { + queueTool.invokeSmoothly(new QueueTool.QueueAction("Scrolling: pressing the mouse button and holding") { + @Override + public Void 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; + } + }); + } + + @Override + protected void stopPushAndWait(final ComponentOperator oper, final int direction, final int orientation) { + queueTool.invokeSmoothly(new QueueTool.QueueAction("Scrolling: releasing the mouse button") { + @Override + public Void 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; + } + }); + } + + @Override + protected Point startDragging(ComponentOperator oper) { + return null; + } + + @Override + protected void drop(ComponentOperator oper, Point pnt) { + } + + @Override + protected void drag(ComponentOperator oper, Point pnt) { + } + + @Override + protected Timeout getScrollDeltaTimeout(ComponentOperator oper) { + return (oper.getTimeouts(). + create("ScrollbarOperator.DragAndDropScrollingDelta")); + } + + @Override + protected boolean canDragAndDrop(ComponentOperator oper) { + return false; + } + + @Override + protected boolean canJump(ComponentOperator oper) { + return false; + } + + @Override + protected boolean canPushAndWait(ComponentOperator oper) { + return true; + } + + @Override + 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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/AbstractScrollDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/AbstractScrollDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,277 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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.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 {@code ADJUST_CLICK_COUNT}. + * + * @author Alexandre Iline(alexandre.iline@oracle.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); + } + + @Override + 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 != ScrollAdjuster.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 != ScrollAdjuster.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 != ScrollAdjuster.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 != ScrollAdjuster.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))); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/JScrollBarAPIDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/JScrollBarAPIDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,158 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); + } + + @Override + public void scrollToMinimum(ComponentOperator oper, int orientation) { + JScrollBarOperator scroll = (JScrollBarOperator) oper; + setValue(oper, scroll.getMinimum()); + } + + @Override + public void scrollToMaximum(ComponentOperator oper, int orientation) { + JScrollBarOperator scroll = (JScrollBarOperator) oper; + setValue(oper, scroll.getMaximum() - scroll.getVisibleAmount()); + } + + @Override + protected void step(ComponentOperator oper, ScrollAdjuster adj) { + JScrollBarOperator scroll = (JScrollBarOperator) oper; + int newValue = -1; + if (adj.getScrollDirection() == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { + newValue = (scroll.getValue() > scroll.getMinimum() + + scroll.getUnitIncrement()) + ? scroll.getValue() - scroll.getUnitIncrement() + : scroll.getMinimum(); + } else if (adj.getScrollDirection() == ScrollAdjuster.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); + } + } + + @Override + protected Timeout getScrollDeltaTimeout(ComponentOperator oper) { + return (oper.getTimeouts(). + create("JScrollBarOperator.DragAndDropScrollingDelta")); + } + + @Override + protected void jump(final ComponentOperator oper, final ScrollAdjuster adj) { + JScrollBarOperator scroll = (JScrollBarOperator) oper; + int newValue = -1; + if (adj.getScrollDirection() == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { + newValue = (scroll.getValue() > scroll.getMinimum() + + scroll.getBlockIncrement()) + ? scroll.getValue() - scroll.getBlockIncrement() + : scroll.getMinimum(); + } else if (adj.getScrollDirection() == ScrollAdjuster.INCREASE_SCROLL_DIRECTION) { + newValue = (scroll.getValue() < scroll.getMaximum() + - scroll.getVisibleAmount() - scroll.getBlockIncrement()) + ? scroll.getValue() + scroll.getBlockIncrement() + : scroll.getMaximum(); + } + setValue(oper, newValue); + } + + @Override + protected void startPushAndWait(ComponentOperator oper, int direction, int orientation) { + } + + @Override + protected void stopPushAndWait(ComponentOperator oper, int direction, int orientation) { + } + + @Override + protected Point startDragging(ComponentOperator oper) { + return null; + } + + @Override + protected void drop(ComponentOperator oper, Point pnt) { + } + + @Override + protected void drag(ComponentOperator oper, Point pnt) { + } + + @Override + protected boolean canDragAndDrop(ComponentOperator oper) { + return false; + } + + @Override + protected boolean canJump(ComponentOperator oper) { + return isSmallIncrement((JScrollBarOperator) oper); + } + + @Override + protected boolean canPushAndWait(ComponentOperator oper) { + return false; + } + + @Override + protected int getDragAndDropStepLength(ComponentOperator oper) { + return 1; + } + + private boolean isSmallIncrement(JScrollBarOperator oper) { + return (oper.getUnitIncrement(-1) <= SMALL_INCREMENT + && oper.getUnitIncrement(1) <= SMALL_INCREMENT); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/JScrollBarDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/JScrollBarDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,252 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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; +import org.netbeans.jemmy.operators.Operator; + +/** + * ScrollDriver for javax.swing.JScrollBar component type. + * + * @author Alexandre Iline(alexandre.iline@oracle.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(); + } + + @Override + 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); + } + + @Override + 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); + } + + @Override + protected void step(ComponentOperator oper, ScrollAdjuster adj) { + JButtonOperator boper = findAButton(oper, adj.getScrollDirection()); + DriverManager.getButtonDriver(boper).push(boper); + } + + @Override + protected void jump(final ComponentOperator oper, final ScrollAdjuster adj) { + final JButtonOperator lessButton = findAButton(oper, ScrollAdjuster.DECREASE_SCROLL_DIRECTION); + final JButtonOperator moreButton = findAButton(oper, ScrollAdjuster.INCREASE_SCROLL_DIRECTION); + queueTool.invokeSmoothly(new QueueTool.QueueAction("Scrolling by clicking with the mouse") { + @Override + public Void launch() { + if (adj.getScrollDirection() != ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION) { + int x, y; + switch (((JScrollBarOperator) oper).getOrientation()) { + case JScrollBar.HORIZONTAL: + switch (adj.getScrollDirection()) { + case ScrollAdjuster.INCREASE_SCROLL_DIRECTION: + x = moreButton.getX() - 1; + break; + case ScrollAdjuster.DECREASE_SCROLL_DIRECTION: + x = lessButton.getX() + lessButton.getWidth(); + break; + default: + return null; + } + y = lessButton.getHeight() / 2; + break; + case JScrollBar.VERTICAL: + switch (adj.getScrollDirection()) { + case ScrollAdjuster.INCREASE_SCROLL_DIRECTION: + y = moreButton.getY() - 1; + break; + case ScrollAdjuster.DECREASE_SCROLL_DIRECTION: + y = lessButton.getY() + lessButton.getHeight(); + break; + default: + return null; + } + x = lessButton.getWidth() / 2; + break; + default: + return null; + } + DriverManager.getMouseDriver(oper). + clickMouse(oper, x, y, 1, Operator.getDefaultMouseButton(), 0, new Timeout("", 0)); + } + return null; + } + }); + } + + @Override + protected void startPushAndWait(ComponentOperator oper, int direction, int orientation) { + JButtonOperator boper = findAButton(oper, direction); + DriverManager.getButtonDriver(boper).press(boper); + } + + @Override + protected void stopPushAndWait(ComponentOperator oper, int direction, int orientation) { + JButtonOperator boper = findAButton(oper, direction); + DriverManager.getButtonDriver(boper).release(boper); + } + + @Override + 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, Operator.getDefaultMouseButton(), 0); + return pnt; + } + + @Override + protected void drop(ComponentOperator oper, Point pnt) { + DriverManager.getMouseDriver(oper). + releaseMouse(oper, pnt.x, pnt.y, Operator.getDefaultMouseButton(), 0); + } + + @Override + protected void drag(ComponentOperator oper, Point pnt) { + DriverManager.getMouseDriver(oper). + dragMouse(oper, pnt.x, pnt.y, Operator.getDefaultMouseButton(), 0); + } + + @Override + protected Timeout getScrollDeltaTimeout(ComponentOperator oper) { + return (oper.getTimeouts(). + create("ScrollbarOperator.DragAndDropScrollingDelta")); + } + + @Override + 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, Operator.getDefaultMouseButton(), 0); + result = ((JScrollBarOperator) oper).getValueIsAdjusting(); + mdriver.releaseMouse(oper, pnt.x, pnt.y, Operator.getDefaultMouseButton(), 0); + return result && isSmallIncrement((JScrollBarOperator) oper); + } + + @Override + protected boolean canJump(ComponentOperator oper) { + return isSmallIncrement((JScrollBarOperator) oper); + } + + @Override + protected boolean canPushAndWait(ComponentOperator oper) { + return isSmallIncrement((JScrollBarOperator) oper); + } + + @Override + 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 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()); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/JSliderAPIDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/JSliderAPIDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,168 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); + } + + @Override + public void scrollToMinimum(final ComponentOperator oper, int orientation) { + ((JSliderOperator) oper).setValue(((JSliderOperator) oper).getMinimum()); + } + + @Override + public void scrollToMaximum(final ComponentOperator oper, int orientation) { + ((JSliderOperator) oper).setValue(((JSliderOperator) oper).getMaximum()); + } + + @Override + protected void step(ComponentOperator oper, ScrollAdjuster adj) { + JSliderOperator scroll = (JSliderOperator) oper; + int newValue = -1; + if (adj.getScrollDirection() == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { + newValue = (scroll.getValue() > scroll.getMinimum() + + getUnitIncrement(scroll)) + ? scroll.getValue() - getUnitIncrement(scroll) + : scroll.getMinimum(); + } else if (adj.getScrollDirection() == ScrollAdjuster.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); + } + } + + @Override + protected Timeout getScrollDeltaTimeout(ComponentOperator oper) { + return (oper.getTimeouts(). + create("JSliderOperator.ScrollingDelta")); + } + + @Override + protected void jump(final ComponentOperator oper, final ScrollAdjuster adj) { + JSliderOperator scroll = (JSliderOperator) oper; + int newValue = -1; + if (adj.getScrollDirection() == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { + newValue = (scroll.getValue() > scroll.getMinimum() + + getBlockIncrement(scroll)) + ? scroll.getValue() - getBlockIncrement(scroll) + : scroll.getMinimum(); + } else if (adj.getScrollDirection() == ScrollAdjuster.INCREASE_SCROLL_DIRECTION) { + newValue = (scroll.getValue() < scroll.getMaximum() + - getBlockIncrement(scroll)) + ? scroll.getValue() + getBlockIncrement(scroll) + : scroll.getMaximum(); + } + setValue(oper, newValue); + } + + @Override + protected void startPushAndWait(ComponentOperator oper, int direction, int orientation) { + } + + @Override + protected void stopPushAndWait(ComponentOperator oper, int direction, int orientation) { + } + + @Override + protected Point startDragging(ComponentOperator oper) { + return null; + } + + @Override + protected void drop(ComponentOperator oper, Point pnt) { + } + + @Override + protected void drag(ComponentOperator oper, Point pnt) { + } + + @Override + protected boolean canDragAndDrop(ComponentOperator oper) { + return false; + } + + @Override + protected boolean canJump(ComponentOperator oper) { + return isSmallIncrement((JSliderOperator) oper); + } + + @Override + protected boolean canPushAndWait(ComponentOperator oper) { + return false; + } + + @Override + 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); + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/JSliderDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/JSliderDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,259 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); + } + + @Override + public void scrollToMinimum(final ComponentOperator oper, int orientation) { + checkSupported(oper); + scroll(oper, + new ScrollAdjuster() { + @Override + public int getScrollDirection() { + return ((((JSliderOperator) oper).getMinimum() + < ((JSliderOperator) oper).getValue()) + ? DECREASE_SCROLL_DIRECTION + : DO_NOT_TOUCH_SCROLL_DIRECTION); + } + + @Override + public int getScrollOrientation() { + return ((JSliderOperator) oper).getOrientation(); + } + + @Override + public String getDescription() { + return "Scroll to minimum"; + } + + @Override + public String toString() { + return "scrollToMinimum.ScrollAdjuster{description = " + getDescription() + '}'; + } + }); + } + + @Override + public void scrollToMaximum(final ComponentOperator oper, int orientation) { + checkSupported(oper); + scroll(oper, + new ScrollAdjuster() { + @Override + public int getScrollDirection() { + return ((((JSliderOperator) oper).getMaximum() + > ((JSliderOperator) oper).getValue()) + ? INCREASE_SCROLL_DIRECTION + : DO_NOT_TOUCH_SCROLL_DIRECTION); + } + + @Override + public int getScrollOrientation() { + return ((JSliderOperator) oper).getOrientation(); + } + + @Override + public String getDescription() { + return "Scroll to maximum"; + } + + @Override + public String toString() { + return "scrollToMaximum.ScrollAdjuster{description = " + getDescription() + '}'; + } + }); + } + + @Override + protected void step(final ComponentOperator oper, final ScrollAdjuster adj) { + if (adj.getScrollDirection() != ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION) { + queueTool.invokeSmoothly(new QueueTool.QueueAction("Scrolling by clicking with the mouse") { + @Override + public Void 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; + } + }); + } + } + + @Override + protected void jump(ComponentOperator oper, ScrollAdjuster adj) { + //cannot + } + + @Override + protected void startPushAndWait(final ComponentOperator oper, final int direction, final int orientation) { + queueTool.invokeSmoothly(new QueueTool.QueueAction("Start scrolling") { + @Override + public Void 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; + } + }); + } + + @Override + protected void stopPushAndWait(final ComponentOperator oper, final int direction, final int orientation) { + queueTool.invokeSmoothly(new QueueTool.QueueAction("Stop scrolling") { + @Override + public Void 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; + } + }); + } + + @Override + protected Point startDragging(ComponentOperator oper) { + //cannot + return null; + } + + @Override + protected void drop(ComponentOperator oper, Point pnt) { + //cannot + } + + @Override + protected void drag(ComponentOperator oper, Point pnt) { + //cannot + } + + @Override + protected Timeout getScrollDeltaTimeout(ComponentOperator oper) { + return oper.getTimeouts().create("JSliderOperator.ScrollingDelta"); + } + + @Override + protected boolean canDragAndDrop(ComponentOperator oper) { + return false; + } + + @Override + protected boolean canJump(ComponentOperator oper) { + return false; + } + + @Override + protected boolean canPushAndWait(ComponentOperator oper) { + return true; + } + + @Override + 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); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/JSpinnerDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/JSpinnerDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,129 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class JSpinnerDriver extends LightSupportiveDriver implements ScrollDriver { + + /** + * Constructs a JSpinnerDriver object. + */ + public JSpinnerDriver() { + super(new String[]{"org.netbeans.jemmy.operators.JSpinnerOperator"}); + } + + @Override + 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() { + @Override + public int getScrollOrientation() { + return SwingConstants.VERTICAL; + } + + @Override + public String getDescription() { + return "Spin to minimum"; + } + + @Override + public int getScrollDirection() { + if (((JSpinnerOperator) oper).getModel().getPreviousValue() != null) { + return ScrollAdjuster.DECREASE_SCROLL_DIRECTION; + } else { + return ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION; + } + } + + @Override + public String toString() { + return "scrollToMinimum.ScrollAdjuster{description = " + getDescription() + '}'; + } + }); + } + + @Override + 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() { + @Override + public int getScrollOrientation() { + return SwingConstants.VERTICAL; + } + + @Override + public String getDescription() { + return "Spin to maximum"; + } + + @Override + public int getScrollDirection() { + if (((JSpinnerOperator) oper).getModel().getNextValue() != null) { + return ScrollAdjuster.INCREASE_SCROLL_DIRECTION; + } else { + return ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION; + } + } + + @Override + public String toString() { + return "scrollToMaximum.ScrollAdjuster{description = " + getDescription() + '}'; + } + }); + } + + @Override + 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(); + } + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/JSplitPaneDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/JSplitPaneDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,158 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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; +import org.netbeans.jemmy.operators.Operator; + +/** + * ScrollDriver for javax.swing.JSplitPane component type. + * + * @author Alexandre Iline(alexandre.iline@oracle.com) + */ +public class JSplitPaneDriver extends LightSupportiveDriver implements ScrollDriver { + + /** + * Constructs a JSplitPaneDriver. + */ + public JSplitPaneDriver() { + super(new String[]{"org.netbeans.jemmy.operators.JSplitPaneOperator"}); + } + + @Override + public void scroll(ComponentOperator oper, ScrollAdjuster adj) { + moveDividerTo((JSplitPaneOperator) oper, adj); + } + + @Override + public void scrollToMinimum(ComponentOperator oper, int orientation) { + expandTo((JSplitPaneOperator) oper, 0); + } + + @Override + 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() == ScrollAdjuster.DECREASE_SCROLL_DIRECTION) { + nextPosition = (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() == ScrollAdjuster.INCREASE_SCROLL_DIRECTION) { + nextPosition = (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, + Operator.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); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/KeyboardJSliderScrollDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/KeyboardJSliderScrollDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.drivers.scrolling; + +import java.awt.Adjustable; +import java.awt.event.KeyEvent; +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(); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/ScrollAdjuster.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/ScrollAdjuster.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.drivers.scrolling; + +/** + * Specifies scrolling criteria. + * + * @author Alexandre Iline(alexandre.iline@oracle.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(); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/ScrollPaneDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/ScrollPaneDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,151 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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; + } + + @Override + public void scrollToMinimum(ComponentOperator oper, final int orientation) { + final Adjustable adj + = (orientation == Scrollbar.HORIZONTAL) + ? ((ScrollPaneOperator) oper).getHAdjustable() + : ((ScrollPaneOperator) oper).getVAdjustable(); + scroll(oper, + new ScrollAdjuster() { + @Override + public int getScrollDirection() { + return ((adj.getMinimum() < adj.getValue()) + ? DECREASE_SCROLL_DIRECTION + : DO_NOT_TOUCH_SCROLL_DIRECTION); + } + + @Override + public int getScrollOrientation() { + return orientation; + } + + @Override + public String getDescription() { + return "Scroll to minimum"; + } + + @Override + public String toString() { + return "scrollToMinimum.ScrollAdjuster{description = " + getDescription() + '}'; + } + }); + } + + @Override + public void scrollToMaximum(ComponentOperator oper, final int orientation) { + final Adjustable adj + = (orientation == Scrollbar.HORIZONTAL) + ? ((ScrollPaneOperator) oper).getHAdjustable() + : ((ScrollPaneOperator) oper).getVAdjustable(); + scroll(oper, + new ScrollAdjuster() { + @Override + public int getScrollDirection() { + return (((adj.getMaximum() - adj.getVisibleAmount()) > adj.getValue()) + ? INCREASE_SCROLL_DIRECTION + : DO_NOT_TOUCH_SCROLL_DIRECTION); + } + + @Override + public int getScrollOrientation() { + return orientation; + } + + @Override + public String getDescription() { + return "Scroll to maximum"; + } + + @Override + public String toString() { + return "scrollToMaximum.ScrollAdjuster{description = " + getDescription() + '}'; + } + }); + } + + @Override + 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); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/ScrollbarDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/ScrollbarDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,137 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); + } + + @Override + public void scrollToMinimum(final ComponentOperator oper, final int orientation) { + scroll(oper, + new ScrollAdjuster() { + @Override + public int getScrollDirection() { + return ((((ScrollbarOperator) oper).getMinimum() + < ((ScrollbarOperator) oper).getValue()) + ? DECREASE_SCROLL_DIRECTION + : DO_NOT_TOUCH_SCROLL_DIRECTION); + } + + @Override + public int getScrollOrientation() { + return ((ScrollbarOperator) oper).getOrientation(); + } + + @Override + public String getDescription() { + return "Scroll to minimum"; + } + + @Override + public String toString() { + return "scrollToMinimum.ScrollAdjuster{description = " + getDescription() + '}'; + } + }); + } + + @Override + public void scrollToMaximum(final ComponentOperator oper, final int orientation) { + scroll(oper, + new ScrollAdjuster() { + @Override + public int getScrollDirection() { + return (((((ScrollbarOperator) oper).getMaximum() + - ((ScrollbarOperator) oper).getVisibleAmount()) + > ((ScrollbarOperator) oper).getValue()) + ? INCREASE_SCROLL_DIRECTION + : DO_NOT_TOUCH_SCROLL_DIRECTION); + } + + @Override + public int getScrollOrientation() { + return ((ScrollbarOperator) oper).getOrientation(); + } + + @Override + public String getDescription() { + return "Scroll to maximum"; + } + + @Override + public String toString() { + return "scrollToMaximum.ScrollAdjuster{description = " + getDescription() + '}'; + } + }); + } + + @Override + 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); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/scrolling/package-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/** + *

Scrolling drivers

+ * Different drivers to perform a scrolling operations.
+ * + * @since 17 Apr 2002 + *
+ */ +package org.netbeans.jemmy.drivers.scrolling; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/tables/JTableMouseDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/tables/JTableMouseDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,105 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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; +import org.netbeans.jemmy.operators.Operator; + +/** + * TableDriver for javax.swing.JTableDriver component type. + * + * @author Alexandre Iline(alexandre.iline@oracle.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(); + } + + @Override + public void selectCell(ComponentOperator oper, int row, int column) { + clickOnCell((JTableOperator) oper, row, column, 1); + } + + @Override + 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") { + @Override + public Void launch() { + Point point = oper.getPointToClick(row, column); + DriverManager.getMouseDriver(oper). + clickMouse(oper, point.x, point.y, clickCount, + Operator.getDefaultMouseButton(), + 0, + oper.getTimeouts().create("ComponentOperator.MouseClickTimeout")); + return null; + } + }); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/tables/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/tables/package-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/** + *

Table drivers

+ * Different drivers to perform a table operations.
+ * + * @since 17 Apr 2002 + *
+ */ +package org.netbeans.jemmy.drivers.tables; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/AWTTextAPIDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/AWTTextAPIDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class AWTTextAPIDriver extends TextAPIDriver { + + /** + * Constructs a AWTTextAPIDriver. + */ + public AWTTextAPIDriver() { + super(new String[]{"org.netbeans.jemmy.operators.TextComponentOperator"}); + } + + @Override + public String getText(ComponentOperator oper) { + return ((TextComponentOperator) oper).getText(); + } + + @Override + public int getCaretPosition(ComponentOperator oper) { + return ((TextComponentOperator) oper).getCaretPosition(); + } + + @Override + public int getSelectionStart(ComponentOperator oper) { + return ((TextComponentOperator) oper).getSelectionStart(); + } + + @Override + public int getSelectionEnd(ComponentOperator oper) { + return ((TextComponentOperator) oper).getSelectionEnd(); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/AWTTextKeyboardDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/AWTTextKeyboardDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class AWTTextKeyboardDriver extends TextKeyboardDriver { + + /** + * Constructs a AWTTextKeyboardDriver. + */ + public AWTTextKeyboardDriver() { + super(new String[]{"org.netbeans.jemmy.operators.TextComponentOperator"}); + } + + @Override + public String getText(ComponentOperator oper) { + return ((TextComponentOperator) oper).getText(); + } + + @Override + public int getCaretPosition(ComponentOperator oper) { + return ((TextComponentOperator) oper).getCaretPosition(); + } + + @Override + public int getSelectionStart(ComponentOperator oper) { + return ((TextComponentOperator) oper).getSelectionStart(); + } + + @Override + public int getSelectionEnd(ComponentOperator oper) { + return ((TextComponentOperator) oper).getSelectionEnd(); + } + + @Override + 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; + } + + @Override + public Timeout getBetweenTimeout(ComponentOperator oper) { + return oper.getTimeouts().create("TextComponentOperator.BetweenKeysTimeout"); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/DownKey.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/DownKey.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,46 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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; + } + + @Override + public int getDirection() { + return 1; + } + + @Override + public GoAndBackKey getBackKey() { + return backKey; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/EndKey.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/EndKey.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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; + } + + @Override + public int getDirection() { + return 1; + } + + @Override + public int getExpectedPosition() { + return cont.getText(oper).length(); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/GoAndBackKey.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/GoAndBackKey.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.drivers.text; + +abstract class GoAndBackKey extends NavigationKey { + + public GoAndBackKey(int keyCode, int mods) { + super(keyCode, mods); + } + + public abstract GoAndBackKey getBackKey(); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/HomeKey.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/HomeKey.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,40 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.drivers.text; + +class HomeKey extends OffsetKey { + + public HomeKey(int keyCode, int mods) { + super(keyCode, mods); + } + + @Override + public int getDirection() { + return -1; + } + + @Override + public int getExpectedPosition() { + return 0; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/NavigationKey.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/NavigationKey.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,44 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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(); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/OffsetKey.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/OffsetKey.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.drivers.text; + +abstract class OffsetKey extends NavigationKey { + + public OffsetKey(int keyCode, int mods) { + super(keyCode, mods); + } + + public abstract int getExpectedPosition(); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/SwingTextAPIDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/SwingTextAPIDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class SwingTextAPIDriver extends TextAPIDriver { + + /** + * Constructs a SwingTextAPIDriver. + */ + public SwingTextAPIDriver() { + super(new String[]{"org.netbeans.jemmy.operators.JTextComponentOperator"}); + } + + @Override + public String getText(ComponentOperator oper) { + return ((JTextComponentOperator) oper).getDisplayedText(); + } + + @Override + public int getCaretPosition(ComponentOperator oper) { + return ((JTextComponentOperator) oper).getCaretPosition(); + } + + @Override + public int getSelectionStart(ComponentOperator oper) { + return ((JTextComponentOperator) oper).getSelectionStart(); + } + + @Override + public int getSelectionEnd(ComponentOperator oper) { + return ((JTextComponentOperator) oper).getSelectionEnd(); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/SwingTextKeyboardDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/SwingTextKeyboardDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,116 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class SwingTextKeyboardDriver extends TextKeyboardDriver { + + /** + * Constructs a SwingTextKeyboardDriver. + */ + public SwingTextKeyboardDriver() { + super(new String[]{"org.netbeans.jemmy.operators.JTextComponentOperator"}); + } + + @Override + 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); + } + } + + @Override + public String getText(ComponentOperator oper) { + return ((JTextComponentOperator) oper).getDisplayedText(); + } + + @Override + public int getCaretPosition(ComponentOperator oper) { + return ((JTextComponentOperator) oper).getCaretPosition(); + } + + @Override + public int getSelectionStart(ComponentOperator oper) { + return ((JTextComponentOperator) oper).getSelectionStart(); + } + + @Override + public int getSelectionEnd(ComponentOperator oper) { + return ((JTextComponentOperator) oper).getSelectionEnd(); + } + + @Override + 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; + } + + @Override + public Timeout getBetweenTimeout(ComponentOperator oper) { + return oper.getTimeouts().create("TextComponentOperator.BetweenKeysTimeout"); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/TextAPIDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/TextAPIDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,154 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void changeCaretPosition(ComponentOperator oper, int position) { + checkSupported(oper); + if (oper instanceof TextComponentOperator) { + ((TextComponentOperator) oper).setCaretPosition(position); + } else { + ((JTextComponentOperator) oper).setCaretPosition(position); + } + } + + @Override + 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); + } + } + + @Override + public void clearText(ComponentOperator oper) { + if (oper instanceof TextComponentOperator) { + ((TextComponentOperator) oper).setText(""); + } else { + ((JTextComponentOperator) oper).setText(""); + } + } + + @Override + 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)); + } + + @Override + public void changeText(ComponentOperator oper, String text) { + checkSupported(oper); + if (oper instanceof TextComponentOperator) { + ((TextComponentOperator) oper).setText(text); + } else { + ((JTextComponentOperator) oper).setText(text); + } + } + + @Override + 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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/TextKeyboardDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/TextKeyboardDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,223 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void changeCaretPosition(ComponentOperator oper, int position) { + DriverManager.getFocusDriver(oper).giveFocus(oper); + checkSupported(oper); + changeCaretPosition(oper, position, 0); + } + + @Override + 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); + } + + @Override + 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(); + } + } + + @Override + 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 (char cr : crs) { + kDriver.typeKey(oper, map.getCharKey(cr), cr, map.getCharModifiers(cr), pushTime); + betweenTime.sleep(); + } + } + + @Override + public void changeText(ComponentOperator oper, String text) { + clearText(oper); + typeText(oper, text, 0); + } + + @Override + 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 + * {@code 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)); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/UpKey.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/UpKey.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,46 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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; + } + + @Override + public int getDirection() { + return -1; + } + + @Override + public GoAndBackKey getBackKey() { + return backKey; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/text/package-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/** + *

Text drivers

+ * Different drivers to perform a text operations.
+ * + * @since 17 Apr 2002 + *
+ */ +package org.netbeans.jemmy.drivers.text; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/trees/JTreeAPIDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/trees/JTreeAPIDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,97 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class JTreeAPIDriver extends LightSupportiveDriver implements TreeDriver { + + /** + * Constructs a JTreeAPIDriver. + */ + public JTreeAPIDriver() { + super(new String[]{"org.netbeans.jemmy.operators.JTreeOperator"}); + } + + @Override + public void selectItem(ComponentOperator oper, int index) { + selectItems(oper, new int[]{index}); + } + + @Override + public void selectItems(ComponentOperator oper, int[] indices) { + checkSupported(oper); + ((JTreeOperator) oper).clearSelection(); + ((JTreeOperator) oper).addSelectionRows(indices); + } + + @Override + public void expandItem(ComponentOperator oper, int index) { + checkSupported(oper); + ((JTreeOperator) oper).expandRow(index); + } + + @Override + public void collapseItem(ComponentOperator oper, int index) { + checkSupported(oper); + ((JTreeOperator) oper).collapseRow(index); + } + + @Override + 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(); + } + + @Override + public void startEditing(ComponentOperator oper, int index, Timeout waitEditorTime) { + startEditingAndReturnEditor(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()))); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/trees/JTreeMouseDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/trees/JTreeMouseDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,184 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); + } + + @Override + public void selectItem(ComponentOperator oper, int index) { + selectItems(oper, new int[]{index}); + } + + @Override + 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") { + @Override + public Void 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 + } + + @Override + 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") { + @Override + public Void launch() { + Point p = toper.getPointToClick(index); + mdriver.clickMouse(toper, p.x, p.y, 2, Operator.getDefaultMouseButton(), + 0, toper.getTimeouts(). + create("ComponentOperator.MouseClickTimeout")); + return null; + } + }); + } + } + + @Override + 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") { + @Override + public Void launch() { + Point p = toper.getPointToClick(index); + mdriver.clickMouse(toper, p.x, p.y, 2, Operator.getDefaultMouseButton(), + 0, toper.getTimeouts(). + create("ComponentOperator.MouseClickTimeout")); + return null; + } + }); + } + } + + @Override + 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")); + } + + @Override + 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") { + @Override + public Void 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") { + @Override + public Void 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()))); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/trees/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/trees/package-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/** + *

Tree drivers

+ * Different drivers to perform a tree operations.
+ * + * @since 17 Apr 2002 + *
+ */ +package org.netbeans.jemmy.drivers.trees; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/windows/DefaultFrameDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/windows/DefaultFrameDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,76 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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(); + } + + @Override + public void iconify(ComponentOperator oper) { + checkSupported(oper); + eDriver.dispatchEvent(oper.getSource(), + new WindowEvent((Window) oper.getSource(), + WindowEvent.WINDOW_ICONIFIED)); + ((FrameOperator) oper).setState(Frame.ICONIFIED); + } + + @Override + public void deiconify(ComponentOperator oper) { + checkSupported(oper); + eDriver.dispatchEvent(oper.getSource(), + new WindowEvent((Window) oper.getSource(), + WindowEvent.WINDOW_DEICONIFIED)); + ((FrameOperator) oper).setState(Frame.NORMAL); + } + + @Override + public void maximize(ComponentOperator oper) { + checkSupported(oper); + oper.setLocation(0, 0); + Dimension ssize = Toolkit.getDefaultToolkit().getScreenSize(); + oper.setSize(ssize.width, ssize.height); + } + + @Override + public void demaximize(ComponentOperator oper) { + checkSupported(oper); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/windows/DefaultInternalFrameDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/windows/DefaultInternalFrameDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,150 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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.JInternalFrameOperator; + +public class DefaultInternalFrameDriver extends LightSupportiveDriver + implements WindowDriver, FrameDriver, InternalFrameDriver { + + public DefaultInternalFrameDriver() { + super(new String[]{"org.netbeans.jemmy.operators.JInternalFrameOperator"}); + } + + @Override + public void activate(ComponentOperator oper) { + checkSupported(oper); + ((JInternalFrameOperator) oper).moveToFront(); + ((JInternalFrameOperator) oper).getTitleOperator().clickMouse(); + } + + @Override + public void requestClose(ComponentOperator oper) { + checkSupported(oper); + ((JInternalFrameOperator) oper).moveToFront(); + ((JInternalFrameOperator) oper).getCloseButton().push(); + } + + @Override + public void requestCloseAndThenHide(ComponentOperator oper) { + throw new UnsupportedOperationException(); + } + + @Override + @Deprecated + public void close(ComponentOperator oper) { + requestClose(oper); + } + + @Override + public void move(ComponentOperator oper, int x, int y) { + checkSupported(oper); + ComponentOperator titleOperator = ((JInternalFrameOperator) oper).getTitleOperator(); + titleOperator.dragNDrop(titleOperator.getCenterY(), + titleOperator.getCenterY(), + x - oper.getX() + titleOperator.getCenterY(), + y - oper.getY() + titleOperator.getCenterY()); + } + + @Override + public void resize(ComponentOperator oper, int width, int height) { + checkSupported(oper); + oper. + dragNDrop(oper.getWidth() - 1, + oper.getHeight() - 1, + width - 1, + height - 1); + } + + @Override + public void iconify(ComponentOperator oper) { + checkSupported(oper); + ((JInternalFrameOperator) oper).getMinimizeButton().clickMouse(); + } + + @Override + public void deiconify(ComponentOperator oper) { + checkSupported(oper); + ((JInternalFrameOperator) oper).getIconOperator().pushButton(); + } + + @Override + public void maximize(ComponentOperator oper) { + checkSupported(oper); + if (!((JInternalFrameOperator) oper).isMaximum()) { + if (!((JInternalFrameOperator) oper).isSelected()) { + activate(oper); + } + ((JInternalFrameOperator) oper).getMaximizeButton().push(); + } + } + + @Override + public void demaximize(ComponentOperator oper) { + checkSupported(oper); + if (((JInternalFrameOperator) oper).isMaximum()) { + if (!((JInternalFrameOperator) oper).isSelected()) { + activate(oper); + } + ((JInternalFrameOperator) oper).getMaximizeButton().push(); + } + } + + @Override + public Component getTitlePane(ComponentOperator operator) { + ComponentSearcher cs = new ComponentSearcher((Container) operator.getSource()); + cs.setOutput(operator.getOutput().createErrorOutput()); + return (cs.findComponent(new ComponentChooser() { + @Override + public boolean checkComponent(Component comp) { + if (System.getProperty("java.version").startsWith("1.2")) { + return comp.getClass().getName().endsWith("InternalFrameTitlePane"); + } else { + return comp instanceof BasicInternalFrameTitlePane; + } + } + + @Override + public String getDescription() { + return "Title pane"; + } + + @Override + public String toString() { + return "getTitlePane.ComponentChooser{description = " + getDescription() + '}'; + } + })); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/windows/DefaultWindowDriver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/windows/DefaultWindowDriver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,93 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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(); + } + + @Override + 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(oper.getSource(), + FocusEvent.FOCUS_GAINED)); + } + + @Override + public void requestClose(ComponentOperator oper) { + checkSupported(oper); + eDriver.dispatchEvent(oper.getSource(), + new WindowEvent((Window) oper.getSource(), + WindowEvent.WINDOW_CLOSING)); + } + + @Override + public void requestCloseAndThenHide(ComponentOperator oper) { + requestClose(oper); + oper.setVisible(false); + } + + @Override + @Deprecated + public void close(ComponentOperator oper) { + requestClose(oper); + } + + @Override + public void move(ComponentOperator oper, int x, int y) { + checkSupported(oper); + oper.setLocation(x, y); + } + + @Override + public void resize(ComponentOperator oper, int width, int height) { + checkSupported(oper); + oper.setSize(width, height); + eDriver.dispatchEvent(oper.getSource(), + new ComponentEvent(oper.getSource(), + ComponentEvent.COMPONENT_RESIZED)); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/windows/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/windows/package-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,28 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/** + *

Window drivers.

+ * Different drivers to perform a window operations.
+ *
+ */ +package org.netbeans.jemmy.drivers.windows; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/explorer/GUIBrowser.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/explorer/GUIBrowser.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1619 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 {@code GUIBrowser.showBrowser()} method + * using. + * + * @author Alexandre Iline (alexandre.iline@oracle.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() { + @Override + public void actionPerformed(ActionEvent e) { + new ComponentBrowser(getOwnr(), + (ComponentNode) mainTree.getSelectionPath(). + getLastPathComponent()). + setVisible(true); + } + }); + + expandButton = new JButton("Expand All"); + expandButton.setEnabled(false); + expandButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + expandAll(mainTree, + mainTree.getSelectionPath()); + } + }); + + JButton refreshButton = new JButton("Reload in ..."); + refreshButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + reload(Integer.parseInt(refreshDelay.getText())); + } + }); + + JButton dumpButton = new JButton("Dump"); + dumpButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JFileChooser chooser + = new JFileChooser(System.getProperty("user.home")); + chooser.addChoosableFileFilter(new FileFilter() { + @Override + public boolean accept(File f) { + return f.getName().endsWith(".xml"); + } + + @Override + public String getDescription() { + return "xml files"; + } + + @Override + public String toString() { + return "dumpButton.ActionListener{description = " + getDescription() + '}'; + } + }); + chooser.showSaveDialog(GUIBrowser.this); + try { + File file = chooser.getSelectedFile(); + try (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() { + @Override + public void windowActivated(WindowEvent e) { + } + + @Override + public void windowClosed(WindowEvent e) { + setVisible(false); + if (exit) { + System.exit(0); + } + } + + @Override + public void windowClosing(WindowEvent e) { + } + + @Override + public void windowDeactivated(WindowEvent e) { + } + + @Override + public void windowDeiconified(WindowEvent e) { + } + + @Override + public void windowIconified(WindowEvent e) { + } + + @Override + public void windowOpened(WindowEvent e) { + } + }); + addComponentListener(new ComponentListener() { + @Override + public void componentHidden(ComponentEvent e) { + } + + @Override + public void componentMoved(ComponentEvent e) { + } + + @Override + public void componentResized(ComponentEvent e) { + split.setDividerLocation(0.8); + } + + @Override + public void componentShown(ComponentEvent e) { + } + }); + + setSize(800, 400); + } + + boolean shown = false; + + @Override + @Deprecated + 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]; + System.arraycopy(argv, 1, newArgv, 0, argv.length - 1); + try { + new ClassReference(argv[0]).startApplication(newArgv); + } catch (ClassNotFoundException + | InvocationTargetException + | 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() { + @Override + 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 ignored) { + } + } + }).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() { + @Override + public int compare(Field f1, Field f2) { + return f1.getName().compareTo(f2.getName()); + } + }); + Method[] mtds = clzz.getMethods(); + Arrays.sort(mtds, new Comparator() { + @Override + public int compare(Method m1, Method m2) { + return m1.getName().compareTo(m2.getName()); + } + }); + for (Field field : fields) { + if (field.getDeclaringClass().getName().equals(clzz.getName())) { + res.add(new FieldNode(field)); + } + } + for (Method mtd : mtds) { + if (mtd.getDeclaringClass().getName().equals(clzz.getName())) { + res.add(new MethodNode(mtd)); + } + } + ClassNode[] result = new ClassNode[res.size()]; + for (int i = 0; i < result.length; i++) { + result[i] = 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 (Component cmp : cmps) { + if (cmp != null && (propDialog.showAll || cmp.isVisible())) { + if (cmp instanceof Container) { + wwns.add(new ContainerNode((Container) cmp)); + } else { + wwns.add(new ComponentNode(cmp)); + } + } + } + comps = new ComponentNode[wwns.size()]; + for (int i = 0; i < wwns.size(); i++) { + comps[i] = 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; + } + + @Override + public void setComponentImageProvider(ComponentImageProvider provider) { + super.setComponentImageProvider(provider); + for (ComponentNode comp1 : comps) { + comp1.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 (Window wn : wns) { + if (propDialog.showAll || wn.isVisible()) { + wwns.add(new WindowNode(wn)); + } + } + wins = new WindowNode[wwns.size()]; + for (int i = 0; i < wwns.size(); i++) { + wins[i] = 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 (Window wn1 : wns) { + if (propDialog.showAll || wn1.isVisible()) { + count++; + } + } + wins = new WindowNode[count]; + count = 0; + for (Window wn : wns) { + if (propDialog.showAll || wn.isVisible()) { + wins[count] = new WindowNode(wn); + count++; + } + } + } + } + + private static class ClassModel implements TreeModel { + + ClassNode clsn; + + ClassModel(ClassNode clsn) { + this.clsn = clsn; + } + + @Override + public void addTreeModelListener(TreeModelListener l) { + } + + @Override + 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; + } + + @Override + 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; + } + + @Override + 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; + } + + @Override + public Object getRoot() { + return clsn; + } + + @Override + public boolean isLeaf(Object node) { + return getChildCount(node) == 0; + } + + @Override + public void removeTreeModelListener(TreeModelListener l) { + } + + @Override + public void valueForPathChanged(TreePath path, Object newValue) { + } + } + + private static class WindowModel implements TreeModel { + + WindowNode win; + + WindowModel(WindowNode win) { + this.win = win; + } + + @Override + public void addTreeModelListener(TreeModelListener l) { + } + + @Override + public Object getChild(Object parent, int index) { + return ((WindowNode) parent).getWindows()[index]; + } + + @Override + public int getChildCount(Object parent) { + return ((WindowNode) parent).getWindows().length; + } + + @Override + public int getIndexOfChild(Object parent, Object child) { + return ((WindowNode) parent).getWindowIndex((WindowNode) child); + } + + @Override + public Object getRoot() { + return win; + } + + @Override + public boolean isLeaf(Object node) { + return ((WindowNode) node).getWindows().length == 0; + } + + @Override + public void removeTreeModelListener(TreeModelListener l) { + } + + @Override + public void valueForPathChanged(TreePath path, Object newValue) { + } + } + + private static class ComponentModel implements TreeModel { + + ContainerNode cont; + + ComponentModel(ContainerNode cont) { + this.cont = cont; + } + + @Override + public void addTreeModelListener(TreeModelListener l) { + } + + @Override + public Object getChild(Object parent, int index) { + if (parent instanceof ContainerNode) { + return ((ContainerNode) parent).getComponents()[index]; + } else { + return ""; + } + } + + @Override + public int getChildCount(Object parent) { + if (parent instanceof ContainerNode) { + return ((ContainerNode) parent).getComponents().length; + } else { + return 0; + } + } + + @Override + public int getIndexOfChild(Object parent, Object child) { + if (parent instanceof ContainerNode) { + return ((ContainerNode) parent).getComponentIndex((ComponentNode) child); + } else { + return -1; + } + } + + @Override + public Object getRoot() { + return cont; + } + + @Override + public boolean isLeaf(Object node) { + if (node instanceof ContainerNode) { + return ((ContainerNode) node).getComponents().length == 0; + } else { + return true; + } + } + + @Override + public void removeTreeModelListener(TreeModelListener l) { + } + + @Override + public void valueForPathChanged(TreePath path, Object newValue) { + } + } + + private static class WindowRenderer implements TreeCellRenderer, ListCellRenderer { + + public WindowRenderer() { + } + + @Override + public Component getTreeCellRendererComponent(JTree tree, + Object value, + boolean selected, + boolean expanded, + boolean leaf, + int row, + boolean hasFocus) { + return get((ClassNode) value, selected); + } + + @Override + public Component getListCellRendererComponent(JList list, + ClassNode value, + int index, + boolean isSelected, + boolean cellHasFocus) { + return get(value, isSelected); + } + + private Component get(ClassNode value, boolean selected) { + Component result = new JLabel(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 static 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() { + @Override + 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() { + @Override + 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() { + @Override + 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() { + @Override + 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() { + @Override + 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() { + @Override + 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() { + @Override + public void actionPerformed(ActionEvent e) { + save(); + setVisible(false); + } + }); + + JButton cnBUtton = new JButton("Cancel"); + cnBUtton.addActionListener(new ActionListener() { + @Override + 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), + viewTabs.elementAt(i)); + } + try (FileOutputStream fileOutputStream = new FileOutputStream(propFile)) { + props.store(fileOutputStream, + "Jemmy GUIBrowser"); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void load() { + if (propFile.exists()) { + try { + try (FileInputStream fileInputStream = new FileInputStream(propFile)) { + props.load(fileInputStream); + } + 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() { + @Override + public void actionPerformed(ActionEvent e) { + new ComponentBrowser(getOwnr(), + getSelectedNode()). + setVisible(true); + } + }); + + expandButton = new JButton("Expand All"); + expandButton.setEnabled(false); + expandButton.addActionListener(new ActionListener() { + @Override + 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 = 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() { + @Override + 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() { + @Override + public void componentHidden(ComponentEvent e) { + } + + @Override + public void componentMoved(ComponentEvent e) { + } + + @Override + public void componentResized(ComponentEvent e) { + if (winSplit != null) { + winSplit.setDividerLocation(0.8); + } + if (componentSplit != null) { + componentSplit.setDividerLocation(0.8); + } + } + + @Override + 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() { + @Override + public void actionPerformed(ActionEvent e) { + if (mouseEvents.isSelected()) { + listListener.addMouseListener(); + } else { + listListener.removeMouseListener(); + } + } + }); + mouseMotionEvents = new JCheckBox("Mouse motion events"); + mouseMotionEvents.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (mouseMotionEvents.isSelected()) { + listListener.addMouseMotionListener(); + } else { + listListener.removeMouseMotionListener(); + } + } + }); + keyEvents = new JCheckBox("Key events"); + keyEvents.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (keyEvents.isSelected()) { + listListener.addKeyListener(); + } else { + listListener.removeKeyListener(); + } + } + }); + JButton clear = new JButton("Clear list"); + clear.addActionListener(new ActionListener() { + @Override + 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 static class SelectionManager implements TreeSelectionListener, ListSelectionListener { + + Component[] comps; + + public SelectionManager(Component[] comps) { + this.comps = comps; + } + + @Override + public void valueChanged(TreeSelectionEvent e) { + for (Component comp : comps) { + comp.setEnabled(e.getPath() != null); + } + } + + @Override + public void valueChanged(ListSelectionEvent e) { + for (Component comp : comps) { + comp.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 static class ToStringListener implements TreeSelectionListener { + + JTextArea area; + + public ToStringListener(JTextArea area) { + this.area = area; + } + + @Override + 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 static class MyModel extends DefaultTableModel { + + private static final long serialVersionUID = 42L; + + @SuppressWarnings(value = "unchecked") + 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((Vector>) (Vector) getDataVector(), new Comparator>() { + @Override + public int compare(Vector v1, Vector v2) { + return v1.get(0).toString().compareTo(v2.get(0).toString()); + } + }); + } + } + + @Override + public boolean isCellEditable(int x, int y) { + return false; + } + } + + private static class ListListener extends TrialListenerManager { + + DefaultListModel model; + + public ListListener(DefaultListModel m, Component comp) { + super(comp); + model = m; + } + + @Override + void printEvent(AWTEvent e) { + model.addElement(e); + } + } + + private static class ImagePane extends JPanel { + + private static final long serialVersionUID = 42L; + BufferedImage image; + + public ImagePane(BufferedImage image) { + super(); + this.image = image; + setPreferredSize(new Dimension(image.getWidth(), image.getHeight())); + } + + @Override + public void paint(Graphics g) { + g.drawImage(image, 0, 0, null); + } + } + + private static 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/explorer/TrialListenerManager.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/explorer/TrialListenerManager.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,204 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); + } + + @Override + public void setOutput(TestOut output) { + this.output = output; + } + + @Override + 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 = new QueueTool().invokeSmoothly( + new QueueTool.QueueAction("event.toString()") { + @Override + public String launch() { + return event.toString(); + } + } + ); + output.printLine(eventToString); + } + + private class TrialMouseListener implements MouseListener { + + @Override + public void mouseClicked(MouseEvent e) { + printEvent(e); + } + + @Override + public void mouseEntered(MouseEvent e) { + printEvent(e); + } + + @Override + public void mouseExited(MouseEvent e) { + printEvent(e); + } + + @Override + public void mousePressed(MouseEvent e) { + printEvent(e); + } + + @Override + public void mouseReleased(MouseEvent e) { + printEvent(e); + } + } + + private class TrialMouseMotionListener implements MouseMotionListener { + + @Override + public void mouseDragged(MouseEvent e) { + printEvent(e); + } + + @Override + public void mouseMoved(MouseEvent e) { + printEvent(e); + } + } + + private class TrialKeyListener implements KeyListener { + + @Override + public void keyPressed(KeyEvent e) { + printEvent(e); + } + + @Override + public void keyReleased(KeyEvent e) { + printEvent(e); + } + + @Override + public void keyTyped(KeyEvent e) { + printEvent(e); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/explorer/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/explorer/package-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,30 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/** + *

Package org.netbeans.jemmy.explorer

+ * Contains auxiliary classes to explore tested application.
+ * + * @since 23 Feb 2002 + *
+ */ +package org.netbeans.jemmy.explorer; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/ColorImageComparator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/ColorImageComparator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,179 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.image; + +import java.awt.image.BufferedImage; + +/** + * Compares two images with color mapping defined by {@code ColorModel} + * implementation. + * + * @author Alexandre Iline (alexandre.iline@oracle.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 {@code 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 {@code map} color mapping. Actual + * comparision perfomed by {@code 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 {@code 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 + * {@code 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 {@code ImageComparator} passed into constructor, + * or itself if no {@code ImageComparator} was passed, processing both + * images by {@code ColorMap} instance before comparision. + */ + @Override + 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; + } + + @Override + 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 {@code 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; + } + + @Override + public int mapColor(int rgb) { + return (rgb == foreground) ? 0xffffff : 0; + } + } + + /** + * Turns {@code 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; + } + + @Override + public int mapColor(int rgb) { + return (rgb == background) ? 0 : rgb; + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/FileImageComparator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/FileImageComparator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,86 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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)); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/ImageComparator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/ImageComparator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.image; + +import java.awt.image.BufferedImage; + +/** + * Interface for all classes performing image comparison. + * + * @author Alexandre Iline (alexandre.iline@oracle.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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/ImageFinder.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/ImageFinder.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/ImageLoader.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/ImageLoader.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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; +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/ImageSaver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/ImageSaver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,43 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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; +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/ImageTool.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/ImageTool.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,199 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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. + */ + @Deprecated + 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. + */ + @Deprecated + 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; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/PNGImageLoader.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/PNGImageLoader.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class PNGImageLoader implements ImageLoader { + + /** + * Loads an image from a PNG image file. + */ + @Override + public BufferedImage load(String fileName) throws IOException { + return new PNGDecoder(new FileInputStream(fileName)).decode(); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/PNGImageSaver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/PNGImageSaver.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class PNGImageSaver implements ImageSaver { + + /** + * Saves an image into a PNG image file. + */ + @Override + public void save(BufferedImage image, String fileName) throws IOException { + new PNGEncoder(new BufferedOutputStream(new FileOutputStream(fileName)), + PNGEncoder.COLOR_MODE). + encode(image); + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/RoughImageComparator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/RoughImageComparator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,73 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.com) + */ +public class RoughImageComparator implements ImageComparator { + + double roughness = .0; + + /** + * Creates a comparator with {@code 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 + */ + @Override + 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; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/RoughImageFinder.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/RoughImageFinder.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,103 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.image; + +import java.awt.Point; +import java.awt.image.BufferedImage; + +/** + * Performs "rough" image search. + * + * @author Alexandre Iline (alexandre.iline@oracle.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 + */ + @Override + 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; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/StrictImageComparator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/StrictImageComparator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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. + */ + @Override + 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; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/StrictImageFinder.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/StrictImageFinder.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,98 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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. + */ + @Override + 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; + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/image/package-info.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,31 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/** + *

Image library

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

+ * + * @since 9 Nov 2002 + *
+ */ +package org.netbeans.jemmy.image; diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/AbstractButtonOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/AbstractButtonOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1213 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 {@code 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 {@code index+1}'th + * {@code 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 + * {@code 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 {@code 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 {@code 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); + } + + @Override + public void setTimeouts(Timeouts timeouts) { + super.setTimeouts(timeouts); + this.timeouts = timeouts; + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + 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 {@code push()} method in a separate thread. + */ + public void pushNoBlock() { + produceNoBlocking(new NoBlockingAction("Button pushing") { + @Override + public Void doAction(Void param) { + push(); + return null; + } + }); + } + + /** + * Changes selection if necessary. Uses {@code 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 {@code changeSelection(boolean)} method in a separate thread. + * + * @param selected a button selection. + */ + public void changeSelectionNoBlock(boolean selected) { + produceNoBlocking(new NoBlockingAction("Button selection changing") { + @Override + public Void doAction(Boolean param) { + changeSelection(param); + 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() { + @Override + public boolean checkComponent(Component comp) { + return isSelected() == selected; + } + + @Override + public String getDescription() { + return ("Items has been " + + (selected ? "" : "un") + "selected"); + } + + @Override + public String toString() { + return "waitSelected.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + /** + * 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. + */ + @Override + 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 {@code AbstractButton.addActionListener(ActionListener)} + * through queue + */ + public void addActionListener(final ActionListener actionListener) { + runMapping(new MapVoidAction("addActionListener") { + @Override + public void map() { + ((AbstractButton) getSource()).addActionListener(actionListener); + } + }); + } + + /** + * Maps {@code AbstractButton.addChangeListener(ChangeListener)} + * through queue + */ + public void addChangeListener(final ChangeListener changeListener) { + runMapping(new MapVoidAction("addChangeListener") { + @Override + public void map() { + ((AbstractButton) getSource()).addChangeListener(changeListener); + } + }); + } + + /** + * Maps {@code AbstractButton.addItemListener(ItemListener)} through queue + */ + public void addItemListener(final ItemListener itemListener) { + runMapping(new MapVoidAction("addItemListener") { + @Override + public void map() { + ((AbstractButton) getSource()).addItemListener(itemListener); + } + }); + } + + /** + * Maps {@code AbstractButton.doClick()} through queue + */ + public void doClick() { + runMapping(new MapVoidAction("doClick") { + @Override + public void map() { + ((AbstractButton) getSource()).doClick(); + } + }); + } + + /** + * Maps {@code AbstractButton.doClick(int)} through queue + */ + public void doClick(final int i) { + runMapping(new MapVoidAction("doClick") { + @Override + public void map() { + ((AbstractButton) getSource()).doClick(i); + } + }); + } + + /** + * Maps {@code AbstractButton.getActionCommand()} through queue + */ + public String getActionCommand() { + return (runMapping(new MapAction("getActionCommand") { + @Override + public String map() { + return ((AbstractButton) getSource()).getActionCommand(); + } + })); + } + + /** + * Maps {@code AbstractButton.getDisabledIcon()} through queue + */ + public Icon getDisabledIcon() { + return (runMapping(new MapAction("getDisabledIcon") { + @Override + public Icon map() { + return ((AbstractButton) getSource()).getDisabledIcon(); + } + })); + } + + /** + * Maps {@code AbstractButton.getDisabledSelectedIcon()} through queue + */ + public Icon getDisabledSelectedIcon() { + return (runMapping(new MapAction("getDisabledSelectedIcon") { + @Override + public Icon map() { + return ((AbstractButton) getSource()).getDisabledSelectedIcon(); + } + })); + } + + /** + * Maps {@code AbstractButton.getHorizontalAlignment()} through queue + */ + public int getHorizontalAlignment() { + return (runMapping(new MapIntegerAction("getHorizontalAlignment") { + @Override + public int map() { + return ((AbstractButton) getSource()).getHorizontalAlignment(); + } + })); + } + + /** + * Maps {@code AbstractButton.getHorizontalTextPosition()} through queue + */ + public int getHorizontalTextPosition() { + return (runMapping(new MapIntegerAction("getHorizontalTextPosition") { + @Override + public int map() { + return ((AbstractButton) getSource()).getHorizontalTextPosition(); + } + })); + } + + /** + * Maps {@code AbstractButton.getIcon()} through queue + */ + public Icon getIcon() { + return (runMapping(new MapAction("getIcon") { + @Override + public Icon map() { + return ((AbstractButton) getSource()).getIcon(); + } + })); + } + + /** + * Maps {@code AbstractButton.getMargin()} through queue + */ + public Insets getMargin() { + return (runMapping(new MapAction("getMargin") { + @Override + public Insets map() { + return ((AbstractButton) getSource()).getMargin(); + } + })); + } + + /** + * Maps {@code AbstractButton.getMnemonic()} through queue + */ + public int getMnemonic() { + return (runMapping(new MapIntegerAction("getMnemonic") { + @Override + public int map() { + return ((AbstractButton) getSource()).getMnemonic(); + } + })); + } + + /** + * Maps {@code AbstractButton.getModel()} through queue + */ + public ButtonModel getModel() { + return (runMapping(new MapAction("getModel") { + @Override + public ButtonModel map() { + return ((AbstractButton) getSource()).getModel(); + } + })); + } + + /** + * Maps {@code AbstractButton.getPressedIcon()} through queue + */ + public Icon getPressedIcon() { + return (runMapping(new MapAction("getPressedIcon") { + @Override + public Icon map() { + return ((AbstractButton) getSource()).getPressedIcon(); + } + })); + } + + /** + * Maps {@code AbstractButton.getRolloverIcon()} through queue + */ + public Icon getRolloverIcon() { + return (runMapping(new MapAction("getRolloverIcon") { + @Override + public Icon map() { + return ((AbstractButton) getSource()).getRolloverIcon(); + } + })); + } + + /** + * Maps {@code AbstractButton.getRolloverSelectedIcon()} through queue + */ + public Icon getRolloverSelectedIcon() { + return (runMapping(new MapAction("getRolloverSelectedIcon") { + @Override + public Icon map() { + return ((AbstractButton) getSource()).getRolloverSelectedIcon(); + } + })); + } + + /** + * Maps {@code AbstractButton.getSelectedIcon()} through queue + */ + public Icon getSelectedIcon() { + return (runMapping(new MapAction("getSelectedIcon") { + @Override + public Icon map() { + return ((AbstractButton) getSource()).getSelectedIcon(); + } + })); + } + + /** + * Maps {@code AbstractButton.getSelectedObjects()} through queue + */ + public Object[] getSelectedObjects() { + return ((Object[]) runMapping(new MapAction("getSelectedObjects") { + @Override + public Object map() { + return ((AbstractButton) getSource()).getSelectedObjects(); + } + })); + } + + /** + * Maps {@code AbstractButton.getText()} through queue + */ + public String getText() { + return (runMapping(new MapAction("getText") { + @Override + public String map() { + return ((AbstractButton) getSource()).getText(); + } + })); + } + + /** + * Maps {@code AbstractButton.getUI()} through queue + */ + public ButtonUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public ButtonUI map() { + return ((AbstractButton) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code AbstractButton.getVerticalAlignment()} through queue + */ + public int getVerticalAlignment() { + return (runMapping(new MapIntegerAction("getVerticalAlignment") { + @Override + public int map() { + return ((AbstractButton) getSource()).getVerticalAlignment(); + } + })); + } + + /** + * Maps {@code AbstractButton.getVerticalTextPosition()} through queue + */ + public int getVerticalTextPosition() { + return (runMapping(new MapIntegerAction("getVerticalTextPosition") { + @Override + public int map() { + return ((AbstractButton) getSource()).getVerticalTextPosition(); + } + })); + } + + /** + * Maps {@code AbstractButton.isBorderPainted()} through queue + */ + public boolean isBorderPainted() { + return (runMapping(new MapBooleanAction("isBorderPainted") { + @Override + public boolean map() { + return ((AbstractButton) getSource()).isBorderPainted(); + } + })); + } + + /** + * Maps {@code AbstractButton.isContentAreaFilled()} through queue + */ + public boolean isContentAreaFilled() { + return (runMapping(new MapBooleanAction("isContentAreaFilled") { + @Override + public boolean map() { + return ((AbstractButton) getSource()).isContentAreaFilled(); + } + })); + } + + /** + * Maps {@code AbstractButton.isFocusPainted()} through queue + */ + public boolean isFocusPainted() { + return (runMapping(new MapBooleanAction("isFocusPainted") { + @Override + public boolean map() { + return ((AbstractButton) getSource()).isFocusPainted(); + } + })); + } + + /** + * Maps {@code AbstractButton.isRolloverEnabled()} through queue + */ + public boolean isRolloverEnabled() { + return (runMapping(new MapBooleanAction("isRolloverEnabled") { + @Override + public boolean map() { + return ((AbstractButton) getSource()).isRolloverEnabled(); + } + })); + } + + /** + * Maps {@code AbstractButton.isSelected()} through queue + */ + public boolean isSelected() { + return (runMapping(new MapBooleanAction("isSelected") { + @Override + public boolean map() { + return ((AbstractButton) getSource()).isSelected(); + } + })); + } + + /** + * Maps {@code AbstractButton.removeActionListener(ActionListener)} + * through queue + */ + public void removeActionListener(final ActionListener actionListener) { + runMapping(new MapVoidAction("removeActionListener") { + @Override + public void map() { + ((AbstractButton) getSource()).removeActionListener(actionListener); + } + }); + } + + /** + * Maps {@code AbstractButton.removeChangeListener(ChangeListener)} + * through queue + */ + public void removeChangeListener(final ChangeListener changeListener) { + runMapping(new MapVoidAction("removeChangeListener") { + @Override + public void map() { + ((AbstractButton) getSource()).removeChangeListener(changeListener); + } + }); + } + + /** + * Maps {@code AbstractButton.removeItemListener(ItemListener)} through queue + */ + public void removeItemListener(final ItemListener itemListener) { + runMapping(new MapVoidAction("removeItemListener") { + @Override + public void map() { + ((AbstractButton) getSource()).removeItemListener(itemListener); + } + }); + } + + /** + * Maps {@code AbstractButton.setActionCommand(String)} through queue + */ + public void setActionCommand(final String string) { + runMapping(new MapVoidAction("setActionCommand") { + @Override + public void map() { + ((AbstractButton) getSource()).setActionCommand(string); + } + }); + } + + /** + * Maps {@code AbstractButton.setBorderPainted(boolean)} through queue + */ + public void setBorderPainted(final boolean b) { + runMapping(new MapVoidAction("setBorderPainted") { + @Override + public void map() { + ((AbstractButton) getSource()).setBorderPainted(b); + } + }); + } + + /** + * Maps {@code AbstractButton.setContentAreaFilled(boolean)} through queue + */ + public void setContentAreaFilled(final boolean b) { + runMapping(new MapVoidAction("setContentAreaFilled") { + @Override + public void map() { + ((AbstractButton) getSource()).setContentAreaFilled(b); + } + }); + } + + /** + * Maps {@code AbstractButton.setDisabledIcon(Icon)} through queue + */ + public void setDisabledIcon(final Icon icon) { + runMapping(new MapVoidAction("setDisabledIcon") { + @Override + public void map() { + ((AbstractButton) getSource()).setDisabledIcon(icon); + } + }); + } + + /** + * Maps {@code AbstractButton.setDisabledSelectedIcon(Icon)} through queue + */ + public void setDisabledSelectedIcon(final Icon icon) { + runMapping(new MapVoidAction("setDisabledSelectedIcon") { + @Override + public void map() { + ((AbstractButton) getSource()).setDisabledSelectedIcon(icon); + } + }); + } + + /** + * Maps {@code AbstractButton.setFocusPainted(boolean)} through queue + */ + public void setFocusPainted(final boolean b) { + runMapping(new MapVoidAction("setFocusPainted") { + @Override + public void map() { + ((AbstractButton) getSource()).setFocusPainted(b); + } + }); + } + + /** + * Maps {@code AbstractButton.setHorizontalAlignment(int)} through queue + */ + public void setHorizontalAlignment(final int i) { + runMapping(new MapVoidAction("setHorizontalAlignment") { + @Override + public void map() { + ((AbstractButton) getSource()).setHorizontalAlignment(i); + } + }); + } + + /** + * Maps {@code AbstractButton.setHorizontalTextPosition(int)} through queue + */ + public void setHorizontalTextPosition(final int i) { + runMapping(new MapVoidAction("setHorizontalTextPosition") { + @Override + public void map() { + ((AbstractButton) getSource()).setHorizontalTextPosition(i); + } + }); + } + + /** + * Maps {@code AbstractButton.setIcon(Icon)} through queue + */ + public void setIcon(final Icon icon) { + runMapping(new MapVoidAction("setIcon") { + @Override + public void map() { + ((AbstractButton) getSource()).setIcon(icon); + } + }); + } + + /** + * Maps {@code AbstractButton.setMargin(Insets)} through queue + */ + public void setMargin(final Insets insets) { + runMapping(new MapVoidAction("setMargin") { + @Override + public void map() { + ((AbstractButton) getSource()).setMargin(insets); + } + }); + } + + /** + * Maps {@code AbstractButton.setMnemonic(char)} through queue + */ + public void setMnemonic(final char c) { + runMapping(new MapVoidAction("setMnemonic") { + @Override + public void map() { + ((AbstractButton) getSource()).setMnemonic(c); + } + }); + } + + /** + * Maps {@code AbstractButton.setMnemonic(int)} through queue + */ + public void setMnemonic(final int i) { + runMapping(new MapVoidAction("setMnemonic") { + @Override + public void map() { + ((AbstractButton) getSource()).setMnemonic(i); + } + }); + } + + /** + * Maps {@code AbstractButton.setModel(ButtonModel)} through queue + */ + public void setModel(final ButtonModel buttonModel) { + runMapping(new MapVoidAction("setModel") { + @Override + public void map() { + ((AbstractButton) getSource()).setModel(buttonModel); + } + }); + } + + /** + * Maps {@code AbstractButton.setPressedIcon(Icon)} through queue + */ + public void setPressedIcon(final Icon icon) { + runMapping(new MapVoidAction("setPressedIcon") { + @Override + public void map() { + ((AbstractButton) getSource()).setPressedIcon(icon); + } + }); + } + + /** + * Maps {@code AbstractButton.setRolloverEnabled(boolean)} through queue + */ + public void setRolloverEnabled(final boolean b) { + runMapping(new MapVoidAction("setRolloverEnabled") { + @Override + public void map() { + ((AbstractButton) getSource()).setRolloverEnabled(b); + } + }); + } + + /** + * Maps {@code AbstractButton.setRolloverIcon(Icon)} through queue + */ + public void setRolloverIcon(final Icon icon) { + runMapping(new MapVoidAction("setRolloverIcon") { + @Override + public void map() { + ((AbstractButton) getSource()).setRolloverIcon(icon); + } + }); + } + + /** + * Maps {@code AbstractButton.setRolloverSelectedIcon(Icon)} through queue + */ + public void setRolloverSelectedIcon(final Icon icon) { + runMapping(new MapVoidAction("setRolloverSelectedIcon") { + @Override + public void map() { + ((AbstractButton) getSource()).setRolloverSelectedIcon(icon); + } + }); + } + + /** + * Maps {@code AbstractButton.setSelected(boolean)} through queue + */ + public void setSelected(final boolean b) { + runMapping(new MapVoidAction("setSelected") { + @Override + public void map() { + ((AbstractButton) getSource()).setSelected(b); + } + }); + } + + /** + * Maps {@code AbstractButton.setSelectedIcon(Icon)} through queue + */ + public void setSelectedIcon(final Icon icon) { + runMapping(new MapVoidAction("setSelectedIcon") { + @Override + public void map() { + ((AbstractButton) getSource()).setSelectedIcon(icon); + } + }); + } + + /** + * Maps {@code AbstractButton.setText(String)} through queue + */ + public void setText(final String string) { + runMapping(new MapVoidAction("setText") { + @Override + public void map() { + ((AbstractButton) getSource()).setText(string); + } + }); + } + + /** + * Maps {@code AbstractButton.setUI(ButtonUI)} through queue + */ + public void setUI(final ButtonUI buttonUI) { + runMapping(new MapVoidAction("setUI") { + @Override + public void map() { + ((AbstractButton) getSource()).setUI(buttonUI); + } + }); + } + + /** + * Maps {@code AbstractButton.setVerticalAlignment(int)} through queue + */ + public void setVerticalAlignment(final int i) { + runMapping(new MapVoidAction("setVerticalAlignment") { + @Override + public void map() { + ((AbstractButton) getSource()).setVerticalAlignment(i); + } + }); + } + + /** + * Maps {@code AbstractButton.setVerticalTextPosition(int)} through queue + */ + public void setVerticalTextPosition(final int i) { + runMapping(new MapVoidAction("setVerticalTextPosition") { + @Override + 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()); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof AbstractButton) { + if (((AbstractButton) comp).getText() != null) { + return (comparator.equals(((AbstractButton) comp).getText(), + label)); + } + } + return false; + } + + @Override + public String getDescription() { + return "AbstractButton with text \"" + label + "\""; + } + + @Override + public String toString() { + return "AbstractButtonByLabelFinder{" + "label=" + label + ", comparator=" + comparator + '}'; + } + } + + /** + * 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/ButtonOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/ButtonOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,530 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 {@code 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 {@code index+1}'th {@code 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 + * {@code 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 {@code 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 {@code 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); + } + + @Override + public void setTimeouts(Timeouts timeouts) { + super.setTimeouts(timeouts); + this.timeouts = timeouts; + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + 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 {@code push()} method in a separate thread. + */ + public void pushNoBlock() { + produceNoBlocking(new NoBlockingAction("Button pushing") { + @Override + public Void doAction(Void 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. + */ + @Override + public Hashtable getDump() { + Hashtable result = super.getDump(); + if (((Button) getSource()).getLabel() != null) { + result.put(TEXT_DPROP, ((Button) getSource()).getLabel()); + } + return result; + } + + //////////////////////////////////////////////////////// + //Mapping // + /** + * Maps {@code Button.addActionListener(ActionListener)} through queue + */ + public void addActionListener(final ActionListener actionListener) { + runMapping(new MapVoidAction("addActionListener") { + @Override + public void map() { + ((Button) getSource()).addActionListener(actionListener); + } + }); + } + + /** + * Maps {@code Button.getActionCommand()} through queue + */ + public String getActionCommand() { + return (runMapping(new MapAction("getActionCommand") { + @Override + public String map() { + return ((Button) getSource()).getActionCommand(); + } + })); + } + + /** + * Maps {@code Button.getLabel()} through queue + */ + public String getLabel() { + return (runMapping(new MapAction("getLabel") { + @Override + public String map() { + return ((Button) getSource()).getLabel(); + } + })); + } + + /** + * Maps {@code Button.removeActionListener(ActionListener)} through queue + */ + public void removeActionListener(final ActionListener actionListener) { + runMapping(new MapVoidAction("removeActionListener") { + @Override + public void map() { + ((Button) getSource()).removeActionListener(actionListener); + } + }); + } + + /** + * Maps {@code Button.setActionCommand(String)} through queue + */ + public void setActionCommand(final String string) { + runMapping(new MapVoidAction("setActionCommand") { + @Override + public void map() { + ((Button) getSource()).setActionCommand(string); + } + }); + } + + /** + * Maps {@code Button.setLabel(String)} through queue + */ + public void setLabel(final String string) { + runMapping(new MapVoidAction("setLabel") { + @Override + 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()); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof Button) { + if (((Button) comp).getLabel() != null) { + return (comparator.equals(((Button) comp).getLabel(), + label)); + } + } + return false; + } + + @Override + public String getDescription() { + return "Button with label \"" + label + "\""; + } + + @Override + public String toString() { + return "ButtonByLabelFinder{" + "label=" + label + ", comparator=" + comparator + '}'; + } + } + + /** + * 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/CheckboxOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/CheckboxOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,540 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + 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 {@code changeSelection(boolean)} method in a separate thread. + * + * @param selected a button selection. + */ + public void changeSelectionNoBlock(boolean selected) { + produceNoBlocking(new NoBlockingAction("Button selection changing") { + @Override + public Void doAction(Boolean param) { + changeSelection(param); + 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() { + @Override + public boolean checkComponent(Component comp) { + return getState() == selected; + } + + @Override + public String getDescription() { + return ("Items has been " + + (selected ? "" : "un") + "selected"); + } + + @Override + public String toString() { + return "CheckboxOperator.waitSelected.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + /** + * Returns information about component. + */ + @Override + public Hashtable getDump() { + Hashtable result = super.getDump(); + result.put(TEXT_DPROP, ((Checkbox) getSource()).getLabel()); + return result; + } + + //////////////////////////////////////////////////////// + //Mapping // + /** + * Maps {@code Checkbox.addItemListener(ItemListener)} through queue + */ + public void addItemListener(final ItemListener itemListener) { + runMapping(new MapVoidAction("addItemListener") { + @Override + public void map() { + ((Checkbox) getSource()).addItemListener(itemListener); + } + }); + } + + /** + * Maps {@code Checkbox.getCheckboxGroup()} through queue + */ + public CheckboxGroup getCheckboxGroup() { + return (runMapping(new MapAction("getCheckboxGroup") { + @Override + public CheckboxGroup map() { + return ((Checkbox) getSource()).getCheckboxGroup(); + } + })); + } + + /** + * Maps {@code Checkbox.getLabel()} through queue + */ + public String getLabel() { + return (runMapping(new MapAction("getLabel") { + @Override + public String map() { + return ((Checkbox) getSource()).getLabel(); + } + })); + } + + /** + * Maps {@code Checkbox.getState()} through queue + */ + public boolean getState() { + return (runMapping(new MapBooleanAction("getState") { + @Override + public boolean map() { + return ((Checkbox) getSource()).getState(); + } + })); + } + + /** + * Maps {@code Checkbox.removeItemListener(ItemListener)} through queue + */ + public void removeItemListener(final ItemListener itemListener) { + runMapping(new MapVoidAction("removeItemListener") { + @Override + public void map() { + ((Checkbox) getSource()).removeItemListener(itemListener); + } + }); + } + + /** + * Maps {@code Checkbox.setCheckboxGroup(CheckboxGroup)} through queue + */ + public void setCheckboxGroup(final CheckboxGroup grp) { + runMapping(new MapVoidAction("setCheckboxGroup") { + @Override + public void map() { + ((Checkbox) getSource()).setCheckboxGroup(grp); + } + }); + } + + /** + * Maps {@code Checkbox.setLabel(String)} through queue + */ + public void setLabel(final String string) { + runMapping(new MapVoidAction("setLabel") { + @Override + public void map() { + ((Checkbox) getSource()).setLabel(string); + } + }); + } + + /** + * Maps {@code Checkbox.setState(boolean)} through queue + */ + public void setState(final boolean state) { + runMapping(new MapVoidAction("setState") { + @Override + 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()); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof Checkbox) { + if (((Checkbox) comp).getLabel() != null) { + return (comparator.equals(((Checkbox) comp).getLabel(), + label)); + } + } + return false; + } + + @Override + public String getDescription() { + return "Checkbox with label \"" + label + "\""; + } + + @Override + public String toString() { + return "CheckboxByLabelFinder{" + "label=" + label + ", comparator=" + comparator + '}'; + } + } + + /** + * 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/ChoiceOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/ChoiceOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,667 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + 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() { + @Override + public boolean checkComponent(Component comp) { + return getSelectedIndex() == index; + } + + @Override + public String getDescription() { + return "Has " + Integer.toString(index) + "'th item selected"; + } + + @Override + public String toString() { + return "ChoiceOperator.waitItemSelected.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + /** + * Returns information about component. + */ + @Override + 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 {@code Choice.add(String)} through queue + */ + public void add(final String item) { + runMapping(new MapVoidAction("add") { + @Override + public void map() { + ((Choice) getSource()).add(item); + } + }); + } + + /** + * Maps {@code Choice.addItemListener(ItemListener)} through queue + */ + public void addItemListener(final ItemListener itemListener) { + runMapping(new MapVoidAction("addItemListener") { + @Override + public void map() { + ((Choice) getSource()).addItemListener(itemListener); + } + }); + } + + /** + * Maps {@code Choice.addNotify()} through queue + */ + @Override + public void addNotify() { + runMapping(new MapVoidAction("addNotify") { + @Override + public void map() { + getSource().addNotify(); + } + }); + } + + /** + * Maps {@code Choice.getItem(int)} through queue + */ + public String getItem(final int index) { + return (runMapping(new MapAction("getItem") { + @Override + public String map() { + return ((Choice) getSource()).getItem(index); + } + })); + } + + /** + * Maps {@code Choice.getItemCount()} through queue + */ + public int getItemCount() { + return (runMapping(new MapIntegerAction("getItemCount") { + @Override + public int map() { + return ((Choice) getSource()).getItemCount(); + } + })); + } + + /** + * Maps {@code Choice.getSelectedIndex()} through queue + */ + public int getSelectedIndex() { + return (runMapping(new MapIntegerAction("getSelectedIndex") { + @Override + public int map() { + return ((Choice) getSource()).getSelectedIndex(); + } + })); + } + + /** + * Maps {@code Choice.getSelectedItem()} through queue + */ + public String getSelectedItem() { + return (runMapping(new MapAction("getSelectedItem") { + @Override + public String map() { + return ((Choice) getSource()).getSelectedItem(); + } + })); + } + + /** + * Maps {@code Choice.insert(String)} through queue + */ + public void insert(final String item, final int index) { + runMapping(new MapVoidAction("insert") { + @Override + public void map() { + ((Choice) getSource()).insert(item, index); + } + }); + } + + /** + * Maps {@code Choice.remove(int)} through queue + */ + public void remove(final int position) { + runMapping(new MapVoidAction("remove") { + @Override + public void map() { + ((Choice) getSource()).remove(position); + } + }); + } + + /** + * Maps {@code Choice.remove(String)} through queue + */ + public void remove(final String item) { + runMapping(new MapVoidAction("remove") { + @Override + public void map() { + ((Choice) getSource()).remove(item); + } + }); + } + + /** + * Maps {@code Choice.removeAll()} through queue + */ + public void removeAll() { + runMapping(new MapVoidAction("removeAll") { + @Override + public void map() { + ((Choice) getSource()).removeAll(); + } + }); + } + + /** + * Maps {@code Choice.removeItemListener(ItemListener)} through queue + */ + public void removeItemListener(final ItemListener itemListener) { + runMapping(new MapVoidAction("removeItemListener") { + @Override + public void map() { + ((Choice) getSource()).removeItemListener(itemListener); + } + }); + } + + /** + * Maps {@code Choice.select(int)} through queue + */ + public void select(final int pos) { + runMapping(new MapVoidAction("select") { + @Override + public void map() { + ((Choice) getSource()).select(pos); + } + }); + } + + /** + * Maps {@code Choice.select(String)} through queue + */ + public void setState(final String str) { + runMapping(new MapVoidAction("select") { + @Override + 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()); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof Choice) { + if (((Choice) comp).getSelectedItem() != null) { + return (comparator.equals(((Choice) comp).getSelectedItem(), + label)); + } + } + return false; + } + + @Override + public String getDescription() { + return "Choice with label \"" + label + "\""; + } + + @Override + public String toString() { + return "ChoiceBySelectedItemFinder{" + "label=" + label + ", comparator=" + comparator + '}'; + } + } + + /** + * 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/ComponentOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/ComponentOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,2535 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 + * {@code Operator.wait"something happened"(*)}
. + * + * @see org.netbeans.jemmy.Timeouts + * + * @author Alexandre Iline (alexandre.iline@oracle.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 static final long PUSH_KEY_TIMEOUT = 0; + private static final long MOUSE_CLICK_TIMEOUT = 0; + private static final long BEFORE_DRAG_TIMEOUT = 0; + private static final long AFTER_DRAG_TIMEOUT = 0; + private static final long WAIT_COMPONENT_TIMEOUT = 60000; + private static final long WAIT_COMPONENT_ENABLED_TIMEOUT = 60000; + private static final long WAIT_FOCUS_TIMEOUT = 60000; + private static final long WAIT_STATE_TIMEOUT = 60000; + + private final Component source; + private volatile Timeouts timeouts; // used in invokeSmoothly in clickMouse + private volatile TestOut output; // used in QueueTool.Locker + private volatile EventDispatcher dispatcher; // used in JInternalFrameByTitleFinder.checkComponent + 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 {@code index+1}'th {@code 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 {@code 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 {@code 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() { + @Override + public Component actionProduced(Void obj) { + return findComponent(cont, new VisibleComponentFinder(chooser), index, + output.createErrorOutput()); + } + + @Override + public String getDescription() { + return "Wait " + chooser.getDescription() + " loaded"; + } + + @Override + public String toString() { + return "ComponentOperator.waitComponent.Waitable{description = " + getDescription() + '}'; + } + }); + waiter.setTimeoutsToCloneOf(timeouts, "ComponentOperator.WaitComponentTimeout"); + waiter.setOutput(output); + return waiter.waitAction(null); + } catch (InterruptedException e) { + return null; + } + } + + /** + * Searches Components in container. + * + * @param cont Container to search components in. + * @param chooser org.netbeans.jemmy.ComponentChooser implementation. + * @return Component array or empty array if component was not found. + */ + public static Component[] findComponents(Container cont, ComponentChooser chooser) { + ComponentSearcher searcher = new ComponentSearcher(cont); + return searcher.findComponents(new VisibleComponentFinder(chooser)); + } + + 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. + */ + @Override + public Component getSource() { + return source; + } + + /** + * Returns 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 // + //////////////////////////////////////////////////////// + @Override + public void setOutput(TestOut out) { + super.setOutput(out); + this.output = out; + if (dispatcher != null) { + dispatcher.setOutput(output.createErrorOutput()); + } + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + public void setTimeouts(Timeouts timeouts) { + super.setTimeouts(timeouts); + this.timeouts = timeouts; + if (dispatcher != null) { + dispatcher.setTimeouts(getTimeouts()); + } + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + 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()); + fDriver = (FocusDriver) DriverManager. + getDriver(DriverManager.FOCUS_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") { + @Override + public Void 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("Clicking the mouse button") { + @Override + public Void 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("Pressing the mouse button") { + @Override + public Void launch() { + pressMouse(getCenterXForClick(), getCenterYForClick()); + return null; + } + }); + } + + /** + * Releases mouse. + */ + public void releaseMouse() { + getQueueTool().invokeSmoothly(new QueueTool.QueueAction("Releasing the mouse button") { + @Override + public Void 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); + } + + /** + * Typed key. + * + * @param keyChar Char to be typed. + * @param modifiers Modifiers (combination of InputEvent.*_MASK fields) + */ + public void typedKey(char keyChar, int modifiers) { + kDriver.typedKey(this, getCharBindingMap().getCharKey(keyChar), keyChar, modifiers); + } + + /** + * 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() + */ + @Deprecated + public void activateWindow() { + getVisualizer().makeVisible(this); + } + + /** + * Prepares component for user input. Uses visualizer defined by + * setVisualiser() method. + */ + public void makeComponentVisible() { + getVisualizer().makeVisible(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() { + @Override + public Component actionProduced(Component obj) { + if (obj.isEnabled()) { + return obj; + } else { + return null; + } + } + + @Override + public String getDescription() { + return ("Component enabled: " + + getSource().getClass().toString()); + } + + @Override + public String toString() { + return "ComponentOperator.waitComponentEnabled.Waitable{description = " + getDescription() + '}'; + } + }); + 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() { + @Override + public boolean checkComponent(Component comp) { + return comp instanceof Window; + } + + @Override + public String getDescription() { + return ""; + } + + @Override + public String toString() { + return "ComponentOperator.getWindow.ComponentChooser{description = " + getDescription() + '}'; + } + }); + 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() { + @Override + public String actionProduced(Void obj) { + return hasFocus() ? "" : null; + } + + @Override + public String getDescription() { + return "Wait component has focus"; + } + + @Override + public String toString() { + return "ComponentOperator.waitHasFocus.Waitable{description = " + getDescription() + '}'; + } + }); + 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() { + @Override + public boolean checkComponent(Component comp) { + return isVisible() == visibility; + } + + @Override + public String getDescription() { + return "Component is " + (visibility ? "" : " not ") + "visible"; + } + + @Override + public String toString() { + return "ComponentOperator.waitComponentVisible.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + public void waitComponentShowing(final boolean visibility) { + waitState(new ComponentChooser() { + @Override + public boolean checkComponent(Component comp) { + return isShowing() == visibility; + } + + @Override + public String getDescription() { + return "Component is " + (visibility ? "" : " not ") + "showing"; + } + + @Override + public String toString() { + return "ComponentOperator.waitComponentShowing.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + /** + * Returns information about component. + */ + @Override + 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 {@code Component.add(PopupMenu)} through queue + */ + public void add(final PopupMenu popupMenu) { + runMapping(new MapVoidAction("add") { + @Override + public void map() { + getSource().add(popupMenu); + } + }); + } + + /** + * Maps {@code Component.addComponentListener(ComponentListener)} + * through queue + */ + public void addComponentListener(final ComponentListener componentListener) { + runMapping(new MapVoidAction("addComponentListener") { + @Override + public void map() { + getSource().addComponentListener(componentListener); + } + }); + } + + /** + * Maps {@code Component.addFocusListener(FocusListener)} through queue + */ + public void addFocusListener(final FocusListener focusListener) { + runMapping(new MapVoidAction("addFocusListener") { + @Override + public void map() { + getSource().addFocusListener(focusListener); + } + }); + } + + /** + * Maps {@code Component.addInputMethodListener(InputMethodListener)} + * through queue + */ + public void addInputMethodListener(final InputMethodListener inputMethodListener) { + runMapping(new MapVoidAction("addInputMethodListener") { + @Override + public void map() { + getSource().addInputMethodListener(inputMethodListener); + } + }); + } + + /** + * Maps {@code Component.addKeyListener(KeyListener)} through queue + */ + public void addKeyListener(final KeyListener keyListener) { + runMapping(new MapVoidAction("addKeyListener") { + @Override + public void map() { + getSource().addKeyListener(keyListener); + } + }); + } + + /** + * Maps {@code Component.addMouseListener(MouseListener)} through queue + */ + public void addMouseListener(final MouseListener mouseListener) { + runMapping(new MapVoidAction("addMouseListener") { + @Override + public void map() { + getSource().addMouseListener(mouseListener); + } + }); + } + + /** + * Maps {@code Component.addMouseMotionListener(MouseMotionListener)} + * through queue + */ + public void addMouseMotionListener(final MouseMotionListener mouseMotionListener) { + runMapping(new MapVoidAction("addMouseMotionListener") { + @Override + public void map() { + getSource().addMouseMotionListener(mouseMotionListener); + } + }); + } + + /** + * Maps {@code Component.addNotify()} through queue + */ + public void addNotify() { + runMapping(new MapVoidAction("addNotify") { + @Override + public void map() { + getSource().addNotify(); + } + }); + } + + /** + * Maps + * {@code Component.addPropertyChangeListener(PropertyChangeListener)} + * through queue + */ + public void addPropertyChangeListener(final PropertyChangeListener propertyChangeListener) { + runMapping(new MapVoidAction("addPropertyChangeListener") { + @Override + public void map() { + getSource().addPropertyChangeListener(propertyChangeListener); + } + }); + } + + /** + * Maps + * {@code Component.addPropertyChangeListener(String, PropertyChangeListener)} + * through queue + */ + public void addPropertyChangeListener(final String string, final PropertyChangeListener propertyChangeListener) { + runMapping(new MapVoidAction("addPropertyChangeListener") { + @Override + public void map() { + getSource().addPropertyChangeListener(string, propertyChangeListener); + } + }); + } + + /** + * Maps {@code 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") { + @Override + public int map() { + return getSource().checkImage(image, i, i1, imageObserver); + } + })); + } + + /** + * Maps {@code Component.checkImage(Image, ImageObserver)} through queue + */ + public int checkImage(final Image image, final ImageObserver imageObserver) { + return (runMapping(new MapIntegerAction("checkImage") { + @Override + public int map() { + return getSource().checkImage(image, imageObserver); + } + })); + } + + /** + * Maps {@code Component.contains(int, int)} through queue + */ + public boolean contains(final int i, final int i1) { + return (runMapping(new MapBooleanAction("contains") { + @Override + public boolean map() { + return getSource().contains(i, i1); + } + })); + } + + /** + * Maps {@code Component.contains(Point)} through queue + */ + public boolean contains(final Point point) { + return (runMapping(new MapBooleanAction("contains") { + @Override + public boolean map() { + return getSource().contains(point); + } + })); + } + + /** + * Maps {@code Component.createImage(int, int)} through queue + */ + public Image createImage(final int i, final int i1) { + return (runMapping(new MapAction("createImage") { + @Override + public Image map() { + return getSource().createImage(i, i1); + } + })); + } + + /** + * Maps {@code Component.createImage(ImageProducer)} through queue + */ + public Image createImage(final ImageProducer imageProducer) { + return (runMapping(new MapAction("createImage") { + @Override + public Image map() { + return getSource().createImage(imageProducer); + } + })); + } + + /** + * Maps {@code Component.dispatchEvent(AWTEvent)} through queue + */ + public void dispatchEvent(final AWTEvent aWTEvent) { + runMapping(new MapVoidAction("dispatchEvent") { + @Override + public void map() { + getSource().dispatchEvent(aWTEvent); + } + }); + } + + /** + * Maps {@code Component.doLayout()} through queue + */ + public void doLayout() { + runMapping(new MapVoidAction("doLayout") { + @Override + public void map() { + getSource().doLayout(); + } + }); + } + + /** + * Maps {@code Component.enableInputMethods(boolean)} through queue + */ + public void enableInputMethods(final boolean b) { + runMapping(new MapVoidAction("enableInputMethods") { + @Override + public void map() { + getSource().enableInputMethods(b); + } + }); + } + + /** + * Maps {@code Component.getAlignmentX()} through queue + */ + public float getAlignmentX() { + return (runMapping(new MapFloatAction("getAlignmentX") { + @Override + public float map() { + return getSource().getAlignmentX(); + } + })); + } + + /** + * Maps {@code Component.getAlignmentY()} through queue + */ + public float getAlignmentY() { + return (runMapping(new MapFloatAction("getAlignmentY") { + @Override + public float map() { + return getSource().getAlignmentY(); + } + })); + } + + /** + * Maps {@code Component.getBackground()} through queue + */ + public Color getBackground() { + return (runMapping(new MapAction("getBackground") { + @Override + public Color map() { + return getSource().getBackground(); + } + })); + } + + /** + * Maps {@code Component.getBounds()} through queue + */ + public Rectangle getBounds() { + return (runMapping(new MapAction("getBounds") { + @Override + public Rectangle map() { + return getSource().getBounds(); + } + })); + } + + /** + * Maps {@code Component.getBounds(Rectangle)} through queue + */ + public Rectangle getBounds(final Rectangle rectangle) { + return (runMapping(new MapAction("getBounds") { + @Override + public Rectangle map() { + return getSource().getBounds(rectangle); + } + })); + } + + /** + * Maps {@code Component.getColorModel()} through queue + */ + public ColorModel getColorModel() { + return (runMapping(new MapAction("getColorModel") { + @Override + public ColorModel map() { + return getSource().getColorModel(); + } + })); + } + + /** + * Maps {@code Component.getComponentAt(int, int)} through queue + */ + public Component getComponentAt(final int i, final int i1) { + return (runMapping(new MapAction("getComponentAt") { + @Override + public Component map() { + return getSource().getComponentAt(i, i1); + } + })); + } + + /** + * Maps {@code Component.getComponentAt(Point)} through queue + */ + public Component getComponentAt(final Point point) { + return (runMapping(new MapAction("getComponentAt") { + @Override + public Component map() { + return getSource().getComponentAt(point); + } + })); + } + + /** + * Maps {@code Component.getComponentOrientation()} through queue + */ + public ComponentOrientation getComponentOrientation() { + return (runMapping(new MapAction("getComponentOrientation") { + @Override + public ComponentOrientation map() { + return getSource().getComponentOrientation(); + } + })); + } + + /** + * Maps {@code Component.getCursor()} through queue + */ + public Cursor getCursor() { + return (runMapping(new MapAction("getCursor") { + @Override + public Cursor map() { + return getSource().getCursor(); + } + })); + } + + /** + * Maps {@code Component.getDropTarget()} through queue + */ + public DropTarget getDropTarget() { + return (runMapping(new MapAction("getDropTarget") { + @Override + public DropTarget map() { + return getSource().getDropTarget(); + } + })); + } + + /** + * Maps {@code Component.getFont()} through queue + */ + public Font getFont() { + return (runMapping(new MapAction("getFont") { + @Override + public Font map() { + return getSource().getFont(); + } + })); + } + + /** + * Maps {@code Component.getFontMetrics(Font)} through queue + */ + public FontMetrics getFontMetrics(final Font font) { + return (runMapping(new MapAction("getFontMetrics") { + @Override + public FontMetrics map() { + return getSource().getFontMetrics(font); + } + })); + } + + /** + * Maps {@code Component.getForeground()} through queue + */ + public Color getForeground() { + return (runMapping(new MapAction("getForeground") { + @Override + public Color map() { + return getSource().getForeground(); + } + })); + } + + /** + * Maps {@code Component.getGraphics()} through queue + */ + public Graphics getGraphics() { + return (runMapping(new MapAction("getGraphics") { + @Override + public Graphics map() { + return getSource().getGraphics(); + } + })); + } + + /** + * Maps {@code Component.getHeight()} through queue + */ + public int getHeight() { + return (runMapping(new MapIntegerAction("getHeight") { + @Override + public int map() { + return getSource().getHeight(); + } + })); + } + + /** + * Maps {@code Component.getInputContext()} through queue + */ + public InputContext getInputContext() { + return (runMapping(new MapAction("getInputContext") { + @Override + public InputContext map() { + return getSource().getInputContext(); + } + })); + } + + /** + * Maps {@code Component.getInputMethodRequests()} through queue + */ + public InputMethodRequests getInputMethodRequests() { + return (runMapping(new MapAction("getInputMethodRequests") { + @Override + public InputMethodRequests map() { + return getSource().getInputMethodRequests(); + } + })); + } + + /** + * Maps {@code Component.getLocale()} through queue + */ + public Locale getLocale() { + return (runMapping(new MapAction("getLocale") { + @Override + public Locale map() { + return getSource().getLocale(); + } + })); + } + + /** + * Maps {@code Component.getLocation()} through queue + */ + public Point getLocation() { + return (runMapping(new MapAction("getLocation") { + @Override + public Point map() { + return getSource().getLocation(); + } + })); + } + + /** + * Maps {@code Component.getLocation(Point)} through queue + */ + public Point getLocation(final Point point) { + return (runMapping(new MapAction("getLocation") { + @Override + public Point map() { + return getSource().getLocation(point); + } + })); + } + + /** + * Maps {@code Component.getLocationOnScreen()} through queue + */ + public Point getLocationOnScreen() { + return (runMapping(new MapAction("getLocationOnScreen") { + @Override + public Point map() { + return getSource().getLocationOnScreen(); + } + })); + } + + /** + * Maps {@code Component.getMaximumSize()} through queue + */ + public Dimension getMaximumSize() { + return (runMapping(new MapAction("getMaximumSize") { + @Override + public Dimension map() { + return getSource().getMaximumSize(); + } + })); + } + + /** + * Maps {@code Component.getMinimumSize()} through queue + */ + public Dimension getMinimumSize() { + return (runMapping(new MapAction("getMinimumSize") { + @Override + public Dimension map() { + return getSource().getMinimumSize(); + } + })); + } + + /** + * Maps {@code Component.getName()} through queue + */ + public String getName() { + return (runMapping(new MapAction("getName") { + @Override + public String map() { + return getSource().getName(); + } + })); + } + + /** + * Maps {@code Component.getParent()} through queue + */ + public Container getParent() { + return (runMapping(new MapAction("getParent") { + @Override + public Container map() { + return getSource().getParent(); + } + })); + } + + /** + * Maps {@code Component.getPreferredSize()} through queue + */ + public Dimension getPreferredSize() { + return (runMapping(new MapAction("getPreferredSize") { + @Override + public Dimension map() { + return getSource().getPreferredSize(); + } + })); + } + + /** + * Maps {@code Component.getSize()} through queue + */ + public Dimension getSize() { + return (runMapping(new MapAction("getSize") { + @Override + public Dimension map() { + return getSource().getSize(); + } + })); + } + + /** + * Maps {@code Component.getSize(Dimension)} through queue + */ + public Dimension getSize(final Dimension dimension) { + return (runMapping(new MapAction("getSize") { + @Override + public Dimension map() { + return getSource().getSize(dimension); + } + })); + } + + /** + * Maps {@code Component.getToolkit()} through queue + */ + public Toolkit getToolkit() { + return (runMapping(new MapAction("getToolkit") { + @Override + public Toolkit map() { + return getSource().getToolkit(); + } + })); + } + + /** + * Maps {@code Component.getTreeLock()} through queue + */ + public Object getTreeLock() { + return (runMapping(new MapAction("getTreeLock") { + @Override + public Object map() { + return getSource().getTreeLock(); + } + })); + } + + /** + * Maps {@code Component.getWidth()} through queue + */ + public int getWidth() { + return (runMapping(new MapIntegerAction("getWidth") { + @Override + public int map() { + return getSource().getWidth(); + } + })); + } + + /** + * Maps {@code Component.getX()} through queue + */ + public int getX() { + return (runMapping(new MapIntegerAction("getX") { + @Override + public int map() { + return getSource().getX(); + } + })); + } + + /** + * Maps {@code Component.getY()} through queue + */ + public int getY() { + return (runMapping(new MapIntegerAction("getY") { + @Override + public int map() { + return getSource().getY(); + } + })); + } + + /** + * Maps {@code Component.hasFocus()} through queue + */ + public boolean hasFocus() { + return (runMapping(new MapBooleanAction("hasFocus") { + @Override + public boolean map() { + return getSource().hasFocus(); + } + })); + } + + /** + * Maps {@code 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") { + @Override + public boolean map() { + return getSource().imageUpdate(image, i, i1, i2, i3, i4); + } + })); + } + + /** + * Maps {@code Component.invalidate()} through queue + */ + public void invalidate() { + runMapping(new MapVoidAction("invalidate") { + @Override + public void map() { + getSource().invalidate(); + } + }); + } + + /** + * Maps {@code Component.isDisplayable()} through queue + */ + public boolean isDisplayable() { + return (runMapping(new MapBooleanAction("isDisplayable") { + @Override + public boolean map() { + return getSource().isDisplayable(); + } + })); + } + + /** + * Maps {@code Component.isDoubleBuffered()} through queue + */ + public boolean isDoubleBuffered() { + return (runMapping(new MapBooleanAction("isDoubleBuffered") { + @Override + public boolean map() { + return getSource().isDoubleBuffered(); + } + })); + } + + /** + * Maps {@code Component.isEnabled()} through queue + */ + public boolean isEnabled() { + return (runMapping(new MapBooleanAction("isEnabled") { + @Override + public boolean map() { + return getSource().isEnabled(); + } + })); + } + + /** + * Maps {@code Component.isFocusTraversable()} through queue + */ + @Deprecated + public boolean isFocusTraversable() { + return (runMapping(new MapBooleanAction("isFocusTraversable") { + @Override + public boolean map() { + return getSource().isFocusTraversable(); + } + })); + } + + /** + * Maps {@code Component.isLightweight()} through queue + */ + public boolean isLightweight() { + return (runMapping(new MapBooleanAction("isLightweight") { + @Override + public boolean map() { + return getSource().isLightweight(); + } + })); + } + + /** + * Maps {@code Component.isOpaque()} through queue + */ + public boolean isOpaque() { + return (runMapping(new MapBooleanAction("isOpaque") { + @Override + public boolean map() { + return getSource().isOpaque(); + } + })); + } + + /** + * Maps {@code Component.isShowing()} through queue + */ + public boolean isShowing() { + return (runMapping(new MapBooleanAction("isShowing") { + @Override + public boolean map() { + return getSource().isShowing(); + } + })); + } + + /** + * Maps {@code Component.isValid()} through queue + */ + public boolean isValid() { + return (runMapping(new MapBooleanAction("isValid") { + @Override + public boolean map() { + return getSource().isValid(); + } + })); + } + + /** + * Maps {@code Component.isVisible()} through queue + */ + public boolean isVisible() { + return (runMapping(new MapBooleanAction("isVisible") { + @Override + public boolean map() { + return getSource().isVisible(); + } + })); + } + + /** + * Maps {@code Component.list()} through queue + */ + public void list() { + runMapping(new MapVoidAction("list") { + @Override + public void map() { + getSource().list(); + } + }); + } + + /** + * Maps {@code Component.list(PrintStream)} through queue + */ + public void list(final PrintStream printStream) { + runMapping(new MapVoidAction("list") { + @Override + public void map() { + getSource().list(printStream); + } + }); + } + + /** + * Maps {@code Component.list(PrintStream, int)} through queue + */ + public void list(final PrintStream printStream, final int i) { + runMapping(new MapVoidAction("list") { + @Override + public void map() { + getSource().list(printStream, i); + } + }); + } + + /** + * Maps {@code Component.list(PrintWriter)} through queue + */ + public void list(final PrintWriter printWriter) { + runMapping(new MapVoidAction("list") { + @Override + public void map() { + getSource().list(printWriter); + } + }); + } + + /** + * Maps {@code Component.list(PrintWriter, int)} through queue + */ + public void list(final PrintWriter printWriter, final int i) { + runMapping(new MapVoidAction("list") { + @Override + public void map() { + getSource().list(printWriter, i); + } + }); + } + + /** + * Maps {@code Component.paint(Graphics)} through queue + */ + public void paint(final Graphics graphics) { + runMapping(new MapVoidAction("paint") { + @Override + public void map() { + getSource().paint(graphics); + } + }); + } + + /** + * Maps {@code Component.paintAll(Graphics)} through queue + */ + public void paintAll(final Graphics graphics) { + runMapping(new MapVoidAction("paintAll") { + @Override + public void map() { + getSource().paintAll(graphics); + } + }); + } + + /** + * Maps {@code 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") { + @Override + public boolean map() { + return getSource().prepareImage(image, i, i1, imageObserver); + } + })); + } + + /** + * Maps {@code Component.prepareImage(Image, ImageObserver)} through queue + */ + public boolean prepareImage(final Image image, final ImageObserver imageObserver) { + return (runMapping(new MapBooleanAction("prepareImage") { + @Override + public boolean map() { + return getSource().prepareImage(image, imageObserver); + } + })); + } + + /** + * Maps {@code Component.print(Graphics)} through queue + */ + public void print(final Graphics graphics) { + runMapping(new MapVoidAction("print") { + @Override + public void map() { + getSource().print(graphics); + } + }); + } + + /** + * Maps {@code Component.printAll(Graphics)} through queue + */ + public void printAll(final Graphics graphics) { + runMapping(new MapVoidAction("printAll") { + @Override + public void map() { + getSource().printAll(graphics); + } + }); + } + + /** + * Maps {@code Component.remove(MenuComponent)} through queue + */ + public void remove(final MenuComponent menuComponent) { + runMapping(new MapVoidAction("remove") { + @Override + public void map() { + getSource().remove(menuComponent); + } + }); + } + + /** + * Maps {@code Component.removeComponentListener(ComponentListener)} + * through queue + */ + public void removeComponentListener(final ComponentListener componentListener) { + runMapping(new MapVoidAction("removeComponentListener") { + @Override + public void map() { + getSource().removeComponentListener(componentListener); + } + }); + } + + /** + * Maps {@code Component.removeFocusListener(FocusListener)} through queue + */ + public void removeFocusListener(final FocusListener focusListener) { + runMapping(new MapVoidAction("removeFocusListener") { + @Override + public void map() { + getSource().removeFocusListener(focusListener); + } + }); + } + + /** + * Maps + * {@code Component.removeInputMethodListener(InputMethodListener)} + * through queue + */ + public void removeInputMethodListener(final InputMethodListener inputMethodListener) { + runMapping(new MapVoidAction("removeInputMethodListener") { + @Override + public void map() { + getSource().removeInputMethodListener(inputMethodListener); + } + }); + } + + /** + * Maps {@code Component.removeKeyListener(KeyListener)} through queue + */ + public void removeKeyListener(final KeyListener keyListener) { + runMapping(new MapVoidAction("removeKeyListener") { + @Override + public void map() { + getSource().removeKeyListener(keyListener); + } + }); + } + + /** + * Maps {@code Component.removeMouseListener(MouseListener)} through queue + */ + public void removeMouseListener(final MouseListener mouseListener) { + runMapping(new MapVoidAction("removeMouseListener") { + @Override + public void map() { + getSource().removeMouseListener(mouseListener); + } + }); + } + + /** + * Maps + * {@code Component.removeMouseMotionListener(MouseMotionListener)} + * through queue + */ + public void removeMouseMotionListener(final MouseMotionListener mouseMotionListener) { + runMapping(new MapVoidAction("removeMouseMotionListener") { + @Override + public void map() { + getSource().removeMouseMotionListener(mouseMotionListener); + } + }); + } + + /** + * Maps {@code Component.removeNotify()} through queue + */ + public void removeNotify() { + runMapping(new MapVoidAction("removeNotify") { + @Override + public void map() { + getSource().removeNotify(); + } + }); + } + + /** + * Maps + * {@code Component.removePropertyChangeListener(PropertyChangeListener)} + * through queue + */ + public void removePropertyChangeListener(final PropertyChangeListener propertyChangeListener) { + runMapping(new MapVoidAction("removePropertyChangeListener") { + @Override + public void map() { + getSource().removePropertyChangeListener(propertyChangeListener); + } + }); + } + + /** + * Maps + * {@code Component.removePropertyChangeListener(String, PropertyChangeListener)} + * through queue + */ + public void removePropertyChangeListener(final String string, final PropertyChangeListener propertyChangeListener) { + runMapping(new MapVoidAction("removePropertyChangeListener") { + @Override + public void map() { + getSource().removePropertyChangeListener(string, propertyChangeListener); + } + }); + } + + /** + * Maps {@code Component.repaint()} through queue + */ + public void repaint() { + runMapping(new MapVoidAction("repaint") { + @Override + public void map() { + getSource().repaint(); + } + }); + } + + /** + * Maps {@code 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") { + @Override + public void map() { + getSource().repaint(i, i1, i2, i3); + } + }); + } + + /** + * Maps {@code Component.repaint(long)} through queue + */ + public void repaint(final long l) { + runMapping(new MapVoidAction("repaint") { + @Override + public void map() { + getSource().repaint(l); + } + }); + } + + /** + * Maps {@code 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") { + @Override + public void map() { + getSource().repaint(l, i, i1, i2, i3); + } + }); + } + + /** + * Maps {@code Component.requestFocus()} through queue + */ + public void requestFocus() { + runMapping(new MapVoidAction("requestFocus") { + @Override + public void map() { + getSource().requestFocus(); + } + }); + } + + /** + * Maps {@code Component.setBackground(Color)} through queue + */ + public void setBackground(final Color color) { + runMapping(new MapVoidAction("setBackground") { + @Override + public void map() { + getSource().setBackground(color); + } + }); + } + + /** + * Maps {@code 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") { + @Override + public void map() { + getSource().setBounds(i, i1, i2, i3); + } + }); + } + + /** + * Maps {@code Component.setBounds(Rectangle)} through queue + */ + public void setBounds(final Rectangle rectangle) { + runMapping(new MapVoidAction("setBounds") { + @Override + public void map() { + getSource().setBounds(rectangle); + } + }); + } + + /** + * Maps {@code Component.setComponentOrientation(ComponentOrientation)} + * through queue + */ + public void setComponentOrientation(final ComponentOrientation componentOrientation) { + runMapping(new MapVoidAction("setComponentOrientation") { + @Override + public void map() { + getSource().setComponentOrientation(componentOrientation); + } + }); + } + + /** + * Maps {@code Component.setCursor(Cursor)} through queue + */ + public void setCursor(final Cursor cursor) { + runMapping(new MapVoidAction("setCursor") { + @Override + public void map() { + getSource().setCursor(cursor); + } + }); + } + + /** + * Maps {@code Component.setDropTarget(DropTarget)} through queue + */ + public void setDropTarget(final DropTarget dropTarget) { + runMapping(new MapVoidAction("setDropTarget") { + @Override + public void map() { + getSource().setDropTarget(dropTarget); + } + }); + } + + /** + * Maps {@code Component.setEnabled(boolean)} through queue + */ + public void setEnabled(final boolean b) { + runMapping(new MapVoidAction("setEnabled") { + @Override + public void map() { + getSource().setEnabled(b); + } + }); + } + + /** + * Maps {@code Component.setFont(Font)} through queue + */ + public void setFont(final Font font) { + runMapping(new MapVoidAction("setFont") { + @Override + public void map() { + getSource().setFont(font); + } + }); + } + + /** + * Maps {@code Component.setForeground(Color)} through queue + */ + public void setForeground(final Color color) { + runMapping(new MapVoidAction("setForeground") { + @Override + public void map() { + getSource().setForeground(color); + } + }); + } + + /** + * Maps {@code Component.setLocale(Locale)} through queue + */ + public void setLocale(final Locale locale) { + runMapping(new MapVoidAction("setLocale") { + @Override + public void map() { + getSource().setLocale(locale); + } + }); + } + + /** + * Maps {@code Component.setLocation(int, int)} through queue + */ + public void setLocation(final int i, final int i1) { + runMapping(new MapVoidAction("setLocation") { + @Override + public void map() { + getSource().setLocation(i, i1); + } + }); + } + + /** + * Maps {@code Component.setLocation(Point)} through queue + */ + public void setLocation(final Point point) { + runMapping(new MapVoidAction("setLocation") { + @Override + public void map() { + getSource().setLocation(point); + } + }); + } + + /** + * Maps {@code Component.setName(String)} through queue + */ + public void setName(final String string) { + runMapping(new MapVoidAction("setName") { + @Override + public void map() { + getSource().setName(string); + } + }); + } + + /** + * Maps {@code Component.setSize(int, int)} through queue + */ + public void setSize(final int i, final int i1) { + runMapping(new MapVoidAction("setSize") { + @Override + public void map() { + getSource().setSize(i, i1); + } + }); + } + + /** + * Maps {@code Component.setSize(Dimension)} through queue + */ + public void setSize(final Dimension dimension) { + runMapping(new MapVoidAction("setSize") { + @Override + public void map() { + getSource().setSize(dimension); + } + }); + } + + /** + * Maps {@code Component.setVisible(boolean)} through queue + */ + public void setVisible(final boolean b) { + runMapping(new MapVoidAction("setVisible") { + @Override + public void map() { + getSource().setVisible(b); + } + }); + } + + /** + * Maps {@code Component.transferFocus()} through queue + */ + public void transferFocus() { + runMapping(new MapVoidAction("transferFocus") { + @Override + public void map() { + getSource().transferFocus(); + } + }); + } + + /** + * Maps {@code Component.update(Graphics)} through queue + */ + public void update(final Graphics graphics) { + runMapping(new MapVoidAction("update") { + @Override + public void map() { + getSource().update(graphics); + } + }); + } + + /** + * Maps {@code Component.validate()} through queue + */ + public void validate() { + runMapping(new MapVoidAction("validate") { + @Override + public void map() { + 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; + } + + @Override + public boolean checkComponent(Component comp) { + if (comp.isShowing()) { + return subFinder.checkComponent(comp); + } + return false; + } + + @Override + public String getDescription() { + return subFinder.getDescription(); + } + + @Override + public String toString() { + return "VisibleComponentFinder{" + "subFinder=" + subFinder + '}'; + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/ContainerOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/ContainerOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,636 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 (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); + } + + @Override + public void setTimeouts(Timeouts timeouts) { + super.setTimeouts(timeouts); + this.timeouts = timeouts; + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + 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() { + @Override + public Component actionProduced(Void obj) { + return searcher.findComponent(chooser, index); + } + + @Override + public String getDescription() { + return ("Wait for \"" + chooser.getDescription() + + "\" subcomponent to be displayed"); + } + + @Override + public String toString() { + return "ContainerOperator.waitSubComponent.Waitable{description = " + getDescription() + '}'; + } + }); + waiter.setTimeoutsToCloneOf(getTimeouts(), "ComponentOperator.WaitComponentTimeout"); + waiter.setOutput(getOutput()); + try { + return 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 {@code Container.add(Component)} through queue + */ + public Component add(final Component component) { + return (runMapping(new MapAction("add") { + @Override + public Component map() { + return ((Container) getSource()).add(component); + } + })); + } + + /** + * Maps {@code Container.add(Component, int)} through queue + */ + public Component add(final Component component, final int i) { + return (runMapping(new MapAction("add") { + @Override + public Component map() { + return ((Container) getSource()).add(component, i); + } + })); + } + + /** + * Maps {@code Container.add(Component, Object)} through queue + */ + public void add(final Component component, final Object object) { + runMapping(new MapVoidAction("add") { + @Override + public void map() { + ((Container) getSource()).add(component, object); + } + }); + } + + /** + * Maps {@code Container.add(Component, Object, int)} through queue + */ + public void add(final Component component, final Object object, final int i) { + runMapping(new MapVoidAction("add") { + @Override + public void map() { + ((Container) getSource()).add(component, object, i); + } + }); + } + + /** + * Maps {@code Container.add(String, Component)} through queue + */ + public Component add(final String string, final Component component) { + return (runMapping(new MapAction("add") { + @Override + public Component map() { + return ((Container) getSource()).add(string, component); + } + })); + } + + /** + * Maps {@code Container.addContainerListener(ContainerListener)} + * through queue + */ + public void addContainerListener(final ContainerListener containerListener) { + runMapping(new MapVoidAction("addContainerListener") { + @Override + public void map() { + ((Container) getSource()).addContainerListener(containerListener); + } + }); + } + + /** + * Maps {@code Container.findComponentAt(int, int)} through queue + */ + public Component findComponentAt(final int i, final int i1) { + return (runMapping(new MapAction("findComponentAt") { + @Override + public Component map() { + return ((Container) getSource()).findComponentAt(i, i1); + } + })); + } + + /** + * Maps {@code Container.findComponentAt(Point)} through queue + */ + public Component findComponentAt(final Point point) { + return (runMapping(new MapAction("findComponentAt") { + @Override + public Component map() { + return ((Container) getSource()).findComponentAt(point); + } + })); + } + + /** + * Maps {@code Container.getComponent(int)} through queue + */ + public Component getComponent(final int i) { + return (runMapping(new MapAction("getComponent") { + @Override + public Component map() { + return ((Container) getSource()).getComponent(i); + } + })); + } + + /** + * Maps {@code Container.getComponentCount()} through queue + */ + public int getComponentCount() { + return (runMapping(new MapIntegerAction("getComponentCount") { + @Override + public int map() { + return ((Container) getSource()).getComponentCount(); + } + })); + } + + /** + * Maps {@code Container.getComponents()} through queue + */ + public Component[] getComponents() { + return ((Component[]) runMapping(new MapAction("getComponents") { + @Override + public Object map() { + return ((Container) getSource()).getComponents(); + } + })); + } + + /** + * Maps {@code Container.getInsets()} through queue + */ + public Insets getInsets() { + return (runMapping(new MapAction("getInsets") { + @Override + public Insets map() { + return ((Container) getSource()).getInsets(); + } + })); + } + + /** + * Maps {@code Container.getLayout()} through queue + */ + public LayoutManager getLayout() { + return (runMapping(new MapAction("getLayout") { + @Override + public LayoutManager map() { + return ((Container) getSource()).getLayout(); + } + })); + } + + /** + * Maps {@code Container.isAncestorOf(Component)} through queue + */ + public boolean isAncestorOf(final Component component) { + return (runMapping(new MapBooleanAction("isAncestorOf") { + @Override + public boolean map() { + return ((Container) getSource()).isAncestorOf(component); + } + })); + } + + /** + * Maps {@code Container.paintComponents(Graphics)} through queue + */ + public void paintComponents(final Graphics graphics) { + runMapping(new MapVoidAction("paintComponents") { + @Override + public void map() { + ((Container) getSource()).paintComponents(graphics); + } + }); + } + + /** + * Maps {@code Container.printComponents(Graphics)} through queue + */ + public void printComponents(final Graphics graphics) { + runMapping(new MapVoidAction("printComponents") { + @Override + public void map() { + ((Container) getSource()).printComponents(graphics); + } + }); + } + + /** + * Maps {@code Container.remove(int)} through queue + */ + public void remove(final int i) { + runMapping(new MapVoidAction("remove") { + @Override + public void map() { + ((Container) getSource()).remove(i); + } + }); + } + + /** + * Maps {@code Container.remove(Component)} through queue + */ + public void remove(final Component component) { + runMapping(new MapVoidAction("remove") { + @Override + public void map() { + ((Container) getSource()).remove(component); + } + }); + } + + /** + * Maps {@code Container.removeAll()} through queue + */ + public void removeAll() { + runMapping(new MapVoidAction("removeAll") { + @Override + public void map() { + ((Container) getSource()).removeAll(); + } + }); + } + + /** + * Maps {@code Container.removeContainerListener(ContainerListener)} + * through queue + */ + public void removeContainerListener(final ContainerListener containerListener) { + runMapping(new MapVoidAction("removeContainerListener") { + @Override + public void map() { + ((Container) getSource()).removeContainerListener(containerListener); + } + }); + } + + /** + * Maps {@code Container.setLayout(LayoutManager)} through queue + */ + public void setLayout(final LayoutManager layoutManager) { + runMapping(new MapVoidAction("setLayout") { + @Override + 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/DialogOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/DialogOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,511 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 + * {@code index+1}'th {@code java.awt.Dialog} that shows, is owned + * by the window managed by the {@code WindowOperator} + * {@code 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 {@code 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 + * {@code java.awt.Dialog} that shows, is owned by the window managed + * by the {@code WindowOperator} {@code 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(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(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. + */ + @Override + 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 {@code Dialog.getTitle()} through queue + */ + public String getTitle() { + return (runMapping(new MapAction("getTitle") { + @Override + public String map() { + return ((Dialog) getSource()).getTitle(); + } + })); + } + + /** + * Maps {@code Dialog.isModal()} through queue + */ + public boolean isModal() { + return (runMapping(new MapBooleanAction("isModal") { + @Override + public boolean map() { + return ((Dialog) getSource()).isModal(); + } + })); + } + + /** + * Maps {@code Dialog.isResizable()} through queue + */ + public boolean isResizable() { + return (runMapping(new MapBooleanAction("isResizable") { + @Override + public boolean map() { + return ((Dialog) getSource()).isResizable(); + } + })); + } + + /** + * Maps {@code Dialog.setModal(boolean)} through queue + */ + public void setModal(final boolean b) { + runMapping(new MapVoidAction("setModal") { + @Override + public void map() { + ((Dialog) getSource()).setModal(b); + } + }); + } + + /** + * Maps {@code Dialog.setResizable(boolean)} through queue + */ + public void setResizable(final boolean b) { + runMapping(new MapVoidAction("setResizable") { + @Override + public void map() { + ((Dialog) getSource()).setResizable(b); + } + }); + } + + /** + * Maps {@code Dialog.setTitle(String)} through queue + */ + public void setTitle(final String string) { + runMapping(new MapVoidAction("setTitle") { + @Override + 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 waiter.waitDialog(new DialogFinder(chooser), index); + } catch (InterruptedException e) { + output.printStackTrace(e); + return null; + } + } + + /** + * A method to be used from subclasses. Uses {@code 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 (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()); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof Dialog) { + if (comp.isShowing() && ((Dialog) comp).getTitle() != null) { + return comparator.equals(((Dialog) comp).getTitle(), title); + } + } + return false; + } + + @Override + public String getDescription() { + return "Dialog with title \"" + title + "\""; + } + + @Override + public String toString() { + return "DialogByTitleFinder{" + "title=" + title + ", comparator=" + comparator + '}'; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/FrameOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/FrameOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,558 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(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); + } + + @Override + public void setOutput(TestOut out) { + super.setOutput(out); + output = out; + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + 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() { + @Override + public boolean checkComponent(Component comp) { + return ((Frame) comp).getState() == state; + } + + @Override + public String getDescription() { + return Integer.toString(state) + " state"; + } + + @Override + public String toString() { + return "FrameOperator.waitState.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + /** + * Returns information about component. + */ + @Override + 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 {@code Frame.getIconImage()} through queue + */ + public Image getIconImage() { + return (runMapping(new MapAction("getIconImage") { + @Override + public Image map() { + return ((Frame) getSource()).getIconImage(); + } + })); + } + + /** + * Maps {@code Frame.getMenuBar()} through queue + */ + public MenuBar getMenuBar() { + return (runMapping(new MapAction("getMenuBar") { + @Override + public MenuBar map() { + return ((Frame) getSource()).getMenuBar(); + } + })); + } + + /** + * Maps {@code Frame.getState()} through queue + */ + public int getState() { + return (runMapping(new MapIntegerAction("getState") { + @Override + public int map() { + return ((Frame) getSource()).getState(); + } + })); + } + + /** + * Maps {@code Frame.getTitle()} through queue + */ + public String getTitle() { + return (runMapping(new MapAction("getTitle") { + @Override + public String map() { + return ((Frame) getSource()).getTitle(); + } + })); + } + + /** + * Maps {@code Frame.isResizable()} through queue + */ + public boolean isResizable() { + return (runMapping(new MapBooleanAction("isResizable") { + @Override + public boolean map() { + return ((Frame) getSource()).isResizable(); + } + })); + } + + /** + * Maps {@code Frame.setIconImage(Image)} through queue + */ + public void setIconImage(final Image image) { + runMapping(new MapVoidAction("setIconImage") { + @Override + public void map() { + ((Frame) getSource()).setIconImage(image); + } + }); + } + + /** + * Maps {@code Frame.setMenuBar(MenuBar)} through queue + */ + public void setMenuBar(final MenuBar menuBar) { + runMapping(new MapVoidAction("setMenuBar") { + @Override + public void map() { + ((Frame) getSource()).setMenuBar(menuBar); + } + }); + } + + /** + * Maps {@code Frame.setResizable(boolean)} through queue + */ + public void setResizable(final boolean b) { + runMapping(new MapVoidAction("setResizable") { + @Override + public void map() { + ((Frame) getSource()).setResizable(b); + } + }); + } + + /** + * Maps {@code Frame.setState(int)} through queue + */ + public void setState(final int i) { + runMapping(new MapVoidAction("setState") { + @Override + public void map() { + ((Frame) getSource()).setState(i); + } + }); + } + + /** + * Maps {@code Frame.setTitle(String)} through queue + */ + public void setTitle(final String string) { + runMapping(new MapVoidAction("setTitle") { + @Override + 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 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()); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof Frame) { + if (comp.isShowing() && ((Frame) comp).getTitle() != null) { + return comparator.equals(((Frame) comp).getTitle(), title); + } + } + return false; + } + + @Override + public String getDescription() { + return "Frame with title \"" + title + "\""; + } + + @Override + public String toString() { + return "FrameByTitleFinder{" + "title=" + title + ", comparator=" + comparator + '}'; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JButtonOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JButtonOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,339 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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. + */ + @Override + 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 {@code JButton.isDefaultButton()} through queue + */ + public boolean isDefaultButton() { + return (runMapping(new MapBooleanAction("isDefaultButton") { + @Override + public boolean map() { + return ((JButton) getSource()).isDefaultButton(); + } + })); + } + + /** + * Maps {@code JButton.isDefaultCapable()} through queue + */ + public boolean isDefaultCapable() { + return (runMapping(new MapBooleanAction("isDefaultCapable") { + @Override + public boolean map() { + return ((JButton) getSource()).isDefaultCapable(); + } + })); + } + + /** + * Maps {@code JButton.setDefaultCapable(boolean)} through queue + */ + public void setDefaultCapable(final boolean b) { + runMapping(new MapVoidAction("setDefaultCapable") { + @Override + 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JCheckBoxMenuItemOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JCheckBoxMenuItemOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,236 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 {@code JCheckBoxMenuItem.getState()} through queue + */ + public boolean getState() { + return (runMapping(new MapBooleanAction("getState") { + @Override + public boolean map() { + return ((JCheckBoxMenuItem) getSource()).getState(); + } + })); + } + + /** + * Maps {@code JCheckBoxMenuItem.setState(boolean)} through queue + */ + public void setState(final boolean b) { + runMapping(new MapVoidAction("setState") { + @Override + 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()); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof JCheckBoxMenuItem) { + if (((JCheckBoxMenuItem) comp).getText() != null) { + return (comparator.equals(((JCheckBoxMenuItem) comp).getText(), + label)); + } + } + return false; + } + + @Override + public String getDescription() { + return "JCheckBoxMenuItem with text \"" + label + "\""; + } + + @Override + public String toString() { + return "JCheckBoxMenuItemByLabelFinder{" + "label=" + label + ", comparator=" + comparator + '}'; + } + } + + /** + * 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JCheckBoxOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JCheckBoxOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,273 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JColorChooserOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JColorChooserOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,548 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + 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. + */ + @Override + 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 + * {@code JColorChooser.addChooserPanel(AbstractColorChooserPanel)} + * through queue + */ + public void addChooserPanel(final AbstractColorChooserPanel abstractColorChooserPanel) { + runMapping(new MapVoidAction("addChooserPanel") { + @Override + public void map() { + ((JColorChooser) getSource()).addChooserPanel(abstractColorChooserPanel); + } + }); + } + + /** + * Maps {@code JColorChooser.getChooserPanels()} through queue + */ + public AbstractColorChooserPanel[] getChooserPanels() { + return ((AbstractColorChooserPanel[]) runMapping(new MapAction("getChooserPanels") { + @Override + public Object map() { + return ((JColorChooser) getSource()).getChooserPanels(); + } + })); + } + + /** + * Maps {@code JColorChooser.getColor()} through queue + */ + public Color getColor() { + return (runMapping(new MapAction("getColor") { + @Override + public Color map() { + return ((JColorChooser) getSource()).getColor(); + } + })); + } + + /** + * Maps {@code JColorChooser.getPreviewPanel()} through queue + */ + public JComponent getPreviewPanel() { + return (runMapping(new MapAction("getPreviewPanel") { + @Override + public JComponent map() { + return ((JColorChooser) getSource()).getPreviewPanel(); + } + })); + } + + /** + * Maps {@code JColorChooser.getSelectionModel()} through queue + */ + public ColorSelectionModel getSelectionModel() { + return (runMapping(new MapAction("getSelectionModel") { + @Override + public ColorSelectionModel map() { + return ((JColorChooser) getSource()).getSelectionModel(); + } + })); + } + + /** + * Maps {@code JColorChooser.getUI()} through queue + */ + public ColorChooserUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public ColorChooserUI map() { + return ((JColorChooser) getSource()).getUI(); + } + })); + } + + /** + * Maps + * {@code JColorChooser.removeChooserPanel(AbstractColorChooserPanel)} + * through queue + */ + public AbstractColorChooserPanel removeChooserPanel(final AbstractColorChooserPanel abstractColorChooserPanel) { + return (runMapping(new MapAction("removeChooserPanel") { + @Override + public AbstractColorChooserPanel map() { + return ((JColorChooser) getSource()).removeChooserPanel(abstractColorChooserPanel); + } + })); + } + + /** + * Maps + * {@code JColorChooser.setChooserPanels(AbstractColorChooserPanel[])} + * through queue + */ + public void setChooserPanels(final AbstractColorChooserPanel[] abstractColorChooserPanel) { + runMapping(new MapVoidAction("setChooserPanels") { + @Override + public void map() { + ((JColorChooser) getSource()).setChooserPanels(abstractColorChooserPanel); + } + }); + } + + /** + * Maps {@code JColorChooser.setColor(int)} through queue + */ + public void setColor(final int i) { + runMapping(new MapVoidAction("setColor") { + @Override + public void map() { + ((JColorChooser) getSource()).setColor(i); + } + }); + } + + /** + * Maps {@code JColorChooser.setColor(int, int, int)} through queue + */ + public void setColor(final int i, final int i1, final int i2) { + runMapping(new MapVoidAction("setColor") { + @Override + public void map() { + ((JColorChooser) getSource()).setColor(i, i1, i2); + } + }); + } + + /** + * Maps {@code JColorChooser.setColor(Color)} through queue + */ + public void setColor(final Color color) { + runMapping(new MapVoidAction("setColor") { + @Override + public void map() { + ((JColorChooser) getSource()).setColor(color); + } + }); + } + + /** + * Maps {@code JColorChooser.setPreviewPanel(JComponent)} through queue + */ + public void setPreviewPanel(final JComponent jComponent) { + runMapping(new MapVoidAction("setPreviewPanel") { + @Override + public void map() { + ((JColorChooser) getSource()).setPreviewPanel(jComponent); + } + }); + } + + /** + * Maps {@code JColorChooser.setSelectionModel(ColorSelectionModel)} + * through queue + */ + public void setSelectionModel(final ColorSelectionModel colorSelectionModel) { + runMapping(new MapVoidAction("setSelectionModel") { + @Override + public void map() { + ((JColorChooser) getSource()).setSelectionModel(colorSelectionModel); + } + }); + } + + /** + * Maps {@code JColorChooser.setUI(ColorChooserUI)} through queue + */ + public void setUI(final ColorChooserUI colorChooserUI) { + runMapping(new MapVoidAction("setUI") { + @Override + 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); + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JComboBoxOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JComboBoxOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1452 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void setTimeouts(Timeouts timeouts) { + super.setTimeouts(timeouts); + this.timeouts = timeouts; + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut output) { + super.setOutput(output); + this.output = output; + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + 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() { + @Override + public boolean checkComponent(Component comp) { + return comp instanceof JButton; + } + + @Override + public String getDescription() { + return "Button for combobox popup menu opening"; + } + + @Override + public String toString() { + return "JComboBoxOperator.findJButton.ComponentChooser{description = " + getDescription() + '}'; + } + })); + } + + /** + * Searches JTextField inside component. + * + * @return JTextField if JComboBox is editable, null otherwise. + */ + public JTextField findJTextField() { + return ((JTextField) waitSubComponent(new ComponentChooser() { + @Override + public boolean checkComponent(Component comp) { + return comp instanceof JTextField; + } + + @Override + public String getDescription() { + return "ComboBox's text field"; + } + + @Override + public String toString() { + return "JComboBoxOperator.findJTextField.ComponentChooser{description = " + getDescription() + '}'; + } + })); + } + + /** + * Creates an operator for button returned by {@code 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 {@code 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 milliseconds, null otherwise. + * @throws TimeoutExpiredException + */ + public JList waitList() { + ListWater 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() { + @Override + public boolean checkComponent(Component comp) { + return findItemIndex(item, comparator) > -1; + } + + @Override + public String getDescription() { + return "Item \"" + item + "\" available in combo box."; + } + + @Override + public String toString() { + return "JComboBoxOperator.waitItem.ComponentChooser{description = " + getDescription() + '}'; + } + }); + 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() { + @Override + public boolean checkComponent(Component comp) { + // given itemIndex is within size of combo box + return getModel().getSize() > itemIndex; + } + + @Override + public String getDescription() { + return "Item \"" + itemIndex + "\" available in combo box."; + } + + @Override + public String toString() { + return "JComboBoxOperator.waitItem.ComponentChooser{description = " + getDescription() + '}'; + } + }); + 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) + */ + @Deprecated + 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() { + @Override + public boolean checkComponent(Component comp) { + return getSelectedIndex() == index; + } + + @Override + public String getDescription() { + return "Has " + Integer.toString(index) + "'th item selected"; + } + + @Override + public String toString() { + return "JComboBoxOperator.waitItemSelected.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + /** + * 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. + */ + @Override + public Hashtable getDump() { + Hashtable result = super.getDump(); + JComboBox jComboBox = (JComboBox) getSource(); + Object selectedItem = jComboBox.getSelectedItem(); + if (selectedItem != null) { + result.put(TEXT_DPROP, selectedItem.toString()); + } + int itemCount = jComboBox.getItemCount(); + String[] items = new String[itemCount]; + for (int i = 0; i < itemCount; i++) { + if (jComboBox.getItemAt(i) != null) { + items[i] = jComboBox.getItemAt(i).toString(); + } + } + addToDump(result, ITEM_PREFIX_DPROP, items); + return result; + } + + //////////////////////////////////////////////////////// + //Mapping // + /** + * Maps {@code JComboBox.actionPerformed(ActionEvent)} through queue + */ + public void actionPerformed(final ActionEvent actionEvent) { + runMapping(new MapVoidAction("actionPerformed") { + @Override + public void map() { + ((JComboBox) getSource()).actionPerformed(actionEvent); + } + }); + } + + /** + * Maps {@code JComboBox.addActionListener(ActionListener)} through queue + */ + public void addActionListener(final ActionListener actionListener) { + runMapping(new MapVoidAction("addActionListener") { + @Override + public void map() { + ((JComboBox) getSource()).addActionListener(actionListener); + } + }); + } + + /** + * Maps {@code JComboBox.addItem(Object)} through queue + */ + @SuppressWarnings(value = "unchecked") + public void addItem(final Object object) { + runMapping(new MapVoidAction("addItem") { + @Override + public void map() { + ((JComboBox) getSource()).addItem(object); + } + }); + } + + /** + * Maps {@code JComboBox.addItemListener(ItemListener)} through queue + */ + public void addItemListener(final ItemListener itemListener) { + runMapping(new MapVoidAction("addItemListener") { + @Override + public void map() { + ((JComboBox) getSource()).addItemListener(itemListener); + } + }); + } + + /** + * Maps {@code JComboBox.configureEditor(ComboBoxEditor, Object)} + * through queue + */ + public void configureEditor(final ComboBoxEditor comboBoxEditor, final Object object) { + runMapping(new MapVoidAction("configureEditor") { + @Override + public void map() { + ((JComboBox) getSource()).configureEditor(comboBoxEditor, object); + } + }); + } + + /** + * Maps {@code JComboBox.contentsChanged(ListDataEvent)} through queue + */ + public void contentsChanged(final ListDataEvent listDataEvent) { + runMapping(new MapVoidAction("contentsChanged") { + @Override + public void map() { + ((JComboBox) getSource()).contentsChanged(listDataEvent); + } + }); + } + + /** + * Maps {@code JComboBox.getActionCommand()} through queue + */ + public String getActionCommand() { + return (runMapping(new MapAction("getActionCommand") { + @Override + public String map() { + return ((JComboBox) getSource()).getActionCommand(); + } + })); + } + + /** + * Maps {@code JComboBox.getEditor()} through queue + */ + public ComboBoxEditor getEditor() { + return (runMapping(new MapAction("getEditor") { + @Override + public ComboBoxEditor map() { + return ((JComboBox) getSource()).getEditor(); + } + })); + } + + /** + * Maps {@code JComboBox.getItemAt(int)} through queue + */ + public Object getItemAt(final int i) { + return (runMapping(new MapAction("getItemAt") { + @Override + public Object map() { + return ((JComboBox) getSource()).getItemAt(i); + } + })); + } + + /** + * Maps {@code JComboBox.getItemCount()} through queue + */ + public int getItemCount() { + return (runMapping(new MapIntegerAction("getItemCount") { + @Override + public int map() { + return ((JComboBox) getSource()).getItemCount(); + } + })); + } + + /** + * Maps {@code JComboBox.getKeySelectionManager()} through queue + */ + public KeySelectionManager getKeySelectionManager() { + return (runMapping(new MapAction("getKeySelectionManager") { + @Override + public KeySelectionManager map() { + return ((JComboBox) getSource()).getKeySelectionManager(); + } + })); + } + + /** + * Maps {@code JComboBox.getMaximumRowCount()} through queue + */ + public int getMaximumRowCount() { + return (runMapping(new MapIntegerAction("getMaximumRowCount") { + @Override + public int map() { + return ((JComboBox) getSource()).getMaximumRowCount(); + } + })); + } + + /** + * Maps {@code JComboBox.getModel()} through queue + */ + public ComboBoxModel getModel() { + return (runMapping(new MapAction>("getModel") { + @Override + public ComboBoxModel map() { + return ((JComboBox) getSource()).getModel(); + } + })); + } + + /** + * Maps {@code JComboBox.getRenderer()} through queue + */ + public ListCellRenderer getRenderer() { + return (runMapping(new MapAction>("getRenderer") { + @Override + public ListCellRenderer map() { + return ((JComboBox) getSource()).getRenderer(); + } + })); + } + + /** + * Maps {@code JComboBox.getSelectedIndex()} through queue + */ + public int getSelectedIndex() { + return (runMapping(new MapIntegerAction("getSelectedIndex") { + @Override + public int map() { + return ((JComboBox) getSource()).getSelectedIndex(); + } + })); + } + + /** + * Maps {@code JComboBox.getSelectedItem()} through queue + */ + public Object getSelectedItem() { + return (runMapping(new MapAction("getSelectedItem") { + @Override + public Object map() { + return ((JComboBox) getSource()).getSelectedItem(); + } + })); + } + + /** + * Maps {@code JComboBox.getSelectedObjects()} through queue + */ + public Object[] getSelectedObjects() { + return ((Object[]) runMapping(new MapAction("getSelectedObjects") { + @Override + public Object map() { + return ((JComboBox) getSource()).getSelectedObjects(); + } + })); + } + + /** + * Maps {@code JComboBox.getUI()} through queue + */ + public ComboBoxUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public ComboBoxUI map() { + return ((JComboBox) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JComboBox.hidePopup()} through queue + */ + public void hidePopup() { + runMapping(new MapVoidAction("hidePopup") { + @Override + public void map() { + ((JComboBox) getSource()).hidePopup(); + } + }); + } + + /** + * Maps {@code JComboBox.insertItemAt(Object, int)} through queue + */ + @SuppressWarnings(value = "unchecked") + public void insertItemAt(final Object object, final int i) { + runMapping(new MapVoidAction("insertItemAt") { + @Override + public void map() { + ((JComboBox) getSource()).insertItemAt(object, i); + } + }); + } + + /** + * Maps {@code JComboBox.intervalAdded(ListDataEvent)} through queue + */ + public void intervalAdded(final ListDataEvent listDataEvent) { + runMapping(new MapVoidAction("intervalAdded") { + @Override + public void map() { + ((JComboBox) getSource()).intervalAdded(listDataEvent); + } + }); + } + + /** + * Maps {@code JComboBox.intervalRemoved(ListDataEvent)} through queue + */ + public void intervalRemoved(final ListDataEvent listDataEvent) { + runMapping(new MapVoidAction("intervalRemoved") { + @Override + public void map() { + ((JComboBox) getSource()).intervalRemoved(listDataEvent); + } + }); + } + + /** + * Maps {@code JComboBox.isEditable()} through queue + */ + public boolean isEditable() { + return (runMapping(new MapBooleanAction("isEditable") { + @Override + public boolean map() { + return ((JComboBox) getSource()).isEditable(); + } + })); + } + + /** + * Maps {@code JComboBox.isLightWeightPopupEnabled()} through queue + */ + public boolean isLightWeightPopupEnabled() { + return (runMapping(new MapBooleanAction("isLightWeightPopupEnabled") { + @Override + public boolean map() { + return ((JComboBox) getSource()).isLightWeightPopupEnabled(); + } + })); + } + + /** + * Maps {@code JComboBox.isPopupVisible()} through queue + */ + public boolean isPopupVisible() { + return (runMapping(new MapBooleanAction("isPopupVisible") { + @Override + public boolean map() { + return ((JComboBox) getSource()).isPopupVisible(); + } + })); + } + + /** + * Maps {@code JComboBox.processKeyEvent(KeyEvent)} through queue + */ + public void processKeyEvent(final KeyEvent keyEvent) { + runMapping(new MapVoidAction("processKeyEvent") { + @Override + public void map() { + ((JComboBox) getSource()).processKeyEvent(keyEvent); + } + }); + } + + /** + * Maps {@code JComboBox.removeActionListener(ActionListener)} through queue + */ + public void removeActionListener(final ActionListener actionListener) { + runMapping(new MapVoidAction("removeActionListener") { + @Override + public void map() { + ((JComboBox) getSource()).removeActionListener(actionListener); + } + }); + } + + /** + * Maps {@code JComboBox.removeAllItems()} through queue + */ + public void removeAllItems() { + runMapping(new MapVoidAction("removeAllItems") { + @Override + public void map() { + ((JComboBox) getSource()).removeAllItems(); + } + }); + } + + /** + * Maps {@code JComboBox.removeItem(Object)} through queue + */ + public void removeItem(final Object object) { + runMapping(new MapVoidAction("removeItem") { + @Override + public void map() { + ((JComboBox) getSource()).removeItem(object); + } + }); + } + + /** + * Maps {@code JComboBox.removeItemAt(int)} through queue + */ + public void removeItemAt(final int i) { + runMapping(new MapVoidAction("removeItemAt") { + @Override + public void map() { + ((JComboBox) getSource()).removeItemAt(i); + } + }); + } + + /** + * Maps {@code JComboBox.removeItemListener(ItemListener)} through queue + */ + public void removeItemListener(final ItemListener itemListener) { + runMapping(new MapVoidAction("removeItemListener") { + @Override + public void map() { + ((JComboBox) getSource()).removeItemListener(itemListener); + } + }); + } + + /** + * Maps {@code JComboBox.selectWithKeyChar(char)} through queue + */ + public boolean selectWithKeyChar(final char c) { + return (runMapping(new MapBooleanAction("selectWithKeyChar") { + @Override + public boolean map() { + return ((JComboBox) getSource()).selectWithKeyChar(c); + } + })); + } + + /** + * Maps {@code JComboBox.setActionCommand(String)} through queue + */ + public void setActionCommand(final String string) { + runMapping(new MapVoidAction("setActionCommand") { + @Override + public void map() { + ((JComboBox) getSource()).setActionCommand(string); + } + }); + } + + /** + * Maps {@code JComboBox.setEditable(boolean)} through queue + */ + public void setEditable(final boolean b) { + runMapping(new MapVoidAction("setEditable") { + @Override + public void map() { + ((JComboBox) getSource()).setEditable(b); + } + }); + } + + /** + * Maps {@code JComboBox.setEditor(ComboBoxEditor)} through queue + */ + public void setEditor(final ComboBoxEditor comboBoxEditor) { + runMapping(new MapVoidAction("setEditor") { + @Override + public void map() { + ((JComboBox) getSource()).setEditor(comboBoxEditor); + } + }); + } + + /** + * Maps {@code JComboBox.setKeySelectionManager(KeySelectionManager)} + * through queue + */ + public void setKeySelectionManager(final KeySelectionManager keySelectionManager) { + runMapping(new MapVoidAction("setKeySelectionManager") { + @Override + public void map() { + ((JComboBox) getSource()).setKeySelectionManager(keySelectionManager); + } + }); + } + + /** + * Maps {@code JComboBox.setLightWeightPopupEnabled(boolean)} through queue + */ + public void setLightWeightPopupEnabled(final boolean b) { + runMapping(new MapVoidAction("setLightWeightPopupEnabled") { + @Override + public void map() { + ((JComboBox) getSource()).setLightWeightPopupEnabled(b); + } + }); + } + + /** + * Maps {@code JComboBox.setMaximumRowCount(int)} through queue + */ + public void setMaximumRowCount(final int i) { + runMapping(new MapVoidAction("setMaximumRowCount") { + @Override + public void map() { + ((JComboBox) getSource()).setMaximumRowCount(i); + } + }); + } + + /** + * Maps {@code JComboBox.setModel(ComboBoxModel)} through queue + */ + @SuppressWarnings(value = "unchecked") + public void setModel(final ComboBoxModel comboBoxModel) { + runMapping(new MapVoidAction("setModel") { + @Override + public void map() { + ((JComboBox) getSource()).setModel(comboBoxModel); + } + }); + } + + /** + * Maps {@code JComboBox.setPopupVisible(boolean)} through queue + */ + public void setPopupVisible(final boolean b) { + runMapping(new MapVoidAction("setPopupVisible") { + @Override + public void map() { + ((JComboBox) getSource()).setPopupVisible(b); + } + }); + } + + /** + * Maps {@code JComboBox.setRenderer(ListCellRenderer)} through queue + */ + @SuppressWarnings(value = "unchecked") + public void setRenderer(final ListCellRenderer listCellRenderer) { + runMapping(new MapVoidAction("setRenderer") { + @Override + public void map() { + ((JComboBox) getSource()).setRenderer(listCellRenderer); + } + }); + } + + /** + * Maps {@code JComboBox.setSelectedIndex(int)} through queue + */ + public void setSelectedIndex(final int i) { + runMapping(new MapVoidAction("setSelectedIndex") { + @Override + public void map() { + ((JComboBox) getSource()).setSelectedIndex(i); + } + }); + } + + /** + * Maps {@code JComboBox.setSelectedItem(Object)} through queue + */ + public void setSelectedItem(final Object object) { + runMapping(new MapVoidAction("setSelectedItem") { + @Override + public void map() { + ((JComboBox) getSource()).setSelectedItem(object); + } + }); + } + + /** + * Maps {@code JComboBox.setUI(ComboBoxUI)} through queue + */ + public void setUI(final ComboBoxUI comboBoxUI) { + runMapping(new MapVoidAction("setUI") { + @Override + public void map() { + ((JComboBox) getSource()).setUI(comboBoxUI); + } + }); + } + + /** + * Maps {@code JComboBox.showPopup()} through queue + */ + public void showPopup() { + runMapping(new MapVoidAction("showPopup") { + @Override + 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()); + } + + @Override + 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; + } + + @Override + public String getDescription() { + return ("JComboBox with text \"" + label + "\" in " + + itemIndex + "'th item"); + } + + @Override + public String toString() { + return "JComboBoxByItemFinder{" + "label=" + label + ", itemIndex=" + itemIndex + ", comparator=" + comparator + '}'; + } + } + + /** + * 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 static class PopupWindowChooser implements ComponentChooser { + + ComponentChooser pChooser; + + public PopupWindowChooser(ComponentChooser pChooser) { + this.pChooser = pChooser; + } + + @Override + public boolean checkComponent(Component comp) { + ComponentSearcher cs = new ComponentSearcher((Container) comp); + cs.setOutput(TestOut.getNullOutput()); + return cs.findComponent(pChooser) != null; + } + + @Override + public String getDescription() { + return "Popup window"; + } + + @Override + public String toString() { + return "PopupWindowChooser{" + "pChooser=" + pChooser + '}'; + } + } + + private class ListWater extends Waiter { + + ComponentChooser cChooser; + ComponentChooser pChooser; + + public ListWater() { + super(); + cChooser = new ComponentChooser() { + @Override + 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; + } + + @Override + public String getDescription() { + return "Popup menu"; + } + + @Override + public String toString() { + return "JComboBoxOperator.ListWater.ComponentChooser{description = " + getDescription() + '}'; + } + }; + pChooser = new PopupWindowChooser(cChooser); + } + + @Override + public Component actionProduced(Void 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; + } + } + + @Override + public String getDescription() { + return "Wait popup expanded"; + } + + @Override + public String toString() { + return "ListWater{" + "cChooser=" + cChooser + ", pChooser=" + pChooser + '}'; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JComponentOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JComponentOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1286 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void setTimeouts(Timeouts timeouts) { + super.setTimeouts(timeouts); + this.timeouts = timeouts; + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + public int getCenterXForClick() { + Rectangle rect = getVisibleRect(); + return ((int) rect.getX() + + (int) rect.getWidth() / 2); + } + + @Override + 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() { + @Override + public boolean checkComponent(Component comp) { + return (comp instanceof Window + || comp instanceof JInternalFrame); + } + + @Override + 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; + } + + @Override + 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 = 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 {@code JComponent.addAncestorListener(AncestorListener)} + * through queue + */ + public void addAncestorListener(final AncestorListener ancestorListener) { + runMapping(new MapVoidAction("addAncestorListener") { + @Override + public void map() { + ((JComponent) getSource()).addAncestorListener(ancestorListener); + } + }); + } + + /** + * Maps + * {@code JComponent.addVetoableChangeListener(VetoableChangeListener)} + * through queue + */ + public void addVetoableChangeListener(final VetoableChangeListener vetoableChangeListener) { + runMapping(new MapVoidAction("addVetoableChangeListener") { + @Override + public void map() { + ((JComponent) getSource()).addVetoableChangeListener(vetoableChangeListener); + } + }); + } + + /** + * Maps {@code JComponent.computeVisibleRect(Rectangle)} through queue + */ + public void computeVisibleRect(final Rectangle rectangle) { + runMapping(new MapVoidAction("computeVisibleRect") { + @Override + public void map() { + ((JComponent) getSource()).computeVisibleRect(rectangle); + } + }); + } + + /** + * Maps {@code JComponent.createToolTip()} through queue + */ + public JToolTip createToolTip() { + return (runMapping(new MapAction("createToolTip") { + @Override + public JToolTip map() { + return ((JComponent) getSource()).createToolTip(); + } + })); + } + + /** + * Maps {@code JComponent.firePropertyChange(String, byte, byte)} + * through queue + */ + public void firePropertyChange(final String string, final byte b, final byte b1) { + runMapping(new MapVoidAction("firePropertyChange") { + @Override + public void map() { + getSource().firePropertyChange(string, b, b1); + } + }); + } + + /** + * Maps {@code JComponent.firePropertyChange(String, char, char)} + * through queue + */ + public void firePropertyChange(final String string, final char c, final char c1) { + runMapping(new MapVoidAction("firePropertyChange") { + @Override + public void map() { + getSource().firePropertyChange(string, c, c1); + } + }); + } + + /** + * Maps {@code JComponent.firePropertyChange(String, double, double)} + * through queue + */ + public void firePropertyChange(final String string, final double d, final double d1) { + runMapping(new MapVoidAction("firePropertyChange") { + @Override + public void map() { + getSource().firePropertyChange(string, d, d1); + } + }); + } + + /** + * Maps {@code JComponent.firePropertyChange(String, float, float)} + * through queue + */ + public void firePropertyChange(final String string, final float f, final float f1) { + runMapping(new MapVoidAction("firePropertyChange") { + @Override + public void map() { + getSource().firePropertyChange(string, f, f1); + } + }); + } + + /** + * Maps {@code JComponent.firePropertyChange(String, int, int)} through queue + */ + public void firePropertyChange(final String string, final int i, final int i1) { + runMapping(new MapVoidAction("firePropertyChange") { + @Override + public void map() { + ((JComponent) getSource()).firePropertyChange(string, i, i1); + } + }); + } + + /** + * Maps {@code JComponent.firePropertyChange(String, long, long)} + * through queue + */ + public void firePropertyChange(final String string, final long l, final long l1) { + runMapping(new MapVoidAction("firePropertyChange") { + @Override + public void map() { + getSource().firePropertyChange(string, l, l1); + } + }); + } + + /** + * Maps {@code JComponent.firePropertyChange(String, short, short)} + * through queue + */ + public void firePropertyChange(final String string, final short s, final short s1) { + runMapping(new MapVoidAction("firePropertyChange") { + @Override + public void map() { + getSource().firePropertyChange(string, s, s1); + } + }); + } + + /** + * Maps {@code JComponent.firePropertyChange(String, boolean, boolean)} + * through queue + */ + public void firePropertyChange(final String string, final boolean b, final boolean b1) { + runMapping(new MapVoidAction("firePropertyChange") { + @Override + public void map() { + ((JComponent) getSource()).firePropertyChange(string, b, b1); + } + }); + } + + /** + * Maps {@code JComponent.getAccessibleContext()} through queue + */ + public AccessibleContext getAccessibleContext() { + return (runMapping(new MapAction("getAccessibleContext") { + @Override + public AccessibleContext map() { + return getSource().getAccessibleContext(); + } + })); + } + + /** + * Maps {@code JComponent.getActionForKeyStroke(KeyStroke)} through queue + */ + public ActionListener getActionForKeyStroke(final KeyStroke keyStroke) { + return (runMapping(new MapAction("getActionForKeyStroke") { + @Override + public ActionListener map() { + return ((JComponent) getSource()).getActionForKeyStroke(keyStroke); + } + })); + } + + /** + * Maps {@code JComponent.getAutoscrolls()} through queue + */ + public boolean getAutoscrolls() { + return (runMapping(new MapBooleanAction("getAutoscrolls") { + @Override + public boolean map() { + return ((JComponent) getSource()).getAutoscrolls(); + } + })); + } + + /** + * Maps {@code JComponent.getBorder()} through queue + */ + public Border getBorder() { + return (runMapping(new MapAction("getBorder") { + @Override + public Border map() { + return ((JComponent) getSource()).getBorder(); + } + })); + } + + /** + * Maps {@code JComponent.getClientProperty(Object)} through queue + */ + public Object getClientProperty(final Object object) { + return (runMapping(new MapAction("getClientProperty") { + @Override + public Object map() { + return ((JComponent) getSource()).getClientProperty(object); + } + })); + } + + /** + * Maps {@code JComponent.getConditionForKeyStroke(KeyStroke)} through queue + */ + public int getConditionForKeyStroke(final KeyStroke keyStroke) { + return (runMapping(new MapIntegerAction("getConditionForKeyStroke") { + @Override + public int map() { + return ((JComponent) getSource()).getConditionForKeyStroke(keyStroke); + } + })); + } + + /** + * Maps {@code JComponent.getDebugGraphicsOptions()} through queue + */ + public int getDebugGraphicsOptions() { + return (runMapping(new MapIntegerAction("getDebugGraphicsOptions") { + @Override + public int map() { + return ((JComponent) getSource()).getDebugGraphicsOptions(); + } + })); + } + + /** + * Maps {@code JComponent.getInsets(Insets)} through queue + */ + public Insets getInsets(final Insets insets) { + return (runMapping(new MapAction("getInsets") { + @Override + public Insets map() { + return ((JComponent) getSource()).getInsets(insets); + } + })); + } + + /** + * Maps {@code JComponent.getNextFocusableComponent()} through queue + */ + @Deprecated + public Component getNextFocusableComponent() { + return (runMapping(new MapAction("getNextFocusableComponent") { + @Override + public Component map() { + return ((JComponent) getSource()).getNextFocusableComponent(); + } + })); + } + + /** + * Maps {@code JComponent.getRegisteredKeyStrokes()} through queue + */ + public KeyStroke[] getRegisteredKeyStrokes() { + return ((KeyStroke[]) runMapping(new MapAction("getRegisteredKeyStrokes") { + @Override + public Object map() { + return ((JComponent) getSource()).getRegisteredKeyStrokes(); + } + })); + } + + /** + * Maps {@code JComponent.getRootPane()} through queue + */ + public JRootPane getRootPane() { + return (runMapping(new MapAction("getRootPane") { + @Override + public JRootPane map() { + return ((JComponent) getSource()).getRootPane(); + } + })); + } + + /** + * Maps {@code JComponent.getToolTipLocation(MouseEvent)} through queue + */ + public Point getToolTipLocation(final MouseEvent mouseEvent) { + return (runMapping(new MapAction("getToolTipLocation") { + @Override + public Point map() { + return ((JComponent) getSource()).getToolTipLocation(mouseEvent); + } + })); + } + + /** + * Maps {@code JComponent.getToolTipText()} through queue + */ + public String getToolTipText() { + return (runMapping(new MapAction("getToolTipText") { + @Override + public String map() { + return ((JComponent) getSource()).getToolTipText(); + } + })); + } + + /** + * Maps {@code JComponent.getToolTipText(MouseEvent)} through queue + */ + public String getToolTipText(final MouseEvent mouseEvent) { + return (runMapping(new MapAction("getToolTipText") { + @Override + public String map() { + return ((JComponent) getSource()).getToolTipText(mouseEvent); + } + })); + } + + /** + * Maps {@code JComponent.getTopLevelAncestor()} through queue + */ + public Container getTopLevelAncestor() { + return (runMapping(new MapAction("getTopLevelAncestor") { + @Override + public Container map() { + return ((JComponent) getSource()).getTopLevelAncestor(); + } + })); + } + + /** + * Maps {@code JComponent.getUIClassID()} through queue + */ + public String getUIClassID() { + return (runMapping(new MapAction("getUIClassID") { + @Override + public String map() { + return ((JComponent) getSource()).getUIClassID(); + } + })); + } + + /** + * Maps {@code JComponent.getVisibleRect()} through queue + */ + public Rectangle getVisibleRect() { + return (runMapping(new MapAction("getVisibleRect") { + @Override + public Rectangle map() { + return ((JComponent) getSource()).getVisibleRect(); + } + })); + } + + /** + * Maps {@code JComponent.grabFocus()} through queue + */ + public void grabFocus() { + runMapping(new MapVoidAction("grabFocus") { + @Override + public void map() { + ((JComponent) getSource()).grabFocus(); + } + }); + } + + /** + * Maps {@code JComponent.isFocusCycleRoot()} through queue + */ + public boolean isFocusCycleRoot() { + return (runMapping(new MapBooleanAction("isFocusCycleRoot") { + @Override + public boolean map() { + return ((JComponent) getSource()).isFocusCycleRoot(); + } + })); + } + + /** + * Maps {@code JComponent.isManagingFocus()} through queue + */ + @Deprecated + public boolean isManagingFocus() { + return (runMapping(new MapBooleanAction("isManagingFocus") { + @Override + public boolean map() { + return ((JComponent) getSource()).isManagingFocus(); + } + })); + } + + /** + * Maps {@code JComponent.isOptimizedDrawingEnabled()} through queue + */ + public boolean isOptimizedDrawingEnabled() { + return (runMapping(new MapBooleanAction("isOptimizedDrawingEnabled") { + @Override + public boolean map() { + return ((JComponent) getSource()).isOptimizedDrawingEnabled(); + } + })); + } + + /** + * Maps {@code JComponent.isPaintingTile()} through queue + */ + public boolean isPaintingTile() { + return (runMapping(new MapBooleanAction("isPaintingTile") { + @Override + public boolean map() { + return ((JComponent) getSource()).isPaintingTile(); + } + })); + } + + /** + * Maps {@code JComponent.isRequestFocusEnabled()} through queue + */ + public boolean isRequestFocusEnabled() { + return (runMapping(new MapBooleanAction("isRequestFocusEnabled") { + @Override + public boolean map() { + return ((JComponent) getSource()).isRequestFocusEnabled(); + } + })); + } + + /** + * Maps {@code JComponent.isValidateRoot()} through queue + */ + public boolean isValidateRoot() { + return (runMapping(new MapBooleanAction("isValidateRoot") { + @Override + public boolean map() { + return ((JComponent) getSource()).isValidateRoot(); + } + })); + } + + /** + * Maps {@code 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") { + @Override + public void map() { + ((JComponent) getSource()).paintImmediately(i, i1, i2, i3); + } + }); + } + + /** + * Maps {@code JComponent.paintImmediately(Rectangle)} through queue + */ + public void paintImmediately(final Rectangle rectangle) { + runMapping(new MapVoidAction("paintImmediately") { + @Override + public void map() { + ((JComponent) getSource()).paintImmediately(rectangle); + } + }); + } + + /** + * Maps {@code JComponent.putClientProperty(Object, Object)} through queue + */ + public void putClientProperty(final Object object, final Object object1) { + runMapping(new MapVoidAction("putClientProperty") { + @Override + public void map() { + ((JComponent) getSource()).putClientProperty(object, object1); + } + }); + } + + /** + * Maps + * {@code 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") { + @Override + public void map() { + ((JComponent) getSource()).registerKeyboardAction(actionListener, string, keyStroke, i); + } + }); + } + + /** + * Maps + * {@code JComponent.registerKeyboardAction(ActionListener, KeyStroke, int)} + * through queue + */ + public void registerKeyboardAction(final ActionListener actionListener, final KeyStroke keyStroke, final int i) { + runMapping(new MapVoidAction("registerKeyboardAction") { + @Override + public void map() { + ((JComponent) getSource()).registerKeyboardAction(actionListener, keyStroke, i); + } + }); + } + + /** + * Maps {@code JComponent.removeAncestorListener(AncestorListener)} + * through queue + */ + public void removeAncestorListener(final AncestorListener ancestorListener) { + runMapping(new MapVoidAction("removeAncestorListener") { + @Override + public void map() { + ((JComponent) getSource()).removeAncestorListener(ancestorListener); + } + }); + } + + /** + * Maps + * {@code JComponent.removeVetoableChangeListener(VetoableChangeListener)} + * through queue + */ + public void removeVetoableChangeListener(final VetoableChangeListener vetoableChangeListener) { + runMapping(new MapVoidAction("removeVetoableChangeListener") { + @Override + public void map() { + ((JComponent) getSource()).removeVetoableChangeListener(vetoableChangeListener); + } + }); + } + + /** + * Maps {@code JComponent.repaint(Rectangle)} through queue + */ + public void repaint(final Rectangle rectangle) { + runMapping(new MapVoidAction("repaint") { + @Override + public void map() { + ((JComponent) getSource()).repaint(rectangle); + } + }); + } + + /** + * Maps {@code JComponent.requestDefaultFocus()} through queue + */ + @Deprecated + public boolean requestDefaultFocus() { + return (runMapping(new MapBooleanAction("requestDefaultFocus") { + @Override + public boolean map() { + return ((JComponent) getSource()).requestDefaultFocus(); + } + })); + } + + /** + * Maps {@code JComponent.resetKeyboardActions()} through queue + */ + public void resetKeyboardActions() { + runMapping(new MapVoidAction("resetKeyboardActions") { + @Override + public void map() { + ((JComponent) getSource()).resetKeyboardActions(); + } + }); + } + + /** + * Maps {@code JComponent.revalidate()} through queue + */ + public void revalidate() { + runMapping(new MapVoidAction("revalidate") { + @Override + public void map() { + getSource().revalidate(); + } + }); + } + + /** + * Maps {@code JComponent.scrollRectToVisible(Rectangle)} through queue + */ + public void scrollRectToVisible(final Rectangle rectangle) { + runMapping(new MapVoidAction("scrollRectToVisible") { + @Override + public void map() { + ((JComponent) getSource()).scrollRectToVisible(rectangle); + } + }); + } + + /** + * Maps {@code JComponent.setAlignmentX(float)} through queue + */ + public void setAlignmentX(final float f) { + runMapping(new MapVoidAction("setAlignmentX") { + @Override + public void map() { + ((JComponent) getSource()).setAlignmentX(f); + } + }); + } + + /** + * Maps {@code JComponent.setAlignmentY(float)} through queue + */ + public void setAlignmentY(final float f) { + runMapping(new MapVoidAction("setAlignmentY") { + @Override + public void map() { + ((JComponent) getSource()).setAlignmentY(f); + } + }); + } + + /** + * Maps {@code JComponent.setAutoscrolls(boolean)} through queue + */ + public void setAutoscrolls(final boolean b) { + runMapping(new MapVoidAction("setAutoscrolls") { + @Override + public void map() { + ((JComponent) getSource()).setAutoscrolls(b); + } + }); + } + + /** + * Maps {@code JComponent.setBorder(Border)} through queue + */ + public void setBorder(final Border border) { + runMapping(new MapVoidAction("setBorder") { + @Override + public void map() { + ((JComponent) getSource()).setBorder(border); + } + }); + } + + /** + * Maps {@code JComponent.setDebugGraphicsOptions(int)} through queue + */ + public void setDebugGraphicsOptions(final int i) { + runMapping(new MapVoidAction("setDebugGraphicsOptions") { + @Override + public void map() { + ((JComponent) getSource()).setDebugGraphicsOptions(i); + } + }); + } + + /** + * Maps {@code JComponent.setDoubleBuffered(boolean)} through queue + */ + public void setDoubleBuffered(final boolean b) { + runMapping(new MapVoidAction("setDoubleBuffered") { + @Override + public void map() { + ((JComponent) getSource()).setDoubleBuffered(b); + } + }); + } + + /** + * Maps {@code JComponent.setMaximumSize(Dimension)} through queue + */ + public void setMaximumSize(final Dimension dimension) { + runMapping(new MapVoidAction("setMaximumSize") { + @Override + public void map() { + getSource().setMaximumSize(dimension); + } + }); + } + + /** + * Maps {@code JComponent.setMinimumSize(Dimension)} through queue + */ + public void setMinimumSize(final Dimension dimension) { + runMapping(new MapVoidAction("setMinimumSize") { + @Override + public void map() { + getSource().setMinimumSize(dimension); + } + }); + } + + /** + * Maps {@code JComponent.setNextFocusableComponent(Component)} through queue + */ + @Deprecated + public void setNextFocusableComponent(final Component component) { + runMapping(new MapVoidAction("setNextFocusableComponent") { + @Override + public void map() { + ((JComponent) getSource()).setNextFocusableComponent(component); + } + }); + } + + /** + * Maps {@code JComponent.setOpaque(boolean)} through queue + */ + public void setOpaque(final boolean b) { + runMapping(new MapVoidAction("setOpaque") { + @Override + public void map() { + ((JComponent) getSource()).setOpaque(b); + } + }); + } + + /** + * Maps {@code JComponent.setPreferredSize(Dimension)} through queue + */ + public void setPreferredSize(final Dimension dimension) { + runMapping(new MapVoidAction("setPreferredSize") { + @Override + public void map() { + getSource().setPreferredSize(dimension); + } + }); + } + + /** + * Maps {@code JComponent.setRequestFocusEnabled(boolean)} through queue + */ + public void setRequestFocusEnabled(final boolean b) { + runMapping(new MapVoidAction("setRequestFocusEnabled") { + @Override + public void map() { + ((JComponent) getSource()).setRequestFocusEnabled(b); + } + }); + } + + /** + * Maps {@code JComponent.setToolTipText(String)} through queue + */ + public void setToolTipText(final String string) { + runMapping(new MapVoidAction("setToolTipText") { + @Override + public void map() { + ((JComponent) getSource()).setToolTipText(string); + } + }); + } + + /** + * Maps {@code JComponent.unregisterKeyboardAction(KeyStroke)} through queue + */ + public void unregisterKeyboardAction(final KeyStroke keyStroke) { + runMapping(new MapVoidAction("unregisterKeyboardAction") { + @Override + public void map() { + ((JComponent) getSource()).unregisterKeyboardAction(keyStroke); + } + }); + } + + /** + * Maps {@code JComponent.updateUI()} through queue + */ + public void updateUI() { + runMapping(new MapVoidAction("updateUI") { + @Override + 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; + + /** + * 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()); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof JComponent) { + if (((JComponent) comp).getToolTipText() != null) { + return (comparator.equals(((JComponent) comp).getToolTipText(), + label)); + } + } + return false; + } + + @Override + public String getDescription() { + return "JComponent with tool tip \"" + label + "\""; + } + + @Override + public String toString() { + return "JComponentByTipFinder{" + "label=" + label + ", comparator=" + comparator + '}'; + } + } + + /** + * 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); + } + } + + static class JToolTipWindowFinder implements ComponentChooser { + + ComponentChooser ppFinder; + + public JToolTipWindowFinder() { + ppFinder = new ComponentChooser() { + @Override + public boolean checkComponent(Component comp) { + return (comp.isShowing() + && comp.isVisible() + && comp instanceof JToolTip); + } + + @Override + public String getDescription() { + return "A tool tip"; + } + + @Override + public String toString() { + return "JComponentOperator.JToolTipWindowFinder.ComponentChooser{description = " + getDescription() + '}'; + } + }; + } + + @Override + 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; + } + + @Override + public String getDescription() { + return "A tool tip window"; + } + + @Override + public String toString() { + return "JToolTipWindowFinder{" + "ppFinder=" + ppFinder + '}'; + } + } + + class JToolTipFinder extends Finder { + + public JToolTipFinder(ComponentChooser sf) { + super(JToolTip.class, sf); + } + + public JToolTipFinder() { + super(JToolTip.class); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JDialogOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JDialogOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,748 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 {@code 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(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(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() { + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof Dialog) { + Dialog dialog = (Dialog) comp; + if (dialog.isModal()) { + Window[] ow = dialog.getOwnedWindows(); + for (Window anOw : ow) { + if (anOw.isVisible()) { + return false; + } + } + return true; + } + } + return false; + } + + @Override + public String getDescription() { + return "Upper modal dialog"; + } + + @Override + public String toString() { + return "JDialogOperator.getTopModalDialog.ComponentChooser{description = " + getDescription() + '}'; + } + })); + } + + //////////////////////////////////////////////////////// + //Mapping // + /** + * Maps {@code JDialog.getAccessibleContext()} through queue + */ + public AccessibleContext getAccessibleContext() { + return (runMapping(new MapAction("getAccessibleContext") { + @Override + public AccessibleContext map() { + return getSource().getAccessibleContext(); + } + })); + } + + /** + * Maps {@code JDialog.getContentPane()} through queue + */ + public Container getContentPane() { + return (runMapping(new MapAction("getContentPane") { + @Override + public Container map() { + return ((JDialog) getSource()).getContentPane(); + } + })); + } + + /** + * Maps {@code JDialog.getDefaultCloseOperation()} through queue + */ + public int getDefaultCloseOperation() { + return (runMapping(new MapIntegerAction("getDefaultCloseOperation") { + @Override + public int map() { + return ((JDialog) getSource()).getDefaultCloseOperation(); + } + })); + } + + /** + * Maps {@code JDialog.getGlassPane()} through queue + */ + public Component getGlassPane() { + return (runMapping(new MapAction("getGlassPane") { + @Override + public Component map() { + return ((JDialog) getSource()).getGlassPane(); + } + })); + } + + /** + * Maps {@code JDialog.getJMenuBar()} through queue + */ + public JMenuBar getJMenuBar() { + return (runMapping(new MapAction("getJMenuBar") { + @Override + public JMenuBar map() { + return ((JDialog) getSource()).getJMenuBar(); + } + })); + } + + /** + * Maps {@code JDialog.getLayeredPane()} through queue + */ + public JLayeredPane getLayeredPane() { + return (runMapping(new MapAction("getLayeredPane") { + @Override + public JLayeredPane map() { + return ((JDialog) getSource()).getLayeredPane(); + } + })); + } + + /** + * Maps {@code JDialog.getRootPane()} through queue + */ + public JRootPane getRootPane() { + return (runMapping(new MapAction("getRootPane") { + @Override + public JRootPane map() { + return ((JDialog) getSource()).getRootPane(); + } + })); + } + + /** + * Maps {@code JDialog.setContentPane(Container)} through queue + */ + public void setContentPane(final Container container) { + runMapping(new MapVoidAction("setContentPane") { + @Override + public void map() { + ((JDialog) getSource()).setContentPane(container); + } + }); + } + + /** + * Maps {@code JDialog.setDefaultCloseOperation(int)} through queue + */ + public void setDefaultCloseOperation(final int i) { + runMapping(new MapVoidAction("setDefaultCloseOperation") { + @Override + public void map() { + ((JDialog) getSource()).setDefaultCloseOperation(i); + } + }); + } + + /** + * Maps {@code JDialog.setGlassPane(Component)} through queue + */ + public void setGlassPane(final Component component) { + runMapping(new MapVoidAction("setGlassPane") { + @Override + public void map() { + ((JDialog) getSource()).setGlassPane(component); + } + }); + } + + /** + * Maps {@code JDialog.setJMenuBar(JMenuBar)} through queue + */ + public void setJMenuBar(final JMenuBar jMenuBar) { + runMapping(new MapVoidAction("setJMenuBar") { + @Override + public void map() { + ((JDialog) getSource()).setJMenuBar(jMenuBar); + } + }); + } + + /** + * Maps {@code JDialog.setLayeredPane(JLayeredPane)} through queue + */ + public void setLayeredPane(final JLayeredPane jLayeredPane) { + runMapping(new MapVoidAction("setLayeredPane") { + @Override + public void map() { + ((JDialog) getSource()).setLayeredPane(jLayeredPane); + } + }); + } + + /** + * Maps {@code JDialog.setLocationRelativeTo(Component)} through queue + */ + public void setLocationRelativeTo(final Component component) { + runMapping(new MapVoidAction("setLocationRelativeTo") { + @Override + 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 {@code 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JEditorPaneOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JEditorPaneOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,481 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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. + */ + @Deprecated + public void usePageNavigationKeys(boolean yesOrNo) { + } + + /** + * Returns information about component. + */ + @Override + public Hashtable getDump() { + Hashtable result = super.getDump(); + result.put(CONTENT_TYPE_DPROP, ((JEditorPane) getSource()).getContentType()); + return result; + } + + //////////////////////////////////////////////////////// + //Mapping // + /** + * Maps {@code JEditorPane.addHyperlinkListener(HyperlinkListener)} + * through queue + */ + public void addHyperlinkListener(final HyperlinkListener hyperlinkListener) { + runMapping(new MapVoidAction("addHyperlinkListener") { + @Override + public void map() { + ((JEditorPane) getSource()).addHyperlinkListener(hyperlinkListener); + } + }); + } + + /** + * Maps {@code JEditorPane.fireHyperlinkUpdate(HyperlinkEvent)} through queue + */ + public void fireHyperlinkUpdate(final HyperlinkEvent hyperlinkEvent) { + runMapping(new MapVoidAction("fireHyperlinkUpdate") { + @Override + public void map() { + ((JEditorPane) getSource()).fireHyperlinkUpdate(hyperlinkEvent); + } + }); + } + + /** + * Maps {@code JEditorPane.getContentType()} through queue + */ + public String getContentType() { + return (runMapping(new MapAction("getContentType") { + @Override + public String map() { + return ((JEditorPane) getSource()).getContentType(); + } + })); + } + + /** + * Maps {@code JEditorPane.getEditorKit()} through queue + */ + public EditorKit getEditorKit() { + return (runMapping(new MapAction("getEditorKit") { + @Override + public EditorKit map() { + return ((JEditorPane) getSource()).getEditorKit(); + } + })); + } + + /** + * Maps {@code JEditorPane.getEditorKitForContentType(String)} through queue + */ + public EditorKit getEditorKitForContentType(final String string) { + return (runMapping(new MapAction("getEditorKitForContentType") { + @Override + public EditorKit map() { + return ((JEditorPane) getSource()).getEditorKitForContentType(string); + } + })); + } + + /** + * Maps {@code JEditorPane.getPage()} through queue + */ + public URL getPage() { + return (runMapping(new MapAction("getPage") { + @Override + public URL map() { + return ((JEditorPane) getSource()).getPage(); + } + })); + } + + /** + * Maps {@code JEditorPane.read(InputStream, Object)} through queue + */ + public void read(final InputStream inputStream, final Object object) { + runMapping(new MapVoidAction("read") { + @Override + public void map() throws IOException { + ((JEditorPane) getSource()).read(inputStream, object); + } + }); + } + + /** + * Maps {@code JEditorPane.removeHyperlinkListener(HyperlinkListener)} + * through queue + */ + public void removeHyperlinkListener(final HyperlinkListener hyperlinkListener) { + runMapping(new MapVoidAction("removeHyperlinkListener") { + @Override + public void map() { + ((JEditorPane) getSource()).removeHyperlinkListener(hyperlinkListener); + } + }); + } + + /** + * Maps {@code JEditorPane.setContentType(String)} through queue + */ + public void setContentType(final String string) { + runMapping(new MapVoidAction("setContentType") { + @Override + public void map() { + ((JEditorPane) getSource()).setContentType(string); + } + }); + } + + /** + * Maps {@code JEditorPane.setEditorKit(EditorKit)} through queue + */ + public void setEditorKit(final EditorKit editorKit) { + runMapping(new MapVoidAction("setEditorKit") { + @Override + public void map() { + ((JEditorPane) getSource()).setEditorKit(editorKit); + } + }); + } + + /** + * Maps + * {@code JEditorPane.setEditorKitForContentType(String, EditorKit)} + * through queue + */ + public void setEditorKitForContentType(final String string, final EditorKit editorKit) { + runMapping(new MapVoidAction("setEditorKitForContentType") { + @Override + public void map() { + ((JEditorPane) getSource()).setEditorKitForContentType(string, editorKit); + } + }); + } + + /** + * Maps {@code JEditorPane.setPage(String)} through queue + */ + public void setPage(final String string) { + runMapping(new MapVoidAction("setPage") { + @Override + public void map() throws IOException { + ((JEditorPane) getSource()).setPage(string); + } + }); + } + + /** + * Maps {@code JEditorPane.setPage(URL)} through queue + */ + public void setPage(final URL uRL) { + runMapping(new MapVoidAction("setPage") { + @Override + 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JFileChooserOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JFileChooserOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1739 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.netbeans.jemmy.operators; + +import java.awt.Component; +import java.awt.Container; +import java.awt.Rectangle; +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@oracle.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); + } + + @Override + public void setTimeouts(Timeouts timeouts) { + super.setTimeouts(timeouts); + this.timeouts = timeouts; + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + if (innerSearcher != null) { + innerSearcher.setOutput(output.createErrorOutput()); + } + } + + @Override + 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() { + @Override + 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); + } + + @Override + public String getDescription() { + return "JButton"; + } + + @Override + public String toString() { + return "JFileChooserOperator.getCancelButton.ComponentChooser{description = " + getDescription() + '}'; + } + }, 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() { + @Override + public boolean checkComponent(Component comp) { + return (comp != null + && comp instanceof JTextField); + } + + @Override + public String getDescription() { + return "JTextField"; + } + + @Override + public String toString() { + return "JFileChooserOperator.getPathField.ComponentChooser{description = " + getDescription() + '}'; + } + })); + } + + /** + * Returns file list. + * + * @return a list being used to display directory content. + */ + public JList getFileList() { + return ((JList) innerSearcher. + findComponent(new ComponentChooser() { + @Override + public boolean checkComponent(Component comp) { + return (comp != null + && comp instanceof JList); + } + + @Override + public String getDescription() { + return "JList"; + } + + @Override + public String toString() { + return "JFileChooserOperator.getFileList.ComponentChooser{description = " + getDescription() + '}'; + } + })); + } + + /** + * 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) + */ + @Deprecated + 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) + */ + @Deprecated + 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) + */ + @Deprecated + 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) + */ + @Deprecated + 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) + */ + @Deprecated + 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) + */ + @Deprecated + 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) + */ + @Deprecated + 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() { + @Override + public boolean checkComponent(Component comp) { + return getFileCount() == count; + } + + @Override + public String getDescription() { + return ("Count of files to be equal " + + Integer.toString(count)); + } + + @Override + public String toString() { + return "JFileChooserOperator.waitFileCount.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + /** + * 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() { + @Override + public boolean checkComponent(Component comp) { + return checkFileDisplayed(fileName); + } + + @Override + public String getDescription() { + return "\"" + fileName + "\"file to be displayed"; + } + + @Override + public String toString() { + return "JFileChooserOperator.waitFileDisplayed.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + //////////////////////////////////////////////////////// + //Mapping // + /** + * Maps {@code JFileChooser.accept(File)} through queue + */ + public boolean accept(final File file) { + return (runMapping(new MapBooleanAction("accept") { + @Override + public boolean map() { + return ((JFileChooser) getSource()).accept(file); + } + })); + } + + /** + * Maps {@code JFileChooser.addActionListener(ActionListener)} through queue + */ + public void addActionListener(final ActionListener actionListener) { + runMapping(new MapVoidAction("addActionListener") { + @Override + public void map() { + ((JFileChooser) getSource()).addActionListener(actionListener); + } + }); + } + + /** + * Maps {@code JFileChooser.addChoosableFileFilter(FileFilter)} through queue + */ + public void addChoosableFileFilter(final FileFilter fileFilter) { + runMapping(new MapVoidAction("addChoosableFileFilter") { + @Override + public void map() { + ((JFileChooser) getSource()).addChoosableFileFilter(fileFilter); + } + }); + } + + /** + * Maps {@code JFileChooser.approveSelection()} through queue + */ + public void approveSelection() { + runMapping(new MapVoidAction("approveSelection") { + @Override + public void map() { + ((JFileChooser) getSource()).approveSelection(); + } + }); + } + + /** + * Maps {@code JFileChooser.cancelSelection()} through queue + */ + public void cancelSelection() { + runMapping(new MapVoidAction("cancelSelection") { + @Override + public void map() { + ((JFileChooser) getSource()).cancelSelection(); + } + }); + } + + /** + * Maps {@code JFileChooser.changeToParentDirectory()} through queue + */ + public void changeToParentDirectory() { + runMapping(new MapVoidAction("changeToParentDirectory") { + @Override + public void map() { + ((JFileChooser) getSource()).changeToParentDirectory(); + } + }); + } + + /** + * Maps {@code JFileChooser.ensureFileIsVisible(File)} through queue + */ + public void ensureFileIsVisible(final File file) { + runMapping(new MapVoidAction("ensureFileIsVisible") { + @Override + public void map() { + ((JFileChooser) getSource()).ensureFileIsVisible(file); + } + }); + } + + /** + * Maps {@code JFileChooser.getAcceptAllFileFilter()} through queue + */ + public FileFilter getAcceptAllFileFilter() { + return (runMapping(new MapAction("getAcceptAllFileFilter") { + @Override + public FileFilter map() { + return ((JFileChooser) getSource()).getAcceptAllFileFilter(); + } + })); + } + + /** + * Maps {@code JFileChooser.getAccessory()} through queue + */ + public JComponent getAccessory() { + return (runMapping(new MapAction("getAccessory") { + @Override + public JComponent map() { + return ((JFileChooser) getSource()).getAccessory(); + } + })); + } + + /** + * Maps {@code JFileChooser.getApproveButtonMnemonic()} through queue + */ + public int getApproveButtonMnemonic() { + return (runMapping(new MapIntegerAction("getApproveButtonMnemonic") { + @Override + public int map() { + return ((JFileChooser) getSource()).getApproveButtonMnemonic(); + } + })); + } + + /** + * Maps {@code JFileChooser.getApproveButtonText()} through queue + */ + public String getApproveButtonText() { + return (runMapping(new MapAction("getApproveButtonText") { + @Override + public String map() { + return ((JFileChooser) getSource()).getApproveButtonText(); + } + })); + } + + /** + * Maps {@code JFileChooser.getApproveButtonToolTipText()} through queue + */ + public String getApproveButtonToolTipText() { + return (runMapping(new MapAction("getApproveButtonToolTipText") { + @Override + public String map() { + return ((JFileChooser) getSource()).getApproveButtonToolTipText(); + } + })); + } + + /** + * Maps {@code JFileChooser.getChoosableFileFilters()} through queue + */ + public FileFilter[] getChoosableFileFilters() { + return ((FileFilter[]) runMapping(new MapAction("getChoosableFileFilters") { + @Override + public Object map() { + return ((JFileChooser) getSource()).getChoosableFileFilters(); + } + })); + } + + /** + * Maps {@code JFileChooser.getCurrentDirectory()} through queue + */ + public File getCurrentDirectory() { + return (runMapping(new MapAction("getCurrentDirectory") { + @Override + public File map() { + return ((JFileChooser) getSource()).getCurrentDirectory(); + } + })); + } + + /** + * Maps {@code JFileChooser.getDescription(File)} through queue + */ + public String getDescription(final File file) { + return (runMapping(new MapAction("getDescription") { + @Override + public String map() { + return ((JFileChooser) getSource()).getDescription(file); + } + })); + } + + /** + * Maps {@code JFileChooser.getDialogTitle()} through queue + */ + public String getDialogTitle() { + return (runMapping(new MapAction("getDialogTitle") { + @Override + public String map() { + return ((JFileChooser) getSource()).getDialogTitle(); + } + })); + } + + /** + * Maps {@code JFileChooser.getDialogType()} through queue + */ + public int getDialogType() { + return (runMapping(new MapIntegerAction("getDialogType") { + @Override + public int map() { + return ((JFileChooser) getSource()).getDialogType(); + } + })); + } + + /** + * Maps {@code JFileChooser.getFileFilter()} through queue + */ + public FileFilter getFileFilter() { + return (runMapping(new MapAction("getFileFilter") { + @Override + public FileFilter map() { + return ((JFileChooser) getSource()).getFileFilter(); + } + })); + } + + /** + * Maps {@code JFileChooser.getFileSelectionMode()} through queue + */ + public int getFileSelectionMode() { + return (runMapping(new MapIntegerAction("getFileSelectionMode") { + @Override + public int map() { + return ((JFileChooser) getSource()).getFileSelectionMode(); + } + })); + } + + /** + * Maps {@code JFileChooser.getFileSystemView()} through queue + */ + public FileSystemView getFileSystemView() { + return (runMapping(new MapAction("getFileSystemView") { + @Override + public FileSystemView map() { + return ((JFileChooser) getSource()).getFileSystemView(); + } + })); + } + + /** + * Maps {@code JFileChooser.getFileView()} through queue + */ + public FileView getFileView() { + return (runMapping(new MapAction("getFileView") { + @Override + public FileView map() { + return ((JFileChooser) getSource()).getFileView(); + } + })); + } + + /** + * Maps {@code JFileChooser.getIcon(File)} through queue + */ + public Icon getIcon(final File file) { + return (runMapping(new MapAction("getIcon") { + @Override + public Icon map() { + return ((JFileChooser) getSource()).getIcon(file); + } + })); + } + + /** + * Maps {@code JFileChooser.getName(File)} through queue + */ + public String getName(final File file) { + return (runMapping(new MapAction("getName") { + @Override + public String map() { + return ((JFileChooser) getSource()).getName(file); + } + })); + } + + /** + * Maps {@code JFileChooser.getSelectedFile()} through queue + */ + public File getSelectedFile() { + return (runMapping(new MapAction("getSelectedFile") { + @Override + public File map() { + return ((JFileChooser) getSource()).getSelectedFile(); + } + })); + } + + /** + * Maps {@code JFileChooser.getSelectedFiles()} through queue + */ + public File[] getSelectedFiles() { + return ((File[]) runMapping(new MapAction("getSelectedFiles") { + @Override + public Object map() { + return ((JFileChooser) getSource()).getSelectedFiles(); + } + })); + } + + /** + * Maps {@code JFileChooser.getTypeDescription(File)} through queue + */ + public String getTypeDescription(final File file) { + return (runMapping(new MapAction("getTypeDescription") { + @Override + public String map() { + return ((JFileChooser) getSource()).getTypeDescription(file); + } + })); + } + + /** + * Maps {@code JFileChooser.getUI()} through queue + */ + public FileChooserUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public FileChooserUI map() { + return ((JFileChooser) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JFileChooser.isDirectorySelectionEnabled()} through queue + */ + public boolean isDirectorySelectionEnabled() { + return (runMapping(new MapBooleanAction("isDirectorySelectionEnabled") { + @Override + public boolean map() { + return ((JFileChooser) getSource()).isDirectorySelectionEnabled(); + } + })); + } + + /** + * Maps {@code JFileChooser.isFileHidingEnabled()} through queue + */ + public boolean isFileHidingEnabled() { + return (runMapping(new MapBooleanAction("isFileHidingEnabled") { + @Override + public boolean map() { + return ((JFileChooser) getSource()).isFileHidingEnabled(); + } + })); + } + + /** + * Maps {@code JFileChooser.isFileSelectionEnabled()} through queue + */ + public boolean isFileSelectionEnabled() { + return (runMapping(new MapBooleanAction("isFileSelectionEnabled") { + @Override + public boolean map() { + return ((JFileChooser) getSource()).isFileSelectionEnabled(); + } + })); + } + + /** + * Maps {@code JFileChooser.isMultiSelectionEnabled()} through queue + */ + public boolean isMultiSelectionEnabled() { + return (runMapping(new MapBooleanAction("isMultiSelectionEnabled") { + @Override + public boolean map() { + return ((JFileChooser) getSource()).isMultiSelectionEnabled(); + } + })); + } + + /** + * Maps {@code JFileChooser.isTraversable(File)} through queue + */ + public boolean isTraversable(final File file) { + return (runMapping(new MapBooleanAction("isTraversable") { + @Override + public boolean map() { + return ((JFileChooser) getSource()).isTraversable(file); + } + })); + } + + /** + * Maps {@code JFileChooser.removeActionListener(ActionListener)} + * through queue + */ + public void removeActionListener(final ActionListener actionListener) { + runMapping(new MapVoidAction("removeActionListener") { + @Override + public void map() { + ((JFileChooser) getSource()).removeActionListener(actionListener); + } + }); + } + + /** + * Maps {@code JFileChooser.removeChoosableFileFilter(FileFilter)} + * through queue + */ + public boolean removeChoosableFileFilter(final FileFilter fileFilter) { + return (runMapping(new MapBooleanAction("removeChoosableFileFilter") { + @Override + public boolean map() { + return ((JFileChooser) getSource()).removeChoosableFileFilter(fileFilter); + } + })); + } + + /** + * Maps {@code JFileChooser.rescanCurrentDirectory()} through queue + */ + public void rescanCurrentDirectory() { + runMapping(new MapVoidAction("rescanCurrentDirectory") { + @Override + public void map() { + ((JFileChooser) getSource()).rescanCurrentDirectory(); + } + }); + } + + /** + * Maps {@code JFileChooser.resetChoosableFileFilters()} through queue + */ + public void resetChoosableFileFilters() { + runMapping(new MapVoidAction("resetChoosableFileFilters") { + @Override + public void map() { + ((JFileChooser) getSource()).resetChoosableFileFilters(); + } + }); + } + + /** + * Maps {@code JFileChooser.setAccessory(JComponent)} through queue + */ + public void setAccessory(final JComponent jComponent) { + runMapping(new MapVoidAction("setAccessory") { + @Override + public void map() { + ((JFileChooser) getSource()).setAccessory(jComponent); + } + }); + } + + /** + * Maps {@code JFileChooser.setApproveButtonMnemonic(char)} through queue + */ + public void setApproveButtonMnemonic(final char c) { + runMapping(new MapVoidAction("setApproveButtonMnemonic") { + @Override + public void map() { + ((JFileChooser) getSource()).setApproveButtonMnemonic(c); + } + }); + } + + /** + * Maps {@code JFileChooser.setApproveButtonMnemonic(int)} through queue + */ + public void setApproveButtonMnemonic(final int i) { + runMapping(new MapVoidAction("setApproveButtonMnemonic") { + @Override + public void map() { + ((JFileChooser) getSource()).setApproveButtonMnemonic(i); + } + }); + } + + /** + * Maps {@code JFileChooser.setApproveButtonText(String)} through queue + */ + public void setApproveButtonText(final String string) { + runMapping(new MapVoidAction("setApproveButtonText") { + @Override + public void map() { + ((JFileChooser) getSource()).setApproveButtonText(string); + } + }); + } + + /** + * Maps {@code JFileChooser.setApproveButtonToolTipText(String)} + * through queue + */ + public void setApproveButtonToolTipText(final String string) { + runMapping(new MapVoidAction("setApproveButtonToolTipText") { + @Override + public void map() { + ((JFileChooser) getSource()).setApproveButtonToolTipText(string); + } + }); + } + + /** + * Maps {@code JFileChooser.setCurrentDirectory(File)} through queue + */ + public void setCurrentDirectory(final File file) { + runMapping(new MapVoidAction("setCurrentDirectory") { + @Override + public void map() { + ((JFileChooser) getSource()).setCurrentDirectory(file); + } + }); + } + + /** + * Maps {@code JFileChooser.setDialogTitle(String)} through queue + */ + public void setDialogTitle(final String string) { + runMapping(new MapVoidAction("setDialogTitle") { + @Override + public void map() { + ((JFileChooser) getSource()).setDialogTitle(string); + } + }); + } + + /** + * Maps {@code JFileChooser.setDialogType(int)} through queue + */ + public void setDialogType(final int i) { + runMapping(new MapVoidAction("setDialogType") { + @Override + public void map() { + ((JFileChooser) getSource()).setDialogType(i); + } + }); + } + + /** + * Maps {@code JFileChooser.setFileFilter(FileFilter)} through queue + */ + public void setFileFilter(final FileFilter fileFilter) { + runMapping(new MapVoidAction("setFileFilter") { + @Override + public void map() { + ((JFileChooser) getSource()).setFileFilter(fileFilter); + } + }); + } + + /** + * Maps {@code JFileChooser.setFileHidingEnabled(boolean)} through queue + */ + public void setFileHidingEnabled(final boolean b) { + runMapping(new MapVoidAction("setFileHidingEnabled") { + @Override + public void map() { + ((JFileChooser) getSource()).setFileHidingEnabled(b); + } + }); + } + + /** + * Maps {@code JFileChooser.setFileSelectionMode(int)} through queue + */ + public void setFileSelectionMode(final int i) { + runMapping(new MapVoidAction("setFileSelectionMode") { + @Override + public void map() { + ((JFileChooser) getSource()).setFileSelectionMode(i); + } + }); + } + + /** + * Maps {@code JFileChooser.setFileSystemView(FileSystemView)} through queue + */ + public void setFileSystemView(final FileSystemView fileSystemView) { + runMapping(new MapVoidAction("setFileSystemView") { + @Override + public void map() { + ((JFileChooser) getSource()).setFileSystemView(fileSystemView); + } + }); + } + + /** + * Maps {@code JFileChooser.setFileView(FileView)} through queue + */ + public void setFileView(final FileView fileView) { + runMapping(new MapVoidAction("setFileView") { + @Override + public void map() { + ((JFileChooser) getSource()).setFileView(fileView); + } + }); + } + + /** + * Maps {@code JFileChooser.setMultiSelectionEnabled(boolean)} through queue + */ + public void setMultiSelectionEnabled(final boolean b) { + runMapping(new MapVoidAction("setMultiSelectionEnabled") { + @Override + public void map() { + ((JFileChooser) getSource()).setMultiSelectionEnabled(b); + } + }); + } + + /** + * Maps {@code JFileChooser.setSelectedFile(File)} through queue + */ + public void setSelectedFile(final File file) { + runMapping(new MapVoidAction("setSelectedFile") { + @Override + public void map() { + ((JFileChooser) getSource()).setSelectedFile(file); + } + }); + } + + /** + * Maps {@code JFileChooser.setSelectedFiles(File[])} through queue + */ + public void setSelectedFiles(final File[] file) { + runMapping(new MapVoidAction("setSelectedFiles") { + @Override + public void map() { + ((JFileChooser) getSource()).setSelectedFiles(file); + } + }); + } + + /** + * Maps {@code JFileChooser.showDialog(Component, String)} through queue + */ + public int showDialog(final Component component, final String string) { + return (runMapping(new MapIntegerAction("showDialog") { + @Override + public int map() { + return ((JFileChooser) getSource()).showDialog(component, string); + } + })); + } + + /** + * Maps {@code JFileChooser.showOpenDialog(Component)} through queue + */ + public int showOpenDialog(final Component component) { + return (runMapping(new MapIntegerAction("showOpenDialog") { + @Override + public int map() { + return ((JFileChooser) getSource()).showOpenDialog(component); + } + })); + } + + /** + * Maps {@code JFileChooser.showSaveDialog(Component)} through queue + */ + public int showSaveDialog(final Component component) { + return (runMapping(new MapIntegerAction("showSaveDialog") { + @Override + public int map() { + return ((JFileChooser) getSource()).showSaveDialog(component); + } + })); + } + + //End of mapping // + //////////////////////////////////////////////////////// + private void waitPainted(int index) { + Waiter drawingWaiter = new Waiter<>(new Waitable() { + @Override + public Rectangle actionProduced(Integer param) { + JList list = getFileList(); + int last_one = list.getModel().getSize() - 1; + if (last_one == -1) { + return new Rectangle(); + } + int current = (param != null) ? param : 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; + } + } + + @Override + public String getDescription() { + return "List drawed"; + } + + @Override + public String toString() { + return "JFileChooserOperator.waitPainted.Waitable{description = " + getDescription() + '}'; + } + }); + drawingWaiter.setTimeoutsToCloneOf(getTimeouts(), "JFileChooserOperator.WaitListPaintedTimeout"); + drawingWaiter.setOutput(getOutput().createErrorOutput()); + try { + drawingWaiter.waitAction((index != -1) ? index : null); + } catch (InterruptedException e) { + output.printStackTrace(e); + } + } + + private JComboBox getCombo(int index) { + return ((JComboBox) innerSearcher. + findComponent(new ComponentChooser() { + @Override + public boolean checkComponent(Component comp) { + return (comp != null + && comp instanceof JComboBox); + } + + @Override + public String getDescription() { + return "JComboBox"; + } + + @Override + public String toString() { + return "JFileChooserOperator.getCombo.ComponentChooser{description = " + getDescription() + '}'; + } + }, index)); + } + + private JButton getNoTextButton(int index) { + return ((JButton) innerSearcher. + findComponent(new ComponentChooser() { + @Override + public boolean checkComponent(Component comp) { + return (comp != null + && comp instanceof JButton + && !(comp.getParent() instanceof JComboBox) + && (((JButton) comp).getText() == null + || ((JButton) comp).getText().length() == 0)); + } + + @Override + public String getDescription() { + return "JButton"; + } + + @Override + public String toString() { + return "JFileChooserOperator.getNoTextButton.ComponentChooser{description = " + getDescription() + '}'; + } + }, index)); + } + + private JToggleButton getToggleButton(int index) { + return ((JToggleButton) innerSearcher. + findComponent(new ComponentChooser() { + @Override + public boolean checkComponent(Component comp) { + return (comp != null + && comp instanceof JToggleButton); + } + + @Override + public String getDescription() { + return "JToggleButton"; + } + + @Override + public String toString() { + return "JFileChooserOperator.getToggleButton.ComponentChooser{description = " + getDescription() + '}'; + } + }, index)); + } + + private int findFileIndex(final String file, final StringComparator comparator) { + Waiter fileWaiter = new Waiter<>(new Waitable() { + @Override + public Integer actionProduced(Void obj) { + File[] files = getFiles(); + for (int i = 0; i < files.length; i++) { + if (comparator.equals(files[i].getName(), + file)) { + return i; + } + } + return null; + } + + @Override + public String getDescription() { + return "\"" + file + "\" file to be displayed"; + } + + @Override + public String toString() { + return "JFileChooserOperator.findFileIndex.Waitable{description = " + getDescription() + '}'; + } + }); + fileWaiter.setOutput(getOutput().createErrorOutput()); + fileWaiter.setTimeoutsToCloneOf(getTimeouts(), "JFileChooserOperator.WaitListPaintedTimeout"); + try { + return fileWaiter.waitAction(null); + } 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(); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp != null + && comp instanceof Window + && comp.isVisible()) { + ComponentSearcher searcher + = new ComponentSearcher((Container) comp); + searcher.setOutput(output); + return searcher.findComponent(subChooser) != null; + } else { + return false; + } + } + + @Override + public String getDescription() { + return "JFileChooser's window"; + } + + @Override + public String toString() { + return "JFileChooserJDialogFinder{" + "subChooser=" + subChooser + '}'; + } + } + + /** + * 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 static class ButtonFinder implements ComponentChooser { + + String text; + + public ButtonFinder(String text) { + this.text = text; + } + + @Override + public boolean checkComponent(Component comp) { + return (comp != null + && comp instanceof JButton + && ((JButton) comp).getText() != null + && ((JButton) comp).getText().equals(text)); + } + + @Override + public String getDescription() { + return "\"" + text + "\" button"; + } + + @Override + public String toString() { + return "ButtonFinder{" + "text=" + text + '}'; + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JFrameOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JFrameOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,443 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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) 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 {@code JFrame.getAccessibleContext()} through queue + */ + public AccessibleContext getAccessibleContext() { + return (runMapping(new MapAction("getAccessibleContext") { + @Override + public AccessibleContext map() { + return getSource().getAccessibleContext(); + } + })); + } + + /** + * Maps {@code JFrame.getContentPane()} through queue + */ + public Container getContentPane() { + return (runMapping(new MapAction("getContentPane") { + @Override + public Container map() { + return ((JFrame) getSource()).getContentPane(); + } + })); + } + + /** + * Maps {@code JFrame.getDefaultCloseOperation()} through queue + */ + public int getDefaultCloseOperation() { + return (runMapping(new MapIntegerAction("getDefaultCloseOperation") { + @Override + public int map() { + return ((JFrame) getSource()).getDefaultCloseOperation(); + } + })); + } + + /** + * Maps {@code JFrame.getGlassPane()} through queue + */ + public Component getGlassPane() { + return (runMapping(new MapAction("getGlassPane") { + @Override + public Component map() { + return ((JFrame) getSource()).getGlassPane(); + } + })); + } + + /** + * Maps {@code JFrame.getJMenuBar()} through queue + */ + public JMenuBar getJMenuBar() { + return (runMapping(new MapAction("getJMenuBar") { + @Override + public JMenuBar map() { + return ((JFrame) getSource()).getJMenuBar(); + } + })); + } + + /** + * Maps {@code JFrame.getLayeredPane()} through queue + */ + public JLayeredPane getLayeredPane() { + return (runMapping(new MapAction("getLayeredPane") { + @Override + public JLayeredPane map() { + return ((JFrame) getSource()).getLayeredPane(); + } + })); + } + + /** + * Maps {@code JFrame.getRootPane()} through queue + */ + public JRootPane getRootPane() { + return (runMapping(new MapAction("getRootPane") { + @Override + public JRootPane map() { + return ((JFrame) getSource()).getRootPane(); + } + })); + } + + /** + * Maps {@code JFrame.setContentPane(Container)} through queue + */ + public void setContentPane(final Container container) { + runMapping(new MapVoidAction("setContentPane") { + @Override + public void map() { + ((JFrame) getSource()).setContentPane(container); + } + }); + } + + /** + * Maps {@code JFrame.setDefaultCloseOperation(int)} through queue + */ + public void setDefaultCloseOperation(final int i) { + runMapping(new MapVoidAction("setDefaultCloseOperation") { + @Override + public void map() { + ((JFrame) getSource()).setDefaultCloseOperation(i); + } + }); + } + + /** + * Maps {@code JFrame.setGlassPane(Component)} through queue + */ + public void setGlassPane(final Component component) { + runMapping(new MapVoidAction("setGlassPane") { + @Override + public void map() { + ((JFrame) getSource()).setGlassPane(component); + } + }); + } + + /** + * Maps {@code JFrame.setJMenuBar(JMenuBar)} through queue + */ + public void setJMenuBar(final JMenuBar jMenuBar) { + runMapping(new MapVoidAction("setJMenuBar") { + @Override + public void map() { + ((JFrame) getSource()).setJMenuBar(jMenuBar); + } + }); + } + + /** + * Maps {@code JFrame.setLayeredPane(JLayeredPane)} through queue + */ + public void setLayeredPane(final JLayeredPane jLayeredPane) { + runMapping(new MapVoidAction("setLayeredPane") { + @Override + 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JInternalFrameOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JInternalFrameOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1552 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + public void setTimeouts(Timeouts times) { + timeouts = times; + super.setTimeouts(timeouts); + } + + @Override + 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.requestClose(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() { + @Override + public boolean checkComponent(Component comp) { + return ((JInternalFrame) comp).isIcon() == icon; + } + + @Override + public String getDescription() { + return "Iconified JInternalFrame"; + } + + @Override + public String toString() { + return "JInternalFrameOperator.waitIcon.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + /** + * 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() { + @Override + public boolean checkComponent(Component comp) { + return ((JInternalFrame) comp).isMaximum() == maximum; + } + + @Override + public String getDescription() { + return "Maximizied JInternalFrame"; + } + + @Override + public String toString() { + return "JInternalFrameOperator.waitMaximum.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + /** + * Returns information about component. + */ + @Override + 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 + * {@code JInternalFrame.addInternalFrameListener(InternalFrameListener)} + * through queue + */ + public void addInternalFrameListener(final InternalFrameListener internalFrameListener) { + runMapping(new MapVoidAction("addInternalFrameListener") { + @Override + public void map() { + ((JInternalFrame) getSource()).addInternalFrameListener(internalFrameListener); + } + }); + } + + /** + * Maps {@code JInternalFrame.dispose()} through queue + */ + public void dispose() { + runMapping(new MapVoidAction("dispose") { + @Override + public void map() { + ((JInternalFrame) getSource()).dispose(); + } + }); + } + + /** + * Maps {@code JInternalFrame.getContentPane()} through queue + */ + public Container getContentPane() { + return (runMapping(new MapAction("getContentPane") { + @Override + public Container map() { + return ((JInternalFrame) getSource()).getContentPane(); + } + })); + } + + /** + * Maps {@code JInternalFrame.getDefaultCloseOperation()} through queue + */ + public int getDefaultCloseOperation() { + return (runMapping(new MapIntegerAction("getDefaultCloseOperation") { + @Override + public int map() { + return ((JInternalFrame) getSource()).getDefaultCloseOperation(); + } + })); + } + + /** + * Maps {@code JInternalFrame.getDesktopIcon()} through queue + */ + public JDesktopIcon getDesktopIcon() { + return (runMapping(new MapAction("getDesktopIcon") { + @Override + public JDesktopIcon map() { + return ((JInternalFrame) getSource()).getDesktopIcon(); + } + })); + } + + /** + * Maps {@code JInternalFrame.getDesktopPane()} through queue + */ + public JDesktopPane getDesktopPane() { + return (runMapping(new MapAction("getDesktopPane") { + @Override + public JDesktopPane map() { + return ((JInternalFrame) getSource()).getDesktopPane(); + } + })); + } + + /** + * Maps {@code JInternalFrame.getFrameIcon()} through queue + */ + public Icon getFrameIcon() { + return (runMapping(new MapAction("getFrameIcon") { + @Override + public Icon map() { + return ((JInternalFrame) getSource()).getFrameIcon(); + } + })); + } + + /** + * Maps {@code JInternalFrame.getGlassPane()} through queue + */ + public Component getGlassPane() { + return (runMapping(new MapAction("getGlassPane") { + @Override + public Component map() { + return ((JInternalFrame) getSource()).getGlassPane(); + } + })); + } + + /** + * Maps {@code JInternalFrame.getJMenuBar()} through queue + */ + public JMenuBar getJMenuBar() { + return (runMapping(new MapAction("getJMenuBar") { + @Override + public JMenuBar map() { + return ((JInternalFrame) getSource()).getJMenuBar(); + } + })); + } + + /** + * Maps {@code JInternalFrame.getLayer()} through queue + */ + public int getLayer() { + return (runMapping(new MapIntegerAction("getLayer") { + @Override + public int map() { + return ((JInternalFrame) getSource()).getLayer(); + } + })); + } + + /** + * Maps {@code JInternalFrame.getLayeredPane()} through queue + */ + public JLayeredPane getLayeredPane() { + return (runMapping(new MapAction("getLayeredPane") { + @Override + public JLayeredPane map() { + return ((JInternalFrame) getSource()).getLayeredPane(); + } + })); + } + + /** + * Maps {@code JInternalFrame.getTitle()} through queue + */ + public String getTitle() { + return (runMapping(new MapAction("getTitle") { + @Override + public String map() { + return ((JInternalFrame) getSource()).getTitle(); + } + })); + } + + /** + * Maps {@code JInternalFrame.getUI()} through queue + */ + public InternalFrameUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public InternalFrameUI map() { + return ((JInternalFrame) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JInternalFrame.getWarningString()} through queue + */ + public String getWarningString() { + return (runMapping(new MapAction("getWarningString") { + @Override + public String map() { + return ((JInternalFrame) getSource()).getWarningString(); + } + })); + } + + /** + * Maps {@code JInternalFrame.isClosable()} through queue + */ + public boolean isClosable() { + return (runMapping(new MapBooleanAction("isClosable") { + @Override + public boolean map() { + return ((JInternalFrame) getSource()).isClosable(); + } + })); + } + + /** + * Maps {@code JInternalFrame.isClosed()} through queue + */ + public boolean isClosed() { + return (runMapping(new MapBooleanAction("isClosed") { + @Override + public boolean map() { + return ((JInternalFrame) getSource()).isClosed(); + } + })); + } + + /** + * Maps {@code JInternalFrame.isIcon()} through queue + */ + public boolean isIcon() { + return (runMapping(new MapBooleanAction("isIcon") { + @Override + public boolean map() { + return ((JInternalFrame) getSource()).isIcon(); + } + })); + } + + /** + * Maps {@code JInternalFrame.isIconifiable()} through queue + */ + public boolean isIconifiable() { + return (runMapping(new MapBooleanAction("isIconifiable") { + @Override + public boolean map() { + return ((JInternalFrame) getSource()).isIconifiable(); + } + })); + } + + /** + * Maps {@code JInternalFrame.isMaximizable()} through queue + */ + public boolean isMaximizable() { + return (runMapping(new MapBooleanAction("isMaximizable") { + @Override + public boolean map() { + return ((JInternalFrame) getSource()).isMaximizable(); + } + })); + } + + /** + * Maps {@code JInternalFrame.isMaximum()} through queue + */ + public boolean isMaximum() { + return (runMapping(new MapBooleanAction("isMaximum") { + @Override + public boolean map() { + return ((JInternalFrame) getSource()).isMaximum(); + } + })); + } + + /** + * Maps {@code JInternalFrame.isResizable()} through queue + */ + public boolean isResizable() { + return (runMapping(new MapBooleanAction("isResizable") { + @Override + public boolean map() { + return ((JInternalFrame) getSource()).isResizable(); + } + })); + } + + /** + * Maps {@code JInternalFrame.isSelected()} through queue + */ + public boolean isSelected() { + return (runMapping(new MapBooleanAction("isSelected") { + @Override + public boolean map() { + return ((JInternalFrame) getSource()).isSelected(); + } + })); + } + + /** + * Maps {@code JInternalFrame.moveToBack()} through queue + */ + public void moveToBack() { + runMapping(new MapVoidAction("moveToBack") { + @Override + public void map() { + ((JInternalFrame) getSource()).moveToBack(); + } + }); + } + + /** + * Maps {@code JInternalFrame.moveToFront()} through queue + */ + public void moveToFront() { + runMapping(new MapVoidAction("moveToFront") { + @Override + public void map() { + ((JInternalFrame) getSource()).moveToFront(); + } + }); + } + + /** + * Maps {@code JInternalFrame.pack()} through queue + */ + public void pack() { + runMapping(new MapVoidAction("pack") { + @Override + public void map() { + ((JInternalFrame) getSource()).pack(); + } + }); + } + + /** + * Maps + * {@code JInternalFrame.removeInternalFrameListener(InternalFrameListener)} + * through queue + */ + public void removeInternalFrameListener(final InternalFrameListener internalFrameListener) { + runMapping(new MapVoidAction("removeInternalFrameListener") { + @Override + public void map() { + ((JInternalFrame) getSource()).removeInternalFrameListener(internalFrameListener); + } + }); + } + + /** + * Maps {@code JInternalFrame.setClosable(boolean)} through queue + */ + public void setClosable(final boolean b) { + runMapping(new MapVoidAction("setClosable") { + @Override + public void map() { + ((JInternalFrame) getSource()).setClosable(b); + } + }); + } + + /** + * Maps {@code JInternalFrame.setClosed(boolean)} through queue + */ + public void setClosed(final boolean b) { + runMapping(new MapVoidAction("setClosed") { + @Override + public void map() throws PropertyVetoException { + ((JInternalFrame) getSource()).setClosed(b); + } + }); + } + + /** + * Maps {@code JInternalFrame.setContentPane(Container)} through queue + */ + public void setContentPane(final Container container) { + runMapping(new MapVoidAction("setContentPane") { + @Override + public void map() { + ((JInternalFrame) getSource()).setContentPane(container); + } + }); + } + + /** + * Maps {@code JInternalFrame.setDefaultCloseOperation(int)} through queue + */ + public void setDefaultCloseOperation(final int i) { + runMapping(new MapVoidAction("setDefaultCloseOperation") { + @Override + public void map() { + ((JInternalFrame) getSource()).setDefaultCloseOperation(i); + } + }); + } + + /** + * Maps {@code JInternalFrame.setDesktopIcon(JDesktopIcon)} through queue + */ + public void setDesktopIcon(final JDesktopIcon jDesktopIcon) { + runMapping(new MapVoidAction("setDesktopIcon") { + @Override + public void map() { + ((JInternalFrame) getSource()).setDesktopIcon(jDesktopIcon); + } + }); + } + + /** + * Maps {@code JInternalFrame.setFrameIcon(Icon)} through queue + */ + public void setFrameIcon(final Icon icon) { + runMapping(new MapVoidAction("setFrameIcon") { + @Override + public void map() { + ((JInternalFrame) getSource()).setFrameIcon(icon); + } + }); + } + + /** + * Maps {@code JInternalFrame.setGlassPane(Component)} through queue + */ + public void setGlassPane(final Component component) { + runMapping(new MapVoidAction("setGlassPane") { + @Override + public void map() { + ((JInternalFrame) getSource()).setGlassPane(component); + } + }); + } + + /** + * Maps {@code JInternalFrame.setIcon(boolean)} through queue + */ + public void setIcon(final boolean b) { + runMapping(new MapVoidAction("setIcon") { + @Override + public void map() throws PropertyVetoException { + ((JInternalFrame) getSource()).setIcon(b); + } + }); + } + + /** + * Maps {@code JInternalFrame.setIconifiable(boolean)} through queue + */ + public void setIconifiable(final boolean b) { + runMapping(new MapVoidAction("setIconifiable") { + @Override + public void map() { + ((JInternalFrame) getSource()).setIconifiable(b); + } + }); + } + + /** + * Maps {@code JInternalFrame.setJMenuBar(JMenuBar)} through queue + */ + public void setJMenuBar(final JMenuBar jMenuBar) { + runMapping(new MapVoidAction("setJMenuBar") { + @Override + public void map() { + ((JInternalFrame) getSource()).setJMenuBar(jMenuBar); + } + }); + } + + /** + * Maps {@code JInternalFrame.setLayer(Integer)} through queue + */ + public void setLayer(final Integer integer) { + runMapping(new MapVoidAction("setLayer") { + @Override + public void map() { + ((JInternalFrame) getSource()).setLayer(integer); + } + }); + } + + /** + * Maps {@code JInternalFrame.setLayeredPane(JLayeredPane)} through queue + */ + public void setLayeredPane(final JLayeredPane jLayeredPane) { + runMapping(new MapVoidAction("setLayeredPane") { + @Override + public void map() { + ((JInternalFrame) getSource()).setLayeredPane(jLayeredPane); + } + }); + } + + /** + * Maps {@code JInternalFrame.setMaximizable(boolean)} through queue + */ + public void setMaximizable(final boolean b) { + runMapping(new MapVoidAction("setMaximizable") { + @Override + public void map() { + ((JInternalFrame) getSource()).setMaximizable(b); + } + }); + } + + /** + * Maps {@code JInternalFrame.setMaximum(boolean)} through queue + */ + public void setMaximum(final boolean b) { + runMapping(new MapVoidAction("setMaximum") { + @Override + public void map() throws PropertyVetoException { + ((JInternalFrame) getSource()).setMaximum(b); + } + }); + } + + /** + * Maps {@code JInternalFrame.setResizable(boolean)} through queue + */ + public void setResizable(final boolean b) { + runMapping(new MapVoidAction("setResizable") { + @Override + public void map() { + ((JInternalFrame) getSource()).setResizable(b); + } + }); + } + + /** + * Maps {@code JInternalFrame.setSelected(boolean)} through queue + */ + public void setSelected(final boolean b) { + runMapping(new MapVoidAction("setSelected") { + @Override + public void map() throws PropertyVetoException { + ((JInternalFrame) getSource()).setSelected(b); + } + }); + } + + /** + * Maps {@code JInternalFrame.setTitle(String)} through queue + */ + public void setTitle(final String string) { + runMapping(new MapVoidAction("setTitle") { + @Override + public void map() { + ((JInternalFrame) getSource()).setTitle(string); + } + }); + } + + /** + * Maps {@code JInternalFrame.setUI(InternalFrameUI)} through queue + */ + public void setUI(final InternalFrameUI internalFrameUI) { + runMapping(new MapVoidAction("setUI") { + @Override + public void map() { + ((JInternalFrame) getSource()).setUI(internalFrameUI); + } + }); + } + + /** + * Maps {@code JInternalFrame.toBack()} through queue + */ + public void toBack() { + runMapping(new MapVoidAction("toBack") { + @Override + public void map() { + ((JInternalFrame) getSource()).toBack(); + } + }); + } + + /** + * Maps {@code JInternalFrame.toFront()} through queue + */ + public void toFront() { + runMapping(new MapVoidAction("toFront") { + @Override + 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() { + @Override + public boolean checkComponent(Component comp) { + return comp instanceof JDesktopPane; + } + + @Override + public String getDescription() { + return "Desctop pane"; + } + + @Override + public String toString() { + return "JInternalFrameOperator.initOperators.ComponentChooser{description = " + getDescription() + '}'; + } + }) != 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 static class WrongInternalFrameStateException extends JemmyInputException { + + private static final long serialVersionUID = 42L; + + /** + * 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()); + } + + @Override + 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; + } + + @Override + public String getDescription() { + return "JInternalFrame with title \"" + label + "\""; + } + + @Override + public String toString() { + return "JInternalFrameByTitleFinder{" + "label=" + label + ", comparator=" + comparator + '}'; + } + } + + /** + * 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()); + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + public void setTimeouts(Timeouts times) { + timeouts = times; + super.setTimeouts(timeouts); + } + + @Override + 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")); + } + + @Override + public boolean checkComponent(Component comp) { + return ((comp instanceof JInternalFrame || comp instanceof JInternalFrame.JDesktopIcon) + && sf.checkComponent(comp)); + } + + @Override + public String getDescription() { + return sf.getDescription(); + } + + @Override + public String toString() { + return "JInternalFrameFinder{" + "sf=" + sf + '}'; + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JLabelOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JLabelOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,629 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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. + */ + @Override + 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 {@code JLabel.getDisabledIcon()} through queue + */ + public Icon getDisabledIcon() { + return (runMapping(new MapAction("getDisabledIcon") { + @Override + public Icon map() { + return ((JLabel) getSource()).getDisabledIcon(); + } + })); + } + + /** + * Maps {@code JLabel.getDisplayedMnemonic()} through queue + */ + public int getDisplayedMnemonic() { + return (runMapping(new MapIntegerAction("getDisplayedMnemonic") { + @Override + public int map() { + return ((JLabel) getSource()).getDisplayedMnemonic(); + } + })); + } + + /** + * Maps {@code JLabel.getHorizontalAlignment()} through queue + */ + public int getHorizontalAlignment() { + return (runMapping(new MapIntegerAction("getHorizontalAlignment") { + @Override + public int map() { + return ((JLabel) getSource()).getHorizontalAlignment(); + } + })); + } + + /** + * Maps {@code JLabel.getHorizontalTextPosition()} through queue + */ + public int getHorizontalTextPosition() { + return (runMapping(new MapIntegerAction("getHorizontalTextPosition") { + @Override + public int map() { + return ((JLabel) getSource()).getHorizontalTextPosition(); + } + })); + } + + /** + * Maps {@code JLabel.getIcon()} through queue + */ + public Icon getIcon() { + return (runMapping(new MapAction("getIcon") { + @Override + public Icon map() { + return ((JLabel) getSource()).getIcon(); + } + })); + } + + /** + * Maps {@code JLabel.getIconTextGap()} through queue + */ + public int getIconTextGap() { + return (runMapping(new MapIntegerAction("getIconTextGap") { + @Override + public int map() { + return ((JLabel) getSource()).getIconTextGap(); + } + })); + } + + /** + * Maps {@code JLabel.getLabelFor()} through queue + */ + public Component getLabelFor() { + return (runMapping(new MapAction("getLabelFor") { + @Override + public Component map() { + return ((JLabel) getSource()).getLabelFor(); + } + })); + } + + /** + * Maps {@code JLabel.getText()} through queue + */ + public String getText() { + return (runMapping(new MapAction("getText") { + @Override + public String map() { + return ((JLabel) getSource()).getText(); + } + })); + } + + /** + * Maps {@code JLabel.getUI()} through queue + */ + public LabelUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public LabelUI map() { + return ((JLabel) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JLabel.getVerticalAlignment()} through queue + */ + public int getVerticalAlignment() { + return (runMapping(new MapIntegerAction("getVerticalAlignment") { + @Override + public int map() { + return ((JLabel) getSource()).getVerticalAlignment(); + } + })); + } + + /** + * Maps {@code JLabel.getVerticalTextPosition()} through queue + */ + public int getVerticalTextPosition() { + return (runMapping(new MapIntegerAction("getVerticalTextPosition") { + @Override + public int map() { + return ((JLabel) getSource()).getVerticalTextPosition(); + } + })); + } + + /** + * Maps {@code JLabel.setDisabledIcon(Icon)} through queue + */ + public void setDisabledIcon(final Icon icon) { + runMapping(new MapVoidAction("setDisabledIcon") { + @Override + public void map() { + ((JLabel) getSource()).setDisabledIcon(icon); + } + }); + } + + /** + * Maps {@code JLabel.setDisplayedMnemonic(char)} through queue + */ + public void setDisplayedMnemonic(final char c) { + runMapping(new MapVoidAction("setDisplayedMnemonic") { + @Override + public void map() { + ((JLabel) getSource()).setDisplayedMnemonic(c); + } + }); + } + + /** + * Maps {@code JLabel.setDisplayedMnemonic(int)} through queue + */ + public void setDisplayedMnemonic(final int i) { + runMapping(new MapVoidAction("setDisplayedMnemonic") { + @Override + public void map() { + ((JLabel) getSource()).setDisplayedMnemonic(i); + } + }); + } + + /** + * Maps {@code JLabel.setHorizontalAlignment(int)} through queue + */ + public void setHorizontalAlignment(final int i) { + runMapping(new MapVoidAction("setHorizontalAlignment") { + @Override + public void map() { + ((JLabel) getSource()).setHorizontalAlignment(i); + } + }); + } + + /** + * Maps {@code JLabel.setHorizontalTextPosition(int)} through queue + */ + public void setHorizontalTextPosition(final int i) { + runMapping(new MapVoidAction("setHorizontalTextPosition") { + @Override + public void map() { + ((JLabel) getSource()).setHorizontalTextPosition(i); + } + }); + } + + /** + * Maps {@code JLabel.setIcon(Icon)} through queue + */ + public void setIcon(final Icon icon) { + runMapping(new MapVoidAction("setIcon") { + @Override + public void map() { + ((JLabel) getSource()).setIcon(icon); + } + }); + } + + /** + * Maps {@code JLabel.setIconTextGap(int)} through queue + */ + public void setIconTextGap(final int i) { + runMapping(new MapVoidAction("setIconTextGap") { + @Override + public void map() { + ((JLabel) getSource()).setIconTextGap(i); + } + }); + } + + /** + * Maps {@code JLabel.setLabelFor(Component)} through queue + */ + public void setLabelFor(final Component component) { + runMapping(new MapVoidAction("setLabelFor") { + @Override + public void map() { + ((JLabel) getSource()).setLabelFor(component); + } + }); + } + + /** + * Maps {@code JLabel.setText(String)} through queue + */ + public void setText(final String string) { + runMapping(new MapVoidAction("setText") { + @Override + public void map() { + ((JLabel) getSource()).setText(string); + } + }); + } + + /** + * Maps {@code JLabel.setUI(LabelUI)} through queue + */ + public void setUI(final LabelUI labelUI) { + runMapping(new MapVoidAction("setUI") { + @Override + public void map() { + ((JLabel) getSource()).setUI(labelUI); + } + }); + } + + /** + * Maps {@code JLabel.setVerticalAlignment(int)} through queue + */ + public void setVerticalAlignment(final int i) { + runMapping(new MapVoidAction("setVerticalAlignment") { + @Override + public void map() { + ((JLabel) getSource()).setVerticalAlignment(i); + } + }); + } + + /** + * Maps {@code JLabel.setVerticalTextPosition(int)} through queue + */ + public void setVerticalTextPosition(final int i) { + runMapping(new MapVoidAction("setVerticalTextPosition") { + @Override + 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()); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof JLabel) { + if (((JLabel) comp).getText() != null) { + return (comparator.equals(((JLabel) comp).getText(), + label)); + } + } + return false; + } + + @Override + public String getDescription() { + return "JLabel with text \"" + label + "\""; + } + + @Override + public String toString() { + return "JLabelByLabelFinder{" + "label=" + label + ", comparator=" + comparator + '}'; + } + } + + /** + * 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JListOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JListOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1735 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void setOutput(TestOut output) { + super.setOutput(output.createErrorOutput()); + this.output = output; + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + 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. + */ + @SuppressWarnings(value = "unchecked") + public Component getRenderedComponent(int itemIndex, boolean isSelected, boolean cellHasFocus) { + return (((ListCellRenderer) 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) + */ + @Deprecated + 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) + */ + @Deprecated + 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") { + @Override + 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") { + @Override + 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) + */ + @Deprecated + 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) + */ + @Deprecated + 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) + */ + @Deprecated + 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") { + @Override + public Void 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() { + @Override + 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; + } + + @Override + public String getDescription() { + return ("Item has been " + + (selected ? "" : "un") + "selected"); + } + + @Override + public String toString() { + return "JListOperator.waitItemsSelection.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + /** + * 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. + */ + @Override + 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 {@code JList.addListSelectionListener(ListSelectionListener)} + * through queue + */ + public void addListSelectionListener(final ListSelectionListener listSelectionListener) { + runMapping(new MapVoidAction("addListSelectionListener") { + @Override + public void map() { + ((JList) getSource()).addListSelectionListener(listSelectionListener); + } + }); + } + + /** + * Maps {@code JList.addSelectionInterval(int, int)} through queue + */ + public void addSelectionInterval(final int i, final int i1) { + runMapping(new MapVoidAction("addSelectionInterval") { + @Override + public void map() { + ((JList) getSource()).addSelectionInterval(i, i1); + } + }); + } + + /** + * Maps {@code JList.clearSelection()} through queue + */ + public void clearSelection() { + runMapping(new MapVoidAction("clearSelection") { + @Override + public void map() { + ((JList) getSource()).clearSelection(); + } + }); + } + + /** + * Maps {@code JList.ensureIndexIsVisible(int)} through queue + */ + public void ensureIndexIsVisible(final int i) { + runMapping(new MapVoidAction("ensureIndexIsVisible") { + @Override + public void map() { + ((JList) getSource()).ensureIndexIsVisible(i); + } + }); + } + + /** + * Maps {@code JList.getAnchorSelectionIndex()} through queue + */ + public int getAnchorSelectionIndex() { + return (runMapping(new MapIntegerAction("getAnchorSelectionIndex") { + @Override + public int map() { + return ((JList) getSource()).getAnchorSelectionIndex(); + } + })); + } + + /** + * Maps {@code JList.getCellBounds(int, int)} through queue + */ + public Rectangle getCellBounds(final int i, final int i1) { + return (runMapping(new MapAction("getCellBounds") { + @Override + public Rectangle map() { + return ((JList) getSource()).getCellBounds(i, i1); + } + })); + } + + /** + * Maps {@code JList.getCellRenderer()} through queue + */ + public ListCellRenderer getCellRenderer() { + return (runMapping(new MapAction>("getCellRenderer") { + @Override + public ListCellRenderer map() { + return ((JList) getSource()).getCellRenderer(); + } + })); + } + + /** + * Maps {@code JList.getFirstVisibleIndex()} through queue + */ + public int getFirstVisibleIndex() { + return (runMapping(new MapIntegerAction("getFirstVisibleIndex") { + @Override + public int map() { + return ((JList) getSource()).getFirstVisibleIndex(); + } + })); + } + + /** + * Maps {@code JList.getFixedCellHeight()} through queue + */ + public int getFixedCellHeight() { + return (runMapping(new MapIntegerAction("getFixedCellHeight") { + @Override + public int map() { + return ((JList) getSource()).getFixedCellHeight(); + } + })); + } + + /** + * Maps {@code JList.getFixedCellWidth()} through queue + */ + public int getFixedCellWidth() { + return (runMapping(new MapIntegerAction("getFixedCellWidth") { + @Override + public int map() { + return ((JList) getSource()).getFixedCellWidth(); + } + })); + } + + /** + * Maps {@code JList.getLastVisibleIndex()} through queue + */ + public int getLastVisibleIndex() { + return (runMapping(new MapIntegerAction("getLastVisibleIndex") { + @Override + public int map() { + return ((JList) getSource()).getLastVisibleIndex(); + } + })); + } + + /** + * Maps {@code JList.getLeadSelectionIndex()} through queue + */ + public int getLeadSelectionIndex() { + return (runMapping(new MapIntegerAction("getLeadSelectionIndex") { + @Override + public int map() { + return ((JList) getSource()).getLeadSelectionIndex(); + } + })); + } + + /** + * Maps {@code JList.getMaxSelectionIndex()} through queue + */ + public int getMaxSelectionIndex() { + return (runMapping(new MapIntegerAction("getMaxSelectionIndex") { + @Override + public int map() { + return ((JList) getSource()).getMaxSelectionIndex(); + } + })); + } + + /** + * Maps {@code JList.getMinSelectionIndex()} through queue + */ + public int getMinSelectionIndex() { + return (runMapping(new MapIntegerAction("getMinSelectionIndex") { + @Override + public int map() { + return ((JList) getSource()).getMinSelectionIndex(); + } + })); + } + + /** + * Maps {@code JList.getModel()} through queue + */ + public ListModel getModel() { + return (runMapping(new MapAction>("getModel") { + @Override + public ListModel map() { + return ((JList) getSource()).getModel(); + } + })); + } + + /** + * Maps {@code JList.getPreferredScrollableViewportSize()} through queue + */ + public Dimension getPreferredScrollableViewportSize() { + return (runMapping(new MapAction("getPreferredScrollableViewportSize") { + @Override + public Dimension map() { + return ((JList) getSource()).getPreferredScrollableViewportSize(); + } + })); + } + + /** + * Maps {@code JList.getPrototypeCellValue()} through queue + */ + public Object getPrototypeCellValue() { + return (runMapping(new MapAction("getPrototypeCellValue") { + @Override + public Object map() { + return ((JList) getSource()).getPrototypeCellValue(); + } + })); + } + + /** + * Maps {@code JList.getScrollableBlockIncrement(Rectangle, int, int)} + * through queue + */ + public int getScrollableBlockIncrement(final Rectangle rectangle, final int i, final int i1) { + return (runMapping(new MapIntegerAction("getScrollableBlockIncrement") { + @Override + public int map() { + return ((JList) getSource()).getScrollableBlockIncrement(rectangle, i, i1); + } + })); + } + + /** + * Maps {@code JList.getScrollableTracksViewportHeight()} through queue + */ + public boolean getScrollableTracksViewportHeight() { + return (runMapping(new MapBooleanAction("getScrollableTracksViewportHeight") { + @Override + public boolean map() { + return ((JList) getSource()).getScrollableTracksViewportHeight(); + } + })); + } + + /** + * Maps {@code JList.getScrollableTracksViewportWidth()} through queue + */ + public boolean getScrollableTracksViewportWidth() { + return (runMapping(new MapBooleanAction("getScrollableTracksViewportWidth") { + @Override + public boolean map() { + return ((JList) getSource()).getScrollableTracksViewportWidth(); + } + })); + } + + /** + * Maps {@code JList.getScrollableUnitIncrement(Rectangle, int, int)} + * through queue + */ + public int getScrollableUnitIncrement(final Rectangle rectangle, final int i, final int i1) { + return (runMapping(new MapIntegerAction("getScrollableUnitIncrement") { + @Override + public int map() { + return ((JList) getSource()).getScrollableUnitIncrement(rectangle, i, i1); + } + })); + } + + /** + * Maps {@code JList.getSelectedIndex()} through queue + */ + public int getSelectedIndex() { + return (runMapping(new MapIntegerAction("getSelectedIndex") { + @Override + public int map() { + return ((JList) getSource()).getSelectedIndex(); + } + })); + } + + /** + * Maps {@code JList.getSelectedIndices()} through queue + */ + public int[] getSelectedIndices() { + return ((int[]) runMapping(new MapAction("getSelectedIndices") { + @Override + public Object map() { + return ((JList) getSource()).getSelectedIndices(); + } + })); + } + + /** + * Maps {@code JList.getSelectedValue()} through queue + */ + public Object getSelectedValue() { + return (runMapping(new MapAction("getSelectedValue") { + @Override + public Object map() { + return ((JList) getSource()).getSelectedValue(); + } + })); + } + + /** + * Maps {@code JList.getSelectedValues()} through queue + */ + @Deprecated + public Object[] getSelectedValues() { + return ((Object[]) runMapping(new MapAction("getSelectedValues") { + @Override + public Object map() { + return ((JList) getSource()).getSelectedValues(); + } + })); + } + + /** + * Maps {@code JList.getSelectionBackground()} through queue + */ + public Color getSelectionBackground() { + return (runMapping(new MapAction("getSelectionBackground") { + @Override + public Color map() { + return ((JList) getSource()).getSelectionBackground(); + } + })); + } + + /** + * Maps {@code JList.getSelectionForeground()} through queue + */ + public Color getSelectionForeground() { + return (runMapping(new MapAction("getSelectionForeground") { + @Override + public Color map() { + return ((JList) getSource()).getSelectionForeground(); + } + })); + } + + /** + * Maps {@code JList.getSelectionMode()} through queue + */ + public int getSelectionMode() { + return (runMapping(new MapIntegerAction("getSelectionMode") { + @Override + public int map() { + return ((JList) getSource()).getSelectionMode(); + } + })); + } + + /** + * Maps {@code JList.getSelectionModel()} through queue + */ + public ListSelectionModel getSelectionModel() { + return (runMapping(new MapAction("getSelectionModel") { + @Override + public ListSelectionModel map() { + return ((JList) getSource()).getSelectionModel(); + } + })); + } + + /** + * Maps {@code JList.getUI()} through queue + */ + public ListUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public ListUI map() { + return ((JList) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JList.getValueIsAdjusting()} through queue + */ + public boolean getValueIsAdjusting() { + return (runMapping(new MapBooleanAction("getValueIsAdjusting") { + @Override + public boolean map() { + return ((JList) getSource()).getValueIsAdjusting(); + } + })); + } + + /** + * Maps {@code JList.getVisibleRowCount()} through queue + */ + public int getVisibleRowCount() { + return (runMapping(new MapIntegerAction("getVisibleRowCount") { + @Override + public int map() { + return ((JList) getSource()).getVisibleRowCount(); + } + })); + } + + /** + * Maps {@code JList.indexToLocation(int)} through queue + */ + public Point indexToLocation(final int i) { + return (runMapping(new MapAction("indexToLocation") { + @Override + public Point map() { + return ((JList) getSource()).indexToLocation(i); + } + })); + } + + /** + * Maps {@code JList.isSelectedIndex(int)} through queue + */ + public boolean isSelectedIndex(final int i) { + return (runMapping(new MapBooleanAction("isSelectedIndex") { + @Override + public boolean map() { + return ((JList) getSource()).isSelectedIndex(i); + } + })); + } + + /** + * Maps {@code JList.isSelectionEmpty()} through queue + */ + public boolean isSelectionEmpty() { + return (runMapping(new MapBooleanAction("isSelectionEmpty") { + @Override + public boolean map() { + return ((JList) getSource()).isSelectionEmpty(); + } + })); + } + + /** + * Maps {@code JList.locationToIndex(Point)} through queue + */ + public int locationToIndex(final Point point) { + return (runMapping(new MapIntegerAction("locationToIndex") { + @Override + public int map() { + return ((JList) getSource()).locationToIndex(point); + } + })); + } + + /** + * Maps + * {@code JList.removeListSelectionListener(ListSelectionListener)} + * through queue + */ + public void removeListSelectionListener(final ListSelectionListener listSelectionListener) { + runMapping(new MapVoidAction("removeListSelectionListener") { + @Override + public void map() { + ((JList) getSource()).removeListSelectionListener(listSelectionListener); + } + }); + } + + /** + * Maps {@code JList.removeSelectionInterval(int, int)} through queue + */ + public void removeSelectionInterval(final int i, final int i1) { + runMapping(new MapVoidAction("removeSelectionInterval") { + @Override + public void map() { + ((JList) getSource()).removeSelectionInterval(i, i1); + } + }); + } + + /** + * Maps {@code JList.setCellRenderer(ListCellRenderer)} through queue + */ + @SuppressWarnings(value = "unchecked") + public void setCellRenderer(final ListCellRenderer listCellRenderer) { + runMapping(new MapVoidAction("setCellRenderer") { + @Override + public void map() { + ((JList) getSource()).setCellRenderer(listCellRenderer); + } + }); + } + + /** + * Maps {@code JList.setFixedCellHeight(int)} through queue + */ + public void setFixedCellHeight(final int i) { + runMapping(new MapVoidAction("setFixedCellHeight") { + @Override + public void map() { + ((JList) getSource()).setFixedCellHeight(i); + } + }); + } + + /** + * Maps {@code JList.setFixedCellWidth(int)} through queue + */ + public void setFixedCellWidth(final int i) { + runMapping(new MapVoidAction("setFixedCellWidth") { + @Override + public void map() { + ((JList) getSource()).setFixedCellWidth(i); + } + }); + } + + /** + * Maps {@code JList.setListData(Vector)} through queue + */ + @SuppressWarnings(value = "unchecked") + public void setListData(final Vector vector) { + runMapping(new MapVoidAction("setListData") { + @Override + public void map() { + ((JList) getSource()).setListData(vector); + } + }); + } + + /** + * Maps {@code JList.setListData(Object[])} through queue + */ + @SuppressWarnings(value = "unchecked") + public void setListData(final Object[] object) { + runMapping(new MapVoidAction("setListData") { + @Override + public void map() { + ((JList) getSource()).setListData(object); + } + }); + } + + /** + * Maps {@code JList.setModel(ListModel)} through queue + */ + @SuppressWarnings(value = "unchecked") + public void setModel(final ListModel listModel) { + runMapping(new MapVoidAction("setModel") { + @Override + public void map() { + ((JList) getSource()).setModel(listModel); + } + }); + } + + /** + * Maps {@code JList.setPrototypeCellValue(Object)} through queue + */ + @SuppressWarnings(value = "unchecked") + public void setPrototypeCellValue(final Object object) { + runMapping(new MapVoidAction("setPrototypeCellValue") { + @Override + public void map() { + ((JList) getSource()).setPrototypeCellValue(object); + } + }); + } + + /** + * Maps {@code JList.setSelectedIndex(int)} through queue + */ + public void setSelectedIndex(final int i) { + runMapping(new MapVoidAction("setSelectedIndex") { + @Override + public void map() { + ((JList) getSource()).setSelectedIndex(i); + } + }); + } + + /** + * Maps {@code JList.setSelectedIndices(int[])} through queue + */ + public void setSelectedIndices(final int[] i) { + runMapping(new MapVoidAction("setSelectedIndices") { + @Override + public void map() { + ((JList) getSource()).setSelectedIndices(i); + } + }); + } + + /** + * Maps {@code JList.setSelectedValue(Object, boolean)} through queue + */ + public void setSelectedValue(final Object object, final boolean b) { + runMapping(new MapVoidAction("setSelectedValue") { + @Override + public void map() { + ((JList) getSource()).setSelectedValue(object, b); + } + }); + } + + /** + * Maps {@code JList.setSelectionBackground(Color)} through queue + */ + public void setSelectionBackground(final Color color) { + runMapping(new MapVoidAction("setSelectionBackground") { + @Override + public void map() { + ((JList) getSource()).setSelectionBackground(color); + } + }); + } + + /** + * Maps {@code JList.setSelectionForeground(Color)} through queue + */ + public void setSelectionForeground(final Color color) { + runMapping(new MapVoidAction("setSelectionForeground") { + @Override + public void map() { + ((JList) getSource()).setSelectionForeground(color); + } + }); + } + + /** + * Maps {@code JList.setSelectionInterval(int, int)} through queue + */ + public void setSelectionInterval(final int i, final int i1) { + runMapping(new MapVoidAction("setSelectionInterval") { + @Override + public void map() { + ((JList) getSource()).setSelectionInterval(i, i1); + } + }); + } + + /** + * Maps {@code JList.setSelectionMode(int)} through queue + */ + public void setSelectionMode(final int i) { + runMapping(new MapVoidAction("setSelectionMode") { + @Override + public void map() { + ((JList) getSource()).setSelectionMode(i); + } + }); + } + + /** + * Maps {@code JList.setSelectionModel(ListSelectionModel)} through queue + */ + public void setSelectionModel(final ListSelectionModel listSelectionModel) { + runMapping(new MapVoidAction("setSelectionModel") { + @Override + public void map() { + ((JList) getSource()).setSelectionModel(listSelectionModel); + } + }); + } + + /** + * Maps {@code JList.setUI(ListUI)} through queue + */ + public void setUI(final ListUI listUI) { + runMapping(new MapVoidAction("setUI") { + @Override + public void map() { + ((JList) getSource()).setUI(listUI); + } + }); + } + + /** + * Maps {@code JList.setValueIsAdjusting(boolean)} through queue + */ + public void setValueIsAdjusting(final boolean b) { + runMapping(new MapVoidAction("setValueIsAdjusting") { + @Override + public void map() { + ((JList) getSource()).setValueIsAdjusting(b); + } + }); + } + + /** + * Maps {@code JList.setVisibleRowCount(int)} through queue + */ + public void setVisibleRowCount(final int i) { + runMapping(new MapVoidAction("setVisibleRowCount") { + @Override + 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 indice : indices) { + checkIndex(indice); + } + } + + /** + * 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 thrown during item selecting if list does not have item requested. + */ + public class NoSuchItemException extends JemmyInputException { + + private static final long serialVersionUID = 42L; + + /** + * 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 static class BySubStringListItemChooser implements ListItemChooser { + + String subString; + StringComparator comparator; + + public BySubStringListItemChooser(String subString, StringComparator comparator) { + this.subString = subString; + this.comparator = comparator; + } + + @Override + public boolean checkItem(JListOperator oper, int index) { + return (comparator.equals(oper.getModel().getElementAt(index).toString(), + subString)); + } + + @Override + public String getDescription() { + return "Item containing \"" + subString + "\" string"; + } + + @Override + public String toString() { + return "BySubStringListItemChooser{" + "subString=" + subString + ", comparator=" + comparator + '}'; + } + } + + private static class ByRenderedComponentListItemChooser implements ListItemChooser { + + ComponentChooser chooser; + + public ByRenderedComponentListItemChooser(ComponentChooser chooser) { + this.chooser = chooser; + } + + @Override + public boolean checkItem(JListOperator oper, int index) { + return chooser.checkComponent(oper.getRenderedComponent(index)); + } + + @Override + public String getDescription() { + return chooser.getDescription(); + } + + @Override + public String toString() { + return "ByRenderedComponentListItemChooser{" + "chooser=" + chooser + '}'; + } + } + + /** + * 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()); + } + + @Override + 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; + } + + @Override + public String getDescription() { + return ("JList with text \"" + label + "\" in " + + itemIndex + "'th item"); + } + + @Override + public String toString() { + return "JListByItemFinder{" + "label=" + label + ", itemIndex=" + itemIndex + ", comparator=" + comparator + '}'; + } + } + + /** + * 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JMenuBarOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JMenuBarOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,992 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); + } + + @Override + public void setOutput(TestOut out) { + super.setOutput(out); + output = out; + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + public void setTimeouts(Timeouts times) { + super.setTimeouts(times); + timeouts = times; + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + 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() { + @Override + public Object launch(Void obj) { + //TDB 1.5 menu workaround + getQueueTool().waitEmpty(); + Object result = driver.pushMenu(JMenuBarOperator.this, + JMenuOperator.converChoosers(choosers)); + getQueueTool().waitEmpty(); + return result; + } + + @Override + public String getDescription() { + return JMenuOperator.createDescription(choosers); + } + + @Override + public String toString() { + return "JMenuBarOperator.pushMenu.Action{description = " + getDescription() + '}'; + } + }, "JMenuOperator.PushMenuTimeout")); + } + + /** + * Executes {@code 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") { + @Override + public Object doAction(Void 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) + */ + @Deprecated + public JMenuItem pushMenu(String[] names, boolean ce, boolean ccs) { + return pushMenu(names, new DefaultStringComparator(ce, ccs)); + } + + /** + * Executes {@code 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 {@code 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) + */ + @Deprecated + 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 {@code 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) + */ + @Deprecated + public JMenuItem pushMenu(String path, String delim, boolean ce, boolean ccs) { + return pushMenu(parseString(path, delim), ce, ccs); + } + + /** + * Executes {@code 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 {@code 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 {@code 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) + */ + @Deprecated + 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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() { + @Override + public boolean checkComponent(Component comp) { + return (comp instanceof JMenu + && ((JMenu) comp).isPopupMenuVisible()); + } + + @Override + public String getDescription() { + return "Expanded JMenu"; + } + + @Override + public String toString() { + return "JMenuBarOperator.closeSubmenus.ComponentChooser{description = " + getDescription() + '}'; + } + }); + if (menu != null) { + JMenuOperator oper = new JMenuOperator(menu); + oper.copyEnvironment(this); + oper.push(); + } + } + + @Override + 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 {@code JMenuBar.add(JMenu)} through queue + */ + public JMenu add(final JMenu jMenu) { + return (runMapping(new MapAction("add") { + @Override + public JMenu map() { + return ((JMenuBar) getSource()).add(jMenu); + } + })); + } + + /** + * Maps {@code JMenuBar.getComponentIndex(Component)} through queue + */ + public int getComponentIndex(final Component component) { + return (runMapping(new MapIntegerAction("getComponentIndex") { + @Override + public int map() { + return ((JMenuBar) getSource()).getComponentIndex(component); + } + })); + } + + /** + * Maps {@code JMenuBar.getHelpMenu()} through queue + */ + public JMenu getHelpMenu() { + return (runMapping(new MapAction("getHelpMenu") { + @Override + public JMenu map() { + return ((JMenuBar) getSource()).getHelpMenu(); + } + })); + } + + /** + * Maps {@code JMenuBar.getMargin()} through queue + */ + public Insets getMargin() { + return (runMapping(new MapAction("getMargin") { + @Override + public Insets map() { + return ((JMenuBar) getSource()).getMargin(); + } + })); + } + + /** + * Maps {@code JMenuBar.getMenu(int)} through queue + */ + public JMenu getMenu(final int i) { + return (runMapping(new MapAction("getMenu") { + @Override + public JMenu map() { + return ((JMenuBar) getSource()).getMenu(i); + } + })); + } + + /** + * Maps {@code JMenuBar.getMenuCount()} through queue + */ + public int getMenuCount() { + return (runMapping(new MapIntegerAction("getMenuCount") { + @Override + public int map() { + return ((JMenuBar) getSource()).getMenuCount(); + } + })); + } + + /** + * Maps {@code JMenuBar.getSelectionModel()} through queue + */ + public SingleSelectionModel getSelectionModel() { + return (runMapping(new MapAction("getSelectionModel") { + @Override + public SingleSelectionModel map() { + return ((JMenuBar) getSource()).getSelectionModel(); + } + })); + } + + /** + * Maps {@code JMenuBar.getSubElements()} through queue + */ + public MenuElement[] getSubElements() { + return ((MenuElement[]) runMapping(new MapAction("getSubElements") { + @Override + public Object map() { + return ((JMenuBar) getSource()).getSubElements(); + } + })); + } + + /** + * Maps {@code JMenuBar.getUI()} through queue + */ + public MenuBarUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public MenuBarUI map() { + return ((JMenuBar) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JMenuBar.isBorderPainted()} through queue + */ + public boolean isBorderPainted() { + return (runMapping(new MapBooleanAction("isBorderPainted") { + @Override + public boolean map() { + return ((JMenuBar) getSource()).isBorderPainted(); + } + })); + } + + /** + * Maps {@code JMenuBar.isSelected()} through queue + */ + public boolean isSelected() { + return (runMapping(new MapBooleanAction("isSelected") { + @Override + public boolean map() { + return ((JMenuBar) getSource()).isSelected(); + } + })); + } + + /** + * Maps {@code JMenuBar.menuSelectionChanged(boolean)} through queue + */ + public void menuSelectionChanged(final boolean b) { + runMapping(new MapVoidAction("menuSelectionChanged") { + @Override + public void map() { + ((JMenuBar) getSource()).menuSelectionChanged(b); + } + }); + } + + /** + * Maps + * {@code JMenuBar.processKeyEvent(KeyEvent, MenuElement[], MenuSelectionManager)} + * through queue + */ + public void processKeyEvent(final KeyEvent keyEvent, final MenuElement[] menuElement, final MenuSelectionManager menuSelectionManager) { + runMapping(new MapVoidAction("processKeyEvent") { + @Override + public void map() { + ((JMenuBar) getSource()).processKeyEvent(keyEvent, menuElement, menuSelectionManager); + } + }); + } + + /** + * Maps + * {@code JMenuBar.processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager)} + * through queue + */ + public void processMouseEvent(final MouseEvent mouseEvent, final MenuElement[] menuElement, final MenuSelectionManager menuSelectionManager) { + runMapping(new MapVoidAction("processMouseEvent") { + @Override + public void map() { + ((JMenuBar) getSource()).processMouseEvent(mouseEvent, menuElement, menuSelectionManager); + } + }); + } + + /** + * Maps {@code JMenuBar.setBorderPainted(boolean)} through queue + */ + public void setBorderPainted(final boolean b) { + runMapping(new MapVoidAction("setBorderPainted") { + @Override + public void map() { + ((JMenuBar) getSource()).setBorderPainted(b); + } + }); + } + + /** + * Maps {@code JMenuBar.setHelpMenu(JMenu)} through queue + */ + public void setHelpMenu(final JMenu jMenu) { + runMapping(new MapVoidAction("setHelpMenu") { + @Override + public void map() { + ((JMenuBar) getSource()).setHelpMenu(jMenu); + } + }); + } + + /** + * Maps {@code JMenuBar.setMargin(Insets)} through queue + */ + public void setMargin(final Insets insets) { + runMapping(new MapVoidAction("setMargin") { + @Override + public void map() { + ((JMenuBar) getSource()).setMargin(insets); + } + }); + } + + /** + * Maps {@code JMenuBar.setSelected(Component)} through queue + */ + public void setSelected(final Component component) { + runMapping(new MapVoidAction("setSelected") { + @Override + public void map() { + ((JMenuBar) getSource()).setSelected(component); + } + }); + } + + /** + * Maps {@code JMenuBar.setSelectionModel(SingleSelectionModel)} + * through queue + */ + public void setSelectionModel(final SingleSelectionModel singleSelectionModel) { + runMapping(new MapVoidAction("setSelectionModel") { + @Override + public void map() { + ((JMenuBar) getSource()).setSelectionModel(singleSelectionModel); + } + }); + } + + /** + * Maps {@code JMenuBar.setUI(MenuBarUI)} through queue + */ + public void setUI(final MenuBarUI menuBarUI) { + runMapping(new MapVoidAction("setUI") { + @Override + 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); + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JMenuItemOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JMenuItemOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,657 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void setTimeouts(Timeouts timeouts) { + super.setTimeouts(timeouts); + this.timeouts = timeouts; + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut out) { + super.setOutput(out); + output = out; + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + public Hashtable getDump() { + Hashtable result = super.getDump(); + result.remove(AbstractButtonOperator.IS_SELECTED_DPROP); + return result; + } + + /** + * Push this menu item. + */ + @Override + public void push() { + setVisualizer(new EmptyVisualizer()); + super.push(); + } + + /** + * Push this menu item and no block further execution. + */ + @Override + public void pushNoBlock() { + setVisualizer(new EmptyVisualizer()); + super.pushNoBlock(); + } + + //////////////////////////////////////////////////////// + //Mapping // + /** + * Maps + * {@code JMenuItem.addMenuDragMouseListener(MenuDragMouseListener)} + * through queue + */ + public void addMenuDragMouseListener(final MenuDragMouseListener menuDragMouseListener) { + runMapping(new MapVoidAction("addMenuDragMouseListener") { + @Override + public void map() { + ((JMenuItem) getSource()).addMenuDragMouseListener(menuDragMouseListener); + } + }); + } + + /** + * Maps {@code JMenuItem.addMenuKeyListener(MenuKeyListener)} through queue + */ + public void addMenuKeyListener(final MenuKeyListener menuKeyListener) { + runMapping(new MapVoidAction("addMenuKeyListener") { + @Override + public void map() { + ((JMenuItem) getSource()).addMenuKeyListener(menuKeyListener); + } + }); + } + + /** + * Maps {@code JMenuItem.getAccelerator()} through queue + */ + public KeyStroke getAccelerator() { + return (runMapping(new MapAction("getAccelerator") { + @Override + public KeyStroke map() { + return ((JMenuItem) getSource()).getAccelerator(); + } + })); + } + + /** + * Maps {@code JMenuItem.getComponent()} through queue + */ + public Component getComponent() { + return (runMapping(new MapAction("getComponent") { + @Override + public Component map() { + return ((JMenuItem) getSource()).getComponent(); + } + })); + } + + /** + * Maps {@code JMenuItem.getSubElements()} through queue + */ + public MenuElement[] getSubElements() { + return ((MenuElement[]) runMapping(new MapAction("getSubElements") { + @Override + public Object map() { + return ((JMenuItem) getSource()).getSubElements(); + } + })); + } + + /** + * Maps {@code JMenuItem.isArmed()} through queue + */ + public boolean isArmed() { + return (runMapping(new MapBooleanAction("isArmed") { + @Override + public boolean map() { + return ((JMenuItem) getSource()).isArmed(); + } + })); + } + + /** + * Maps {@code JMenuItem.menuSelectionChanged(boolean)} through queue + */ + public void menuSelectionChanged(final boolean b) { + runMapping(new MapVoidAction("menuSelectionChanged") { + @Override + public void map() { + ((JMenuItem) getSource()).menuSelectionChanged(b); + } + }); + } + + /** + * Maps + * {@code JMenuItem.processKeyEvent(KeyEvent, MenuElement[], MenuSelectionManager)} + * through queue + */ + public void processKeyEvent(final KeyEvent keyEvent, final MenuElement[] menuElement, final MenuSelectionManager menuSelectionManager) { + runMapping(new MapVoidAction("processKeyEvent") { + @Override + public void map() { + ((JMenuItem) getSource()).processKeyEvent(keyEvent, menuElement, menuSelectionManager); + } + }); + } + + /** + * Maps {@code JMenuItem.processMenuDragMouseEvent(MenuDragMouseEvent)} + * through queue + */ + public void processMenuDragMouseEvent(final MenuDragMouseEvent menuDragMouseEvent) { + runMapping(new MapVoidAction("processMenuDragMouseEvent") { + @Override + public void map() { + ((JMenuItem) getSource()).processMenuDragMouseEvent(menuDragMouseEvent); + } + }); + } + + /** + * Maps {@code JMenuItem.processMenuKeyEvent(MenuKeyEvent)} through queue + */ + public void processMenuKeyEvent(final MenuKeyEvent menuKeyEvent) { + runMapping(new MapVoidAction("processMenuKeyEvent") { + @Override + public void map() { + ((JMenuItem) getSource()).processMenuKeyEvent(menuKeyEvent); + } + }); + } + + /** + * Maps + * {@code JMenuItem.processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager)} + * through queue + */ + public void processMouseEvent(final MouseEvent mouseEvent, final MenuElement[] menuElement, final MenuSelectionManager menuSelectionManager) { + runMapping(new MapVoidAction("processMouseEvent") { + @Override + public void map() { + ((JMenuItem) getSource()).processMouseEvent(mouseEvent, menuElement, menuSelectionManager); + } + }); + } + + /** + * Maps + * {@code JMenuItem.removeMenuDragMouseListener(MenuDragMouseListener)} + * through queue + */ + public void removeMenuDragMouseListener(final MenuDragMouseListener menuDragMouseListener) { + runMapping(new MapVoidAction("removeMenuDragMouseListener") { + @Override + public void map() { + ((JMenuItem) getSource()).removeMenuDragMouseListener(menuDragMouseListener); + } + }); + } + + /** + * Maps {@code JMenuItem.removeMenuKeyListener(MenuKeyListener)} + * through queue + */ + public void removeMenuKeyListener(final MenuKeyListener menuKeyListener) { + runMapping(new MapVoidAction("removeMenuKeyListener") { + @Override + public void map() { + ((JMenuItem) getSource()).removeMenuKeyListener(menuKeyListener); + } + }); + } + + /** + * Maps {@code JMenuItem.setAccelerator(KeyStroke)} through queue + */ + public void setAccelerator(final KeyStroke keyStroke) { + runMapping(new MapVoidAction("setAccelerator") { + @Override + public void map() { + ((JMenuItem) getSource()).setAccelerator(keyStroke); + } + }); + } + + /** + * Maps {@code JMenuItem.setArmed(boolean)} through queue + */ + public void setArmed(final boolean b) { + runMapping(new MapVoidAction("setArmed") { + @Override + public void map() { + ((JMenuItem) getSource()).setArmed(b); + } + }); + } + + /** + * Maps {@code JMenuItem.setUI(MenuItemUI)} through queue + */ + public void setUI(final MenuItemUI menuItemUI) { + runMapping(new MapVoidAction("setUI") { + @Override + 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 (Object element1 : elements) { + if (element1 instanceof JMenuItem) { + size++; + } + } + JMenuItemOperator[] result = new JMenuItemOperator[size]; + int index = 0; + for (Object element : elements) { + if (element instanceof JMenuItem) { + result[index] = new JMenuItemOperator((JMenuItem) element); + 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()); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof JMenuItem) { + if (((JMenuItem) comp).getText() != null) { + return (comparator.equals(((JMenuItem) comp).getText(), + label)); + } + } + return false; + } + + @Override + public String getDescription() { + return "JMenuItem with text \"" + label + "\""; + } + + @Override + public String toString() { + return "JMenuItemByLabelFinder{" + "label=" + label + ", comparator=" + comparator + '}'; + } + } + + /** + * 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JMenuOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JMenuOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1202 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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(); + } + + @Override + public void setTimeouts(Timeouts timeouts) { + super.setTimeouts(timeouts); + this.timeouts = timeouts; + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut out) { + super.setOutput(out); + output = out; + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + 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() { + @Override + public Object launch(Void obj) { + //TDB 1.5 menu workaround + getQueueTool().waitEmpty(); + Object result = driver.pushMenu(JMenuOperator.this, converChoosers(choosers)); + getQueueTool().waitEmpty(); + return result; + } + + @Override + public String getDescription() { + return createDescription(choosers); + } + + @Override + public String toString() { + return "JMenuOperator.pushMenu.Action{description = " + getDescription() + '}'; + } + }, "JMenuOperator.PushMenuTimeout")); + } + + /** + * Executes {@code 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") { + @Override + public Object doAction(Void 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) + */ + @Deprecated + public JMenuItem pushMenu(String[] names, boolean ce, boolean ccs) { + return pushMenu(names, new DefaultStringComparator(ce, ccs)); + } + + /** + * Executes {@code 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 {@code 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) + */ + @Deprecated + 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 {@code 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) + */ + @Deprecated + public JMenuItem pushMenu(String path, String delim, boolean ce, boolean ccs) { + return pushMenu(path, delim, new DefaultStringComparator(ce, ccs)); + } + + /** + * Executes {@code 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 {@code 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 {@code 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) + */ + @Deprecated + 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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()); + } + + @Override + 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 {@code JMenu.add(String)} through queue + */ + public JMenuItem add(final String string) { + return (runMapping(new MapAction("add") { + @Override + public JMenuItem map() { + return ((JMenu) getSource()).add(string); + } + })); + } + + /** + * Maps {@code JMenu.add(Action)} through queue + */ + public JMenuItem add(final javax.swing.Action action) { + return (runMapping(new MapAction("add") { + @Override + public JMenuItem map() { + return ((JMenu) getSource()).add(action); + } + })); + } + + /** + * Maps {@code JMenu.add(JMenuItem)} through queue + */ + public JMenuItem add(final JMenuItem jMenuItem) { + return (runMapping(new MapAction("add") { + @Override + public JMenuItem map() { + return ((JMenu) getSource()).add(jMenuItem); + } + })); + } + + /** + * Maps {@code JMenu.addMenuListener(MenuListener)} through queue + */ + public void addMenuListener(final MenuListener menuListener) { + runMapping(new MapVoidAction("addMenuListener") { + @Override + public void map() { + ((JMenu) getSource()).addMenuListener(menuListener); + } + }); + } + + /** + * Maps {@code JMenu.addSeparator()} through queue + */ + public void addSeparator() { + runMapping(new MapVoidAction("addSeparator") { + @Override + public void map() { + ((JMenu) getSource()).addSeparator(); + } + }); + } + + /** + * Maps {@code JMenu.getDelay()} through queue + */ + public int getDelay() { + return (runMapping(new MapIntegerAction("getDelay") { + @Override + public int map() { + return ((JMenu) getSource()).getDelay(); + } + })); + } + + /** + * Maps {@code JMenu.getItem(int)} through queue + */ + public JMenuItem getItem(final int i) { + return (runMapping(new MapAction("getItem") { + @Override + public JMenuItem map() { + return ((JMenu) getSource()).getItem(i); + } + })); + } + + /** + * Maps {@code JMenu.getItemCount()} through queue + */ + public int getItemCount() { + return (runMapping(new MapIntegerAction("getItemCount") { + @Override + public int map() { + return ((JMenu) getSource()).getItemCount(); + } + })); + } + + /** + * Maps {@code JMenu.getMenuComponent(int)} through queue + */ + public Component getMenuComponent(final int i) { + return (runMapping(new MapAction("getMenuComponent") { + @Override + public Component map() { + return ((JMenu) getSource()).getMenuComponent(i); + } + })); + } + + /** + * Maps {@code JMenu.getMenuComponentCount()} through queue + */ + public int getMenuComponentCount() { + return (runMapping(new MapIntegerAction("getMenuComponentCount") { + @Override + public int map() { + return ((JMenu) getSource()).getMenuComponentCount(); + } + })); + } + + /** + * Maps {@code JMenu.getMenuComponents()} through queue + */ + public Component[] getMenuComponents() { + return ((Component[]) runMapping(new MapAction("getMenuComponents") { + @Override + public Object map() { + return ((JMenu) getSource()).getMenuComponents(); + } + })); + } + + /** + * Maps {@code JMenu.getPopupMenu()} through queue + */ + public JPopupMenu getPopupMenu() { + return (runMapping(new MapAction("getPopupMenu") { + @Override + public JPopupMenu map() { + return ((JMenu) getSource()).getPopupMenu(); + } + })); + } + + /** + * Maps {@code JMenu.insert(String, int)} through queue + */ + public void insert(final String string, final int i) { + runMapping(new MapVoidAction("insert") { + @Override + public void map() { + ((JMenu) getSource()).insert(string, i); + } + }); + } + + /** + * Maps {@code JMenu.insert(Action, int)} through queue + */ + public JMenuItem insert(final javax.swing.Action action, final int i) { + return (runMapping(new MapAction("insert") { + @Override + public JMenuItem map() { + return ((JMenu) getSource()).insert(action, i); + } + })); + } + + /** + * Maps {@code JMenu.insert(JMenuItem, int)} through queue + */ + public JMenuItem insert(final JMenuItem jMenuItem, final int i) { + return (runMapping(new MapAction("insert") { + @Override + public JMenuItem map() { + return ((JMenu) getSource()).insert(jMenuItem, i); + } + })); + } + + /** + * Maps {@code JMenu.insertSeparator(int)} through queue + */ + public void insertSeparator(final int i) { + runMapping(new MapVoidAction("insertSeparator") { + @Override + public void map() { + ((JMenu) getSource()).insertSeparator(i); + } + }); + } + + /** + * Maps {@code JMenu.isMenuComponent(Component)} through queue + */ + public boolean isMenuComponent(final Component component) { + return (runMapping(new MapBooleanAction("isMenuComponent") { + @Override + public boolean map() { + return ((JMenu) getSource()).isMenuComponent(component); + } + })); + } + + /** + * Maps {@code JMenu.isPopupMenuVisible()} through queue + */ + public boolean isPopupMenuVisible() { + return (runMapping(new MapBooleanAction("isPopupMenuVisible") { + @Override + public boolean map() { + return ((JMenu) getSource()).isPopupMenuVisible(); + } + })); + } + + /** + * Maps {@code JMenu.isTearOff()} through queue + */ + public boolean isTearOff() { + return (runMapping(new MapBooleanAction("isTearOff") { + @Override + public boolean map() { + return ((JMenu) getSource()).isTearOff(); + } + })); + } + + /** + * Maps {@code JMenu.isTopLevelMenu()} through queue + */ + public boolean isTopLevelMenu() { + return (runMapping(new MapBooleanAction("isTopLevelMenu") { + @Override + public boolean map() { + return ((JMenu) getSource()).isTopLevelMenu(); + } + })); + } + + /** + * Maps {@code JMenu.remove(JMenuItem)} through queue + */ + public void remove(final JMenuItem jMenuItem) { + runMapping(new MapVoidAction("remove") { + @Override + public void map() { + ((JMenu) getSource()).remove(jMenuItem); + } + }); + } + + /** + * Maps {@code JMenu.removeMenuListener(MenuListener)} through queue + */ + public void removeMenuListener(final MenuListener menuListener) { + runMapping(new MapVoidAction("removeMenuListener") { + @Override + public void map() { + ((JMenu) getSource()).removeMenuListener(menuListener); + } + }); + } + + /** + * Maps {@code JMenu.setDelay(int)} through queue + */ + public void setDelay(final int i) { + runMapping(new MapVoidAction("setDelay") { + @Override + public void map() { + ((JMenu) getSource()).setDelay(i); + } + }); + } + + /** + * Maps {@code JMenu.setMenuLocation(int, int)} through queue + */ + public void setMenuLocation(final int i, final int i1) { + runMapping(new MapVoidAction("setMenuLocation") { + @Override + public void map() { + ((JMenu) getSource()).setMenuLocation(i, i1); + } + }); + } + + /** + * Maps {@code JMenu.setPopupMenuVisible(boolean)} through queue + */ + public void setPopupMenuVisible(final boolean b) { + runMapping(new MapVoidAction("setPopupMenuVisible") { + @Override + public void map() { + ((JMenu) getSource()).setPopupMenuVisible(b); + } + }); + } + + //End of mapping // + //////////////////////////////////////////////////////// + static String createDescription(ComponentChooser[] choosers) { + StringBuilder description = new StringBuilder("("); + for (int i = 0; i < choosers.length; i++) { + if (i > 0) { + description.append(", "); + } + description.append(choosers[i].getDescription()); + } + description.append(")"); + return "Menu pushing: " + description.toString(); + } + + static DescriptablePathChooser converChoosers(final ComponentChooser[] choosers) { + return (new DescriptablePathChooser() { + @Override + public boolean checkPathComponent(int depth, Object component) { + return choosers[depth].checkComponent((Component) component); + } + + @Override + public int getDepth() { + return choosers.length; + } + + @Override + public String getDescription() { + return createDescription(choosers); + } + + @Override + public String toString() { + return "JMenuOperator.converChoosers.DescriptablePathChooser{description = " + getDescription() + '}'; + } + }); + } + + /** + * 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()); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof JMenu) { + if (((JMenu) comp).getText() != null) { + return (comparator.equals(((JMenu) comp).getText(), + label)); + } + } + return false; + } + + @Override + public String getDescription() { + return "JMenu with text \"" + label + "\""; + } + + @Override + public String toString() { + return "JMenuByLabelFinder{" + "label=" + label + ", comparator=" + comparator + '}'; + } + } + + /** + * 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JPasswordFieldOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JPasswordFieldOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,347 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public Hashtable getDump() { + Hashtable result = super.getDump(); + result.put(ECHO_CHAR_DPROP, + Character.toString(((JPasswordField) getSource()).getEchoChar())); + return result; + } + + //////////////////////////////////////////////////////// + //Mapping // + /** + * Maps {@code JPasswordField.echoCharIsSet()} through queue + */ + public boolean echoCharIsSet() { + return (runMapping(new MapBooleanAction("echoCharIsSet") { + @Override + public boolean map() { + return ((JPasswordField) getSource()).echoCharIsSet(); + } + })); + } + + /** + * Maps {@code JPasswordField.getEchoChar()} through queue + */ + public char getEchoChar() { + return (runMapping(new MapCharacterAction("getEchoChar") { + @Override + public char map() { + return ((JPasswordField) getSource()).getEchoChar(); + } + })); + } + + /** + * Maps {@code JPasswordField.getPassword()} through queue + */ + public char[] getPassword() { + return ((char[]) runMapping(new MapAction("getPassword") { + @Override + public Object map() { + return ((JPasswordField) getSource()).getPassword(); + } + })); + } + + /** + * Maps {@code JPasswordField.setEchoChar(char)} through queue + */ + public void setEchoChar(final char c) { + runMapping(new MapVoidAction("setEchoChar") { + @Override + 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JPopupMenuOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JPopupMenuOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1384 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 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 {@code 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() { + @Override + public boolean checkComponent(Component comp) { + ComponentSearcher searcher = new ComponentSearcher((Container) comp); + searcher.setOutput(JemmyProperties.getCurrentOutput().createErrorOutput()); + return searcher.findComponent(popupChooser) != null; + } + + @Override + public String getDescription() { + return "Window containing \"" + popupChooser.getDescription() + "\" popup"; + } + + @Override + public String toString() { + return "JPopupMenuOperator.waitJPopupMenu.ComponentChooser{description = " + getDescription() + '}'; + } + })); + return new JPopupMenuOperator(wind); + } catch (InterruptedException e) { + throw (new JemmyException("Popup waiting has been interrupted", e)); + } + } + + /** + * Waits popup containing menu item with {@code 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() { + @Override + 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; + } + } + + @Override + public String getDescription() { + return "Popup containing \"" + menuItemText + "\" menu item"; + } + + @Override + public String toString() { + return "JPopupMenuOperator.waitJPopupMenu.ComponentChooser{description = " + getDescription() + '}'; + } + })); + } + + /** + * 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() { + @Override + 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))); + } + + @Override + public String getDescription() { + return "Popup menu"; + } + + @Override + public String toString() { + return "JPopupMenuOperator.callPopup.ComponentChooser{description = " + getDescription() + '}'; + } + }), + 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(); + } + + @Override + public void setOutput(TestOut out) { + super.setOutput(out); + output = out; + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + public void setTimeouts(Timeouts times) { + super.setTimeouts(times); + timeouts = times; + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + 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() { + @Override + public Object launch(Void obj) { + //TDB 1.5 menu workaround + getQueueTool().waitEmpty(); + Object result = driver.pushMenu(JPopupMenuOperator.this, + JMenuOperator.converChoosers(choosers)); + getQueueTool().waitEmpty(); + return result; + } + + @Override + public String getDescription() { + return JMenuOperator.createDescription(choosers); + } + + @Override + public String toString() { + return "JPopupMenuOperator.pushMenu.ComponentChooser{description = " + getDescription() + '}'; + } + }, "JMenuOperator.PushMenuTimeout")); + } + + /** + * Executes {@code 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") { + @Override + public Object doAction(Void 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) + */ + @Deprecated + public JMenuItem pushMenu(String[] names, boolean ce, boolean ccs) { + return pushMenu(names, new DefaultStringComparator(ce, ccs)); + } + + /** + * Executes {@code 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 {@code 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) + */ + @Deprecated + 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 {@code 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) + */ + @Deprecated + public JMenuItem pushMenu(String path, String delim, boolean ce, boolean ccs) { + return pushMenu(parseString(path, delim), ce, ccs); + } + + /** + * Executes {@code 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 {@code 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 {@code 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) + */ + @Deprecated + 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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()); + } + + @Override + public Hashtable getDump() { + Hashtable result = super.getDump(); + if (((JPopupMenu) getSource()).getLabel() != null) { + result.put(LABEL_DPROP, ((JPopupMenu) getSource()).getLabel()); + } + return result; + } + + //////////////////////////////////////////////////////// + //Mapping // + /** + * Maps {@code JPopupMenu.add(String)} through queue + */ + public JMenuItem add(final String string) { + return (runMapping(new MapAction("add") { + @Override + public JMenuItem map() { + return ((JPopupMenu) getSource()).add(string); + } + })); + } + + /** + * Maps {@code JPopupMenu.add(Action)} through queue + */ + public JMenuItem add(final javax.swing.Action action) { + return (runMapping(new MapAction("add") { + @Override + public JMenuItem map() { + return ((JPopupMenu) getSource()).add(action); + } + })); + } + + /** + * Maps {@code JPopupMenu.add(JMenuItem)} through queue + */ + public JMenuItem add(final JMenuItem jMenuItem) { + return (runMapping(new MapAction("add") { + @Override + public JMenuItem map() { + return ((JPopupMenu) getSource()).add(jMenuItem); + } + })); + } + + /** + * Maps {@code JPopupMenu.addPopupMenuListener(PopupMenuListener)} + * through queue + */ + public void addPopupMenuListener(final PopupMenuListener popupMenuListener) { + runMapping(new MapVoidAction("addPopupMenuListener") { + @Override + public void map() { + ((JPopupMenu) getSource()).addPopupMenuListener(popupMenuListener); + } + }); + } + + /** + * Maps {@code JPopupMenu.addSeparator()} through queue + */ + public void addSeparator() { + runMapping(new MapVoidAction("addSeparator") { + @Override + public void map() { + ((JPopupMenu) getSource()).addSeparator(); + } + }); + } + + /** + * Maps {@code JPopupMenu.getComponentIndex(Component)} through queue + */ + public int getComponentIndex(final Component component) { + return (runMapping(new MapIntegerAction("getComponentIndex") { + @Override + public int map() { + return ((JPopupMenu) getSource()).getComponentIndex(component); + } + })); + } + + /** + * Maps {@code JPopupMenu.getInvoker()} through queue + */ + public Component getInvoker() { + return (runMapping(new MapAction("getInvoker") { + @Override + public Component map() { + return ((JPopupMenu) getSource()).getInvoker(); + } + })); + } + + /** + * Maps {@code JPopupMenu.getLabel()} through queue + */ + public String getLabel() { + return (runMapping(new MapAction("getLabel") { + @Override + public String map() { + return ((JPopupMenu) getSource()).getLabel(); + } + })); + } + + /** + * Maps {@code JPopupMenu.getMargin()} through queue + */ + public Insets getMargin() { + return (runMapping(new MapAction("getMargin") { + @Override + public Insets map() { + return ((JPopupMenu) getSource()).getMargin(); + } + })); + } + + /** + * Maps {@code JPopupMenu.getSelectionModel()} through queue + */ + public SingleSelectionModel getSelectionModel() { + return (runMapping(new MapAction("getSelectionModel") { + @Override + public SingleSelectionModel map() { + return ((JPopupMenu) getSource()).getSelectionModel(); + } + })); + } + + /** + * Maps {@code JPopupMenu.getSubElements()} through queue + */ + public MenuElement[] getSubElements() { + return ((MenuElement[]) runMapping(new MapAction("getSubElements") { + @Override + public Object map() { + return ((JPopupMenu) getSource()).getSubElements(); + } + })); + } + + /** + * Maps {@code JPopupMenu.getUI()} through queue + */ + public PopupMenuUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public PopupMenuUI map() { + return ((JPopupMenu) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JPopupMenu.insert(Component, int)} through queue + */ + public void insert(final Component component, final int i) { + runMapping(new MapVoidAction("insert") { + @Override + public void map() { + ((JPopupMenu) getSource()).insert(component, i); + } + }); + } + + /** + * Maps {@code JPopupMenu.insert(Action, int)} through queue + */ + public void insert(final javax.swing.Action action, final int i) { + runMapping(new MapVoidAction("insert") { + @Override + public void map() { + ((JPopupMenu) getSource()).insert(action, i); + } + }); + } + + /** + * Maps {@code JPopupMenu.isBorderPainted()} through queue + */ + public boolean isBorderPainted() { + return (runMapping(new MapBooleanAction("isBorderPainted") { + @Override + public boolean map() { + return ((JPopupMenu) getSource()).isBorderPainted(); + } + })); + } + + /** + * Maps {@code JPopupMenu.isLightWeightPopupEnabled()} through queue + */ + public boolean isLightWeightPopupEnabled() { + return (runMapping(new MapBooleanAction("isLightWeightPopupEnabled") { + @Override + public boolean map() { + return ((JPopupMenu) getSource()).isLightWeightPopupEnabled(); + } + })); + } + + /** + * Maps {@code JPopupMenu.menuSelectionChanged(boolean)} through queue + */ + public void menuSelectionChanged(final boolean b) { + runMapping(new MapVoidAction("menuSelectionChanged") { + @Override + public void map() { + ((JPopupMenu) getSource()).menuSelectionChanged(b); + } + }); + } + + /** + * Maps {@code JPopupMenu.pack()} through queue + */ + public void pack() { + runMapping(new MapVoidAction("pack") { + @Override + public void map() { + ((JPopupMenu) getSource()).pack(); + } + }); + } + + /** + * Maps + * {@code JPopupMenu.processKeyEvent(KeyEvent, MenuElement[], MenuSelectionManager)} + * through queue + */ + public void processKeyEvent(final KeyEvent keyEvent, final MenuElement[] menuElement, final MenuSelectionManager menuSelectionManager) { + runMapping(new MapVoidAction("processKeyEvent") { + @Override + public void map() { + ((JPopupMenu) getSource()).processKeyEvent(keyEvent, menuElement, menuSelectionManager); + } + }); + } + + /** + * Maps + * {@code JPopupMenu.processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager)} + * through queue + */ + public void processMouseEvent(final MouseEvent mouseEvent, final MenuElement[] menuElement, final MenuSelectionManager menuSelectionManager) { + runMapping(new MapVoidAction("processMouseEvent") { + @Override + public void map() { + ((JPopupMenu) getSource()).processMouseEvent(mouseEvent, menuElement, menuSelectionManager); + } + }); + } + + /** + * Maps {@code JPopupMenu.removePopupMenuListener(PopupMenuListener)} + * through queue + */ + public void removePopupMenuListener(final PopupMenuListener popupMenuListener) { + runMapping(new MapVoidAction("removePopupMenuListener") { + @Override + public void map() { + ((JPopupMenu) getSource()).removePopupMenuListener(popupMenuListener); + } + }); + } + + /** + * Maps {@code JPopupMenu.setBorderPainted(boolean)} through queue + */ + public void setBorderPainted(final boolean b) { + runMapping(new MapVoidAction("setBorderPainted") { + @Override + public void map() { + ((JPopupMenu) getSource()).setBorderPainted(b); + } + }); + } + + /** + * Maps {@code JPopupMenu.setInvoker(Component)} through queue + */ + public void setInvoker(final Component component) { + runMapping(new MapVoidAction("setInvoker") { + @Override + public void map() { + ((JPopupMenu) getSource()).setInvoker(component); + } + }); + } + + /** + * Maps {@code JPopupMenu.setLabel(String)} through queue + */ + public void setLabel(final String string) { + runMapping(new MapVoidAction("setLabel") { + @Override + public void map() { + ((JPopupMenu) getSource()).setLabel(string); + } + }); + } + + /** + * Maps {@code JPopupMenu.setLightWeightPopupEnabled(boolean)} through queue + */ + public void setLightWeightPopupEnabled(final boolean b) { + runMapping(new MapVoidAction("setLightWeightPopupEnabled") { + @Override + public void map() { + ((JPopupMenu) getSource()).setLightWeightPopupEnabled(b); + } + }); + } + + /** + * Maps {@code JPopupMenu.setPopupSize(int, int)} through queue + */ + public void setPopupSize(final int i, final int i1) { + runMapping(new MapVoidAction("setPopupSize") { + @Override + public void map() { + ((JPopupMenu) getSource()).setPopupSize(i, i1); + } + }); + } + + /** + * Maps {@code JPopupMenu.setPopupSize(Dimension)} through queue + */ + public void setPopupSize(final Dimension dimension) { + runMapping(new MapVoidAction("setPopupSize") { + @Override + public void map() { + ((JPopupMenu) getSource()).setPopupSize(dimension); + } + }); + } + + /** + * Maps {@code JPopupMenu.setSelected(Component)} through queue + */ + public void setSelected(final Component component) { + runMapping(new MapVoidAction("setSelected") { + @Override + public void map() { + ((JPopupMenu) getSource()).setSelected(component); + } + }); + } + + /** + * Maps {@code JPopupMenu.setSelectionModel(SingleSelectionModel)} + * through queue + */ + public void setSelectionModel(final SingleSelectionModel singleSelectionModel) { + runMapping(new MapVoidAction("setSelectionModel") { + @Override + public void map() { + ((JPopupMenu) getSource()).setSelectionModel(singleSelectionModel); + } + }); + } + + /** + * Maps {@code JPopupMenu.setUI(PopupMenuUI)} through queue + */ + public void setUI(final PopupMenuUI popupMenuUI) { + runMapping(new MapVoidAction("setUI") { + @Override + public void map() { + ((JPopupMenu) getSource()).setUI(popupMenuUI); + } + }); + } + + /** + * Maps {@code JPopupMenu.show(Component, int, int)} through queue + */ + public void show(final Component component, final int i, final int i1) { + runMapping(new MapVoidAction("show") { + @Override + 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); + } + + @Override + 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() { + @Override + public boolean checkComponent(Component comp) { + return (comp.isShowing() + && comp.isVisible() + && subFinder.checkComponent(comp)); + } + + @Override + public String getDescription() { + return subFinder.getDescription(); + } + + @Override + public String toString() { + return "JPopupMenuOperator.JPopupWindowFinder.ComponentChooser{description = " + getDescription() + '}'; + } + }; + } + + /** + * Constructs JPopupWindowFinder. + */ + public JPopupWindowFinder() { + this(ComponentSearcher.getTrueChooser("Any JPopupWindow")); + } + + @Override + 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; + } + + @Override + public String getDescription() { + return subFinder.getDescription(); + } + + @Override + public String toString() { + return "JPopupWindowFinder{" + "subFinder=" + subFinder + ", ppFinder=" + ppFinder + '}'; + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JProgressBarOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JProgressBarOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,679 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void setTimeouts(Timeouts timeouts) { + this.timeouts = timeouts; + super.setTimeouts(timeouts); + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + public TestOut getOutput() { + return output; + } + + /** + * Waits for criteria defined by {@code chooser} to be reached. + * + * @param chooser an object specifying waiting criteria. + * @see #waitValue(int) + * @deprecated Use waitState(ComponentChooser) instead. + */ + @Deprecated + 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() { + @Override + public String actionProduced(Void obj) { + return (chooser.checkValue(((JProgressBar) getSource()).getValue()) + ? "" : null); + } + + @Override + public String getDescription() { + return "\"" + chooser.getDescription() + "\" value"; + } + + @Override + public String toString() { + return "JProgressBarOperator.waitValue.Waitable{description = " + getDescription() + '}'; + } + }); + 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 {@code 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() { + @Override + public boolean checkComponent(Component comp) { + return ((JProgressBar) comp).getValue() >= value; + } + + @Override + public String getDescription() { + return "greater then " + Integer.toString(value); + } + + @Override + public String toString() { + return "JProgressBarOperator.waitValue.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + /** + * Waits progress bar string to match {@code 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() { + @Override + public boolean checkComponent(Component comp) { + return getComparator().equals(((JProgressBar) comp).getString(), value); + } + + @Override + public String getDescription() { + return "'" + value + "' string"; + } + + @Override + public String toString() { + return "JProgressBarOperator.waitValue.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + @Override + 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 {@code JProgressBar.addChangeListener(ChangeListener)} through queue + */ + public void addChangeListener(final ChangeListener changeListener) { + runMapping(new MapVoidAction("addChangeListener") { + @Override + public void map() { + ((JProgressBar) getSource()).addChangeListener(changeListener); + } + }); + } + + /** + * Maps {@code JProgressBar.getMaximum()} through queue + */ + public int getMaximum() { + return (runMapping(new MapIntegerAction("getMaximum") { + @Override + public int map() { + return ((JProgressBar) getSource()).getMaximum(); + } + })); + } + + /** + * Maps {@code JProgressBar.getMinimum()} through queue + */ + public int getMinimum() { + return (runMapping(new MapIntegerAction("getMinimum") { + @Override + public int map() { + return ((JProgressBar) getSource()).getMinimum(); + } + })); + } + + /** + * Maps {@code JProgressBar.getModel()} through queue + */ + public BoundedRangeModel getModel() { + return (runMapping(new MapAction("getModel") { + @Override + public BoundedRangeModel map() { + return ((JProgressBar) getSource()).getModel(); + } + })); + } + + /** + * Maps {@code JProgressBar.getOrientation()} through queue + */ + public int getOrientation() { + return (runMapping(new MapIntegerAction("getOrientation") { + @Override + public int map() { + return ((JProgressBar) getSource()).getOrientation(); + } + })); + } + + /** + * Maps {@code JProgressBar.getPercentComplete()} through queue + */ + public double getPercentComplete() { + return (runMapping(new MapDoubleAction("getPercentComplete") { + @Override + public double map() { + return ((JProgressBar) getSource()).getPercentComplete(); + } + })); + } + + /** + * Maps {@code JProgressBar.getString()} through queue + */ + public String getString() { + return (runMapping(new MapAction("getString") { + @Override + public String map() { + return ((JProgressBar) getSource()).getString(); + } + })); + } + + /** + * Maps {@code JProgressBar.getUI()} through queue + */ + public ProgressBarUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public ProgressBarUI map() { + return ((JProgressBar) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JProgressBar.getValue()} through queue + */ + public int getValue() { + return (runMapping(new MapIntegerAction("getValue") { + @Override + public int map() { + return ((JProgressBar) getSource()).getValue(); + } + })); + } + + /** + * Maps {@code JProgressBar.isBorderPainted()} through queue + */ + public boolean isBorderPainted() { + return (runMapping(new MapBooleanAction("isBorderPainted") { + @Override + public boolean map() { + return ((JProgressBar) getSource()).isBorderPainted(); + } + })); + } + + /** + * Maps {@code JProgressBar.isStringPainted()} through queue + */ + public boolean isStringPainted() { + return (runMapping(new MapBooleanAction("isStringPainted") { + @Override + public boolean map() { + return ((JProgressBar) getSource()).isStringPainted(); + } + })); + } + + /** + * Maps {@code JProgressBar.removeChangeListener(ChangeListener)} + * through queue + */ + public void removeChangeListener(final ChangeListener changeListener) { + runMapping(new MapVoidAction("removeChangeListener") { + @Override + public void map() { + ((JProgressBar) getSource()).removeChangeListener(changeListener); + } + }); + } + + /** + * Maps {@code JProgressBar.setBorderPainted(boolean)} through queue + */ + public void setBorderPainted(final boolean b) { + runMapping(new MapVoidAction("setBorderPainted") { + @Override + public void map() { + ((JProgressBar) getSource()).setBorderPainted(b); + } + }); + } + + /** + * Maps {@code JProgressBar.setMaximum(int)} through queue + */ + public void setMaximum(final int i) { + runMapping(new MapVoidAction("setMaximum") { + @Override + public void map() { + ((JProgressBar) getSource()).setMaximum(i); + } + }); + } + + /** + * Maps {@code JProgressBar.setMinimum(int)} through queue + */ + public void setMinimum(final int i) { + runMapping(new MapVoidAction("setMinimum") { + @Override + public void map() { + ((JProgressBar) getSource()).setMinimum(i); + } + }); + } + + /** + * Maps {@code JProgressBar.setModel(BoundedRangeModel)} through queue + */ + public void setModel(final BoundedRangeModel boundedRangeModel) { + runMapping(new MapVoidAction("setModel") { + @Override + public void map() { + ((JProgressBar) getSource()).setModel(boundedRangeModel); + } + }); + } + + /** + * Maps {@code JProgressBar.setOrientation(int)} through queue + */ + public void setOrientation(final int i) { + runMapping(new MapVoidAction("setOrientation") { + @Override + public void map() { + ((JProgressBar) getSource()).setOrientation(i); + } + }); + } + + /** + * Maps {@code JProgressBar.setString(String)} through queue + */ + public void setString(final String string) { + runMapping(new MapVoidAction("setString") { + @Override + public void map() { + ((JProgressBar) getSource()).setString(string); + } + }); + } + + /** + * Maps {@code JProgressBar.setStringPainted(boolean)} through queue + */ + public void setStringPainted(final boolean b) { + runMapping(new MapVoidAction("setStringPainted") { + @Override + public void map() { + ((JProgressBar) getSource()).setStringPainted(b); + } + }); + } + + /** + * Maps {@code JProgressBar.setUI(ProgressBarUI)} through queue + */ + public void setUI(final ProgressBarUI progressBarUI) { + runMapping(new MapVoidAction("setUI") { + @Override + public void map() { + ((JProgressBar) getSource()).setUI(progressBarUI); + } + }); + } + + /** + * Maps {@code JProgressBar.setValue(int)} through queue + */ + public void setValue(final int i) { + runMapping(new MapVoidAction("setValue") { + @Override + public void map() { + ((JProgressBar) getSource()).setValue(i); + } + }); + } + + //End of mapping // + //////////////////////////////////////////////////////// + /** + * Interface to define criteria for {@code waitValue(ValueChooser)} + * method. + * + * @see #waitValue(int) + * @deprecated Use waitState(ComponentChooser) instead. + */ + @Deprecated + 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); + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JRadioButtonMenuItemOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JRadioButtonMenuItemOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,212 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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()); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof JRadioButtonMenuItem) { + if (((JRadioButtonMenuItem) comp).getText() != null) { + return (comparator.equals(((JRadioButtonMenuItem) comp).getText(), + label)); + } + } + return false; + } + + @Override + public String getDescription() { + return "JRadioButtonMenuItem with text \"" + label + "\""; + } + + @Override + public String toString() { + return "JRadioButtonMenuItemByLabelFinder{" + "label=" + label + ", comparator=" + comparator + '}'; + } + } + + /** + * 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JRadioButtonOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JRadioButtonOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,273 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JScrollBarOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JScrollBarOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1025 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + public void setTimeouts(Timeouts timeouts) { + this.timeouts = timeouts; + super.setTimeouts(timeouts); + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + 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. + */ + @Deprecated + 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, P 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() { + @Override + public Void launch(Void obj) { + driver.scroll(JScrollBarOperator.this, adj); + return null; + } + + @Override + public String getDescription() { + return "Scrolling"; + } + + @Override + public String toString() { + return "JScrollBarOperator.scrollTo.Action{description = " + getDescription() + '}'; + } + }, "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() { + @Override + public Void launch(Void obj) { + driver.scrollToMinimum(JScrollBarOperator.this, getOrientation()); + return null; + } + + @Override + public String getDescription() { + return "Scrolling"; + } + + @Override + public String toString() { + return "JScrollBarOperator.scrollToMinimum.Action{description = " + getDescription() + '}'; + } + }, "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() { + @Override + public Void launch(Void obj) { + driver.scrollToMaximum(JScrollBarOperator.this, getOrientation()); + return null; + } + + @Override + public String getDescription() { + return "Scrolling"; + } + + @Override + public String toString() { + return "JScrollBarOperator.scrollToMaximum.Action{description = " + getDescription() + '}'; + } + }, "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; + } + + @Override + 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 {@code JScrollBar.addAdjustmentListener(AdjustmentListener)} + * through queue + */ + public void addAdjustmentListener(final AdjustmentListener adjustmentListener) { + runMapping(new MapVoidAction("addAdjustmentListener") { + @Override + public void map() { + ((JScrollBar) getSource()).addAdjustmentListener(adjustmentListener); + } + }); + } + + /** + * Maps {@code JScrollBar.getBlockIncrement()} through queue + */ + public int getBlockIncrement() { + return (runMapping(new MapIntegerAction("getBlockIncrement") { + @Override + public int map() { + return ((JScrollBar) getSource()).getBlockIncrement(); + } + })); + } + + /** + * Maps {@code JScrollBar.getBlockIncrement(int)} through queue + */ + public int getBlockIncrement(final int i) { + return (runMapping(new MapIntegerAction("getBlockIncrement") { + @Override + public int map() { + return ((JScrollBar) getSource()).getBlockIncrement(i); + } + })); + } + + /** + * Maps {@code JScrollBar.getMaximum()} through queue + */ + public int getMaximum() { + return (runMapping(new MapIntegerAction("getMaximum") { + @Override + public int map() { + return ((JScrollBar) getSource()).getMaximum(); + } + })); + } + + /** + * Maps {@code JScrollBar.getMinimum()} through queue + */ + public int getMinimum() { + return (runMapping(new MapIntegerAction("getMinimum") { + @Override + public int map() { + return ((JScrollBar) getSource()).getMinimum(); + } + })); + } + + /** + * Maps {@code JScrollBar.getModel()} through queue + */ + public BoundedRangeModel getModel() { + return (runMapping(new MapAction("getModel") { + @Override + public BoundedRangeModel map() { + return ((JScrollBar) getSource()).getModel(); + } + })); + } + + /** + * Maps {@code JScrollBar.getOrientation()} through queue + */ + public int getOrientation() { + return (runMapping(new MapIntegerAction("getOrientation") { + @Override + public int map() { + return ((JScrollBar) getSource()).getOrientation(); + } + })); + } + + /** + * Maps {@code JScrollBar.getUI()} through queue + */ + public ScrollBarUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public ScrollBarUI map() { + return ((JScrollBar) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JScrollBar.getUnitIncrement()} through queue + */ + public int getUnitIncrement() { + return (runMapping(new MapIntegerAction("getUnitIncrement") { + @Override + public int map() { + return ((JScrollBar) getSource()).getUnitIncrement(); + } + })); + } + + /** + * Maps {@code JScrollBar.getUnitIncrement(int)} through queue + */ + public int getUnitIncrement(final int i) { + return (runMapping(new MapIntegerAction("getUnitIncrement") { + @Override + public int map() { + return ((JScrollBar) getSource()).getUnitIncrement(i); + } + })); + } + + /** + * Maps {@code JScrollBar.getValue()} through queue + */ + public int getValue() { + return (runMapping(new MapIntegerAction("getValue") { + @Override + public int map() { + return ((JScrollBar) getSource()).getValue(); + } + })); + } + + /** + * Maps {@code JScrollBar.getValueIsAdjusting()} through queue + */ + public boolean getValueIsAdjusting() { + return (runMapping(new MapBooleanAction("getValueIsAdjusting") { + @Override + public boolean map() { + return ((JScrollBar) getSource()).getValueIsAdjusting(); + } + })); + } + + /** + * Maps {@code JScrollBar.getVisibleAmount()} through queue + */ + public int getVisibleAmount() { + return (runMapping(new MapIntegerAction("getVisibleAmount") { + @Override + public int map() { + return ((JScrollBar) getSource()).getVisibleAmount(); + } + })); + } + + /** + * Maps {@code JScrollBar.removeAdjustmentListener(AdjustmentListener)} + * through queue + */ + public void removeAdjustmentListener(final AdjustmentListener adjustmentListener) { + runMapping(new MapVoidAction("removeAdjustmentListener") { + @Override + public void map() { + ((JScrollBar) getSource()).removeAdjustmentListener(adjustmentListener); + } + }); + } + + /** + * Maps {@code JScrollBar.setBlockIncrement(int)} through queue + */ + public void setBlockIncrement(final int i) { + runMapping(new MapVoidAction("setBlockIncrement") { + @Override + public void map() { + ((JScrollBar) getSource()).setBlockIncrement(i); + } + }); + } + + /** + * Maps {@code JScrollBar.setMaximum(int)} through queue + */ + public void setMaximum(final int i) { + runMapping(new MapVoidAction("setMaximum") { + @Override + public void map() { + ((JScrollBar) getSource()).setMaximum(i); + } + }); + } + + /** + * Maps {@code JScrollBar.setMinimum(int)} through queue + */ + public void setMinimum(final int i) { + runMapping(new MapVoidAction("setMinimum") { + @Override + public void map() { + ((JScrollBar) getSource()).setMinimum(i); + } + }); + } + + /** + * Maps {@code JScrollBar.setModel(BoundedRangeModel)} through queue + */ + public void setModel(final BoundedRangeModel boundedRangeModel) { + runMapping(new MapVoidAction("setModel") { + @Override + public void map() { + ((JScrollBar) getSource()).setModel(boundedRangeModel); + } + }); + } + + /** + * Maps {@code JScrollBar.setOrientation(int)} through queue + */ + public void setOrientation(final int i) { + runMapping(new MapVoidAction("setOrientation") { + @Override + public void map() { + ((JScrollBar) getSource()).setOrientation(i); + } + }); + } + + /** + * Maps {@code JScrollBar.setUnitIncrement(int)} through queue + */ + public void setUnitIncrement(final int i) { + runMapping(new MapVoidAction("setUnitIncrement") { + @Override + public void map() { + ((JScrollBar) getSource()).setUnitIncrement(i); + } + }); + } + + /** + * Maps {@code JScrollBar.setValue(int)} through queue + */ + public void setValue(final int i) { + runMapping(new MapVoidAction("setValue") { + @Override + public void map() { + ((JScrollBar) getSource()).setValue(i); + } + }); + } + + /** + * Maps {@code JScrollBar.setValueIsAdjusting(boolean)} through queue + */ + public void setValueIsAdjusting(final boolean b) { + runMapping(new MapVoidAction("setValueIsAdjusting") { + @Override + public void map() { + ((JScrollBar) getSource()).setValueIsAdjusting(b); + } + }); + } + + /** + * Maps {@code 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") { + @Override + public void map() { + ((JScrollBar) getSource()).setValues(i, i1, i2, i3); + } + }); + } + + /** + * Maps {@code JScrollBar.setVisibleAmount(int)} through queue + */ + public void setVisibleAmount(final int i) { + runMapping(new MapVoidAction("setVisibleAmount") { + @Override + public void map() { + ((JScrollBar) getSource()).setVisibleAmount(i); + } + }); + } + + //End of mapping // + //////////////////////////////////////////////////////// + private void initOperators() { + if (minButtOperator != null + && maxButtOperator != null) { + return; + } + ComponentChooser chooser = new ComponentChooser() { + @Override + public boolean checkComponent(Component comp) { + return comp instanceof JButton; + } + + @Override + public String getDescription() { + return ""; + } + + @Override + public String toString() { + return "JScrollBarOperator.initOperators.ComponentChooser{description = " + getDescription() + '}'; + } + }; + 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; + } + + @Override + 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); + } + } + + @Override + public int getScrollOrientation() { + return getOrientation(); + } + + @Override + public String getDescription() { + return "Scroll to " + Integer.toString(value) + " value"; + } + + @Override + public String toString() { + return "ValueScrollAdjuster{" + "value=" + value + '}'; + } + } + + private class WaitableChecker

implements ScrollAdjuster { + + Waitable w; + P waitParam; + boolean increase; + boolean reached = false; + + public WaitableChecker(Waitable w, P waitParam, boolean increase, JScrollBarOperator oper) { + this.w = w; + this.waitParam = waitParam; + this.increase = increase; + } + + @Override + public int getScrollDirection() { + if (!reached && w.actionProduced(waitParam) != null) { + reached = true; + } + if (reached) { + return ScrollAdjuster.DO_NOT_TOUCH_SCROLL_DIRECTION; + } else { + return (increase + ? ScrollAdjuster.INCREASE_SCROLL_DIRECTION + : ScrollAdjuster.DECREASE_SCROLL_DIRECTION); + } + } + + @Override + public int getScrollOrientation() { + return getOrientation(); + } + + @Override + public String getDescription() { + return w.getDescription(); + } + + @Override + public String toString() { + return "WaitableChecker{" + "w=" + w + ", waitParam=" + waitParam + ", increase=" + increase + ", reached=" + reached + '}'; + } + } + + private class CheckerAdjustable implements ScrollAdjuster { + + ScrollChecker checker; + JScrollBarOperator oper; + + public CheckerAdjustable(ScrollChecker checker, JScrollBarOperator oper) { + this.checker = checker; + this.oper = oper; + } + + @Override + public int getScrollDirection() { + return checker.getScrollDirection(oper); + } + + @Override + public int getScrollOrientation() { + return getOrientation(); + } + + @Override + public String getDescription() { + return checker.getDescription(); + } + + @Override + public String toString() { + return "CheckerAdjustable{" + "checker=" + checker + ", oper=" + oper + '}'; + } + } + + /** + * 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JScrollPaneOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JScrollPaneOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,961 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void setTimeouts(Timeouts timeouts) { + super.setTimeouts(timeouts); + this.timeouts = timeouts; + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + 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 = runMapping( + new Operator.MapAction("comp.toString()") { + @Override + public String 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 {@code JScrollPane.createHorizontalScrollBar()} through queue + */ + public JScrollBar createHorizontalScrollBar() { + return (runMapping(new MapAction("createHorizontalScrollBar") { + @Override + public JScrollBar map() { + return ((JScrollPane) getSource()).createHorizontalScrollBar(); + } + })); + } + + /** + * Maps {@code JScrollPane.createVerticalScrollBar()} through queue + */ + public JScrollBar createVerticalScrollBar() { + return (runMapping(new MapAction("createVerticalScrollBar") { + @Override + public JScrollBar map() { + return ((JScrollPane) getSource()).createVerticalScrollBar(); + } + })); + } + + /** + * Maps {@code JScrollPane.getColumnHeader()} through queue + */ + public JViewport getColumnHeader() { + return (runMapping(new MapAction("getColumnHeader") { + @Override + public JViewport map() { + return ((JScrollPane) getSource()).getColumnHeader(); + } + })); + } + + /** + * Maps {@code JScrollPane.getCorner(String)} through queue + */ + public Component getCorner(final String string) { + return (runMapping(new MapAction("getCorner") { + @Override + public Component map() { + return ((JScrollPane) getSource()).getCorner(string); + } + })); + } + + /** + * Maps {@code JScrollPane.getHorizontalScrollBar()} through queue + */ + public JScrollBar getHorizontalScrollBar() { + return (runMapping(new MapAction("getHorizontalScrollBar") { + @Override + public JScrollBar map() { + return ((JScrollPane) getSource()).getHorizontalScrollBar(); + } + })); + } + + /** + * Maps {@code JScrollPane.getHorizontalScrollBarPolicy()} through queue + */ + public int getHorizontalScrollBarPolicy() { + return (runMapping(new MapIntegerAction("getHorizontalScrollBarPolicy") { + @Override + public int map() { + return ((JScrollPane) getSource()).getHorizontalScrollBarPolicy(); + } + })); + } + + /** + * Maps {@code JScrollPane.getRowHeader()} through queue + */ + public JViewport getRowHeader() { + return (runMapping(new MapAction("getRowHeader") { + @Override + public JViewport map() { + return ((JScrollPane) getSource()).getRowHeader(); + } + })); + } + + /** + * Maps {@code JScrollPane.getUI()} through queue + */ + public ScrollPaneUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public ScrollPaneUI map() { + return ((JScrollPane) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JScrollPane.getVerticalScrollBar()} through queue + */ + public JScrollBar getVerticalScrollBar() { + return (runMapping(new MapAction("getVerticalScrollBar") { + @Override + public JScrollBar map() { + return ((JScrollPane) getSource()).getVerticalScrollBar(); + } + })); + } + + /** + * Maps {@code JScrollPane.getVerticalScrollBarPolicy()} through queue + */ + public int getVerticalScrollBarPolicy() { + return (runMapping(new MapIntegerAction("getVerticalScrollBarPolicy") { + @Override + public int map() { + return ((JScrollPane) getSource()).getVerticalScrollBarPolicy(); + } + })); + } + + /** + * Maps {@code JScrollPane.getViewport()} through queue + */ + public JViewport getViewport() { + return (runMapping(new MapAction("getViewport") { + @Override + public JViewport map() { + return ((JScrollPane) getSource()).getViewport(); + } + })); + } + + /** + * Maps {@code JScrollPane.getViewportBorder()} through queue + */ + public Border getViewportBorder() { + return (runMapping(new MapAction("getViewportBorder") { + @Override + public Border map() { + return ((JScrollPane) getSource()).getViewportBorder(); + } + })); + } + + /** + * Maps {@code JScrollPane.getViewportBorderBounds()} through queue + */ + public Rectangle getViewportBorderBounds() { + return (runMapping(new MapAction("getViewportBorderBounds") { + @Override + public Rectangle map() { + return ((JScrollPane) getSource()).getViewportBorderBounds(); + } + })); + } + + /** + * Maps {@code JScrollPane.setColumnHeader(JViewport)} through queue + */ + public void setColumnHeader(final JViewport jViewport) { + runMapping(new MapVoidAction("setColumnHeader") { + @Override + public void map() { + ((JScrollPane) getSource()).setColumnHeader(jViewport); + } + }); + } + + /** + * Maps {@code JScrollPane.setColumnHeaderView(Component)} through queue + */ + public void setColumnHeaderView(final Component component) { + runMapping(new MapVoidAction("setColumnHeaderView") { + @Override + public void map() { + ((JScrollPane) getSource()).setColumnHeaderView(component); + } + }); + } + + /** + * Maps {@code JScrollPane.setCorner(String, Component)} through queue + */ + public void setCorner(final String string, final Component component) { + runMapping(new MapVoidAction("setCorner") { + @Override + public void map() { + ((JScrollPane) getSource()).setCorner(string, component); + } + }); + } + + /** + * Maps {@code JScrollPane.setHorizontalScrollBar(JScrollBar)} through queue + */ + public void setHorizontalScrollBar(final JScrollBar jScrollBar) { + runMapping(new MapVoidAction("setHorizontalScrollBar") { + @Override + public void map() { + ((JScrollPane) getSource()).setHorizontalScrollBar(jScrollBar); + } + }); + } + + /** + * Maps {@code JScrollPane.setHorizontalScrollBarPolicy(int)} through queue + */ + public void setHorizontalScrollBarPolicy(final int i) { + runMapping(new MapVoidAction("setHorizontalScrollBarPolicy") { + @Override + public void map() { + ((JScrollPane) getSource()).setHorizontalScrollBarPolicy(i); + } + }); + } + + /** + * Maps {@code JScrollPane.setRowHeader(JViewport)} through queue + */ + public void setRowHeader(final JViewport jViewport) { + runMapping(new MapVoidAction("setRowHeader") { + @Override + public void map() { + ((JScrollPane) getSource()).setRowHeader(jViewport); + } + }); + } + + /** + * Maps {@code JScrollPane.setRowHeaderView(Component)} through queue + */ + public void setRowHeaderView(final Component component) { + runMapping(new MapVoidAction("setRowHeaderView") { + @Override + public void map() { + ((JScrollPane) getSource()).setRowHeaderView(component); + } + }); + } + + /** + * Maps {@code JScrollPane.setUI(ScrollPaneUI)} through queue + */ + public void setUI(final ScrollPaneUI scrollPaneUI) { + runMapping(new MapVoidAction("setUI") { + @Override + public void map() { + ((JScrollPane) getSource()).setUI(scrollPaneUI); + } + }); + } + + /** + * Maps {@code JScrollPane.setVerticalScrollBar(JScrollBar)} through queue + */ + public void setVerticalScrollBar(final JScrollBar jScrollBar) { + runMapping(new MapVoidAction("setVerticalScrollBar") { + @Override + public void map() { + ((JScrollPane) getSource()).setVerticalScrollBar(jScrollBar); + } + }); + } + + /** + * Maps {@code JScrollPane.setVerticalScrollBarPolicy(int)} through queue + */ + public void setVerticalScrollBarPolicy(final int i) { + runMapping(new MapVoidAction("setVerticalScrollBarPolicy") { + @Override + public void map() { + ((JScrollPane) getSource()).setVerticalScrollBarPolicy(i); + } + }); + } + + /** + * Maps {@code JScrollPane.setViewport(JViewport)} through queue + */ + public void setViewport(final JViewport jViewport) { + runMapping(new MapVoidAction("setViewport") { + @Override + public void map() { + ((JScrollPane) getSource()).setViewport(jViewport); + } + }); + } + + /** + * Maps {@code JScrollPane.setViewportBorder(Border)} through queue + */ + public void setViewportBorder(final Border border) { + runMapping(new MapVoidAction("setViewportBorder") { + @Override + public void map() { + ((JScrollPane) getSource()).setViewportBorder(border); + } + }); + } + + /** + * Maps {@code JScrollPane.setViewportView(Component)} through queue + */ + public void setViewportView(final Component component) { + runMapping(new MapVoidAction("setViewportView") { + @Override + 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; + } + + @Override + 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; + } + } + + @Override + public String getDescription() { + return ""; + } + + @Override + public String toString() { + return "ComponentRectChecker{" + "comp=" + comp + ", x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + ", orientation=" + orientation + '}'; + } + } + + /** + * 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JSliderOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JSliderOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,917 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 {@code 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@oracle.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 {@code ScrollDriver} + * registered for this component, So this field is useless. + */ + @Deprecated + 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 {@code ScrollDriver} + * registered for this component, So this field is useless. + */ + @Deprecated + 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 {@code ScrollDriver} + * registered for this component, so value set by this method is ignored. + */ + @Deprecated + 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 {@code ScrollDriver} + * registered for this component, so value returned by this method is + * ignored. + */ + @Deprecated + public int getScrollModel() { + return scrollModel; + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + public void setTimeouts(Timeouts timeouts) { + this.timeouts = timeouts; + super.setTimeouts(timeouts); + } + + @Override + 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() { + @Override + public Void launch(Void obj) { + driver.scroll(JSliderOperator.this, adj); + return null; + } + + @Override + public String getDescription() { + return "Scrolling"; + } + + @Override + public String toString() { + return "JSliderOperator.scrollTo.Action{description = " + getDescription() + '}'; + } + }, "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()); + } + + @Override + 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 {@code JSlider.addChangeListener(ChangeListener)} through queue + */ + public void addChangeListener(final ChangeListener changeListener) { + runMapping(new MapVoidAction("addChangeListener") { + @Override + public void map() { + ((JSlider) getSource()).addChangeListener(changeListener); + } + }); + } + + /** + * Maps {@code JSlider.createStandardLabels(int)} through queue + */ + public Hashtable createStandardLabels(final int i) { + return ((Hashtable) runMapping(new MapAction("createStandardLabels") { + @Override + public Object map() { + return ((JSlider) getSource()).createStandardLabels(i); + } + })); + } + + /** + * Maps {@code JSlider.createStandardLabels(int, int)} through queue + */ + public Hashtable createStandardLabels(final int i, final int i1) { + return ((Hashtable) runMapping(new MapAction("createStandardLabels") { + @Override + public Object map() { + return ((JSlider) getSource()).createStandardLabels(i, i1); + } + })); + } + + /** + * Maps {@code JSlider.getExtent()} through queue + */ + public int getExtent() { + return (runMapping(new MapIntegerAction("getExtent") { + @Override + public int map() { + return ((JSlider) getSource()).getExtent(); + } + })); + } + + /** + * Maps {@code JSlider.getInverted()} through queue + */ + public boolean getInverted() { + return (runMapping(new MapBooleanAction("getInverted") { + @Override + public boolean map() { + return ((JSlider) getSource()).getInverted(); + } + })); + } + + /** + * Maps {@code JSlider.getLabelTable()} through queue + */ + public Dictionary getLabelTable() { + return (runMapping(new MapAction>("getLabelTable") { + @Override + public Dictionary map() { + return ((JSlider) getSource()).getLabelTable(); + } + })); + } + + /** + * Maps {@code JSlider.getMajorTickSpacing()} through queue + */ + public int getMajorTickSpacing() { + return (runMapping(new MapIntegerAction("getMajorTickSpacing") { + @Override + public int map() { + return ((JSlider) getSource()).getMajorTickSpacing(); + } + })); + } + + /** + * Maps {@code JSlider.getMaximum()} through queue + */ + public int getMaximum() { + return (runMapping(new MapIntegerAction("getMaximum") { + @Override + public int map() { + return ((JSlider) getSource()).getMaximum(); + } + })); + } + + /** + * Maps {@code JSlider.getMinimum()} through queue + */ + public int getMinimum() { + return (runMapping(new MapIntegerAction("getMinimum") { + @Override + public int map() { + return ((JSlider) getSource()).getMinimum(); + } + })); + } + + /** + * Maps {@code JSlider.getMinorTickSpacing()} through queue + */ + public int getMinorTickSpacing() { + return (runMapping(new MapIntegerAction("getMinorTickSpacing") { + @Override + public int map() { + return ((JSlider) getSource()).getMinorTickSpacing(); + } + })); + } + + /** + * Maps {@code JSlider.getModel()} through queue + */ + public BoundedRangeModel getModel() { + return (runMapping(new MapAction("getModel") { + @Override + public BoundedRangeModel map() { + return ((JSlider) getSource()).getModel(); + } + })); + } + + /** + * Maps {@code JSlider.getOrientation()} through queue + */ + public int getOrientation() { + return (runMapping(new MapIntegerAction("getOrientation") { + @Override + public int map() { + return ((JSlider) getSource()).getOrientation(); + } + })); + } + + /** + * Maps {@code JSlider.getPaintLabels()} through queue + */ + public boolean getPaintLabels() { + return (runMapping(new MapBooleanAction("getPaintLabels") { + @Override + public boolean map() { + return ((JSlider) getSource()).getPaintLabels(); + } + })); + } + + /** + * Maps {@code JSlider.getPaintTicks()} through queue + */ + public boolean getPaintTicks() { + return (runMapping(new MapBooleanAction("getPaintTicks") { + @Override + public boolean map() { + return ((JSlider) getSource()).getPaintTicks(); + } + })); + } + + /** + * Maps {@code JSlider.getPaintTrack()} through queue + */ + public boolean getPaintTrack() { + return (runMapping(new MapBooleanAction("getPaintTrack") { + @Override + public boolean map() { + return ((JSlider) getSource()).getPaintTrack(); + } + })); + } + + /** + * Maps {@code JSlider.getSnapToTicks()} through queue + */ + public boolean getSnapToTicks() { + return (runMapping(new MapBooleanAction("getSnapToTicks") { + @Override + public boolean map() { + return ((JSlider) getSource()).getSnapToTicks(); + } + })); + } + + /** + * Maps {@code JSlider.getUI()} through queue + */ + public SliderUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public SliderUI map() { + return ((JSlider) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JSlider.getValue()} through queue + */ + public int getValue() { + return (runMapping(new MapIntegerAction("getValue") { + @Override + public int map() { + return ((JSlider) getSource()).getValue(); + } + })); + } + + /** + * Maps {@code JSlider.getValueIsAdjusting()} through queue + */ + public boolean getValueIsAdjusting() { + return (runMapping(new MapBooleanAction("getValueIsAdjusting") { + @Override + public boolean map() { + return ((JSlider) getSource()).getValueIsAdjusting(); + } + })); + } + + /** + * Maps {@code JSlider.removeChangeListener(ChangeListener)} through queue + */ + public void removeChangeListener(final ChangeListener changeListener) { + runMapping(new MapVoidAction("removeChangeListener") { + @Override + public void map() { + ((JSlider) getSource()).removeChangeListener(changeListener); + } + }); + } + + /** + * Maps {@code JSlider.setExtent(int)} through queue + */ + public void setExtent(final int i) { + runMapping(new MapVoidAction("setExtent") { + @Override + public void map() { + ((JSlider) getSource()).setExtent(i); + } + }); + } + + /** + * Maps {@code JSlider.setInverted(boolean)} through queue + */ + public void setInverted(final boolean b) { + runMapping(new MapVoidAction("setInverted") { + @Override + public void map() { + ((JSlider) getSource()).setInverted(b); + } + }); + } + + /** + * Maps {@code JSlider.setLabelTable(Dictionary)} through queue + */ + public void setLabelTable(final Dictionary dictionary) { + runMapping(new MapVoidAction("setLabelTable") { + @Override + public void map() { + ((JSlider) getSource()).setLabelTable(dictionary); + } + }); + } + + /** + * Maps {@code JSlider.setMajorTickSpacing(int)} through queue + */ + public void setMajorTickSpacing(final int i) { + runMapping(new MapVoidAction("setMajorTickSpacing") { + @Override + public void map() { + ((JSlider) getSource()).setMajorTickSpacing(i); + } + }); + } + + /** + * Maps {@code JSlider.setMaximum(int)} through queue + */ + public void setMaximum(final int i) { + runMapping(new MapVoidAction("setMaximum") { + @Override + public void map() { + ((JSlider) getSource()).setMaximum(i); + } + }); + } + + /** + * Maps {@code JSlider.setMinimum(int)} through queue + */ + public void setMinimum(final int i) { + runMapping(new MapVoidAction("setMinimum") { + @Override + public void map() { + ((JSlider) getSource()).setMinimum(i); + } + }); + } + + /** + * Maps {@code JSlider.setMinorTickSpacing(int)} through queue + */ + public void setMinorTickSpacing(final int i) { + runMapping(new MapVoidAction("setMinorTickSpacing") { + @Override + public void map() { + ((JSlider) getSource()).setMinorTickSpacing(i); + } + }); + } + + /** + * Maps {@code JSlider.setModel(BoundedRangeModel)} through queue + */ + public void setModel(final BoundedRangeModel boundedRangeModel) { + runMapping(new MapVoidAction("setModel") { + @Override + public void map() { + ((JSlider) getSource()).setModel(boundedRangeModel); + } + }); + } + + /** + * Maps {@code JSlider.setOrientation(int)} through queue + */ + public void setOrientation(final int i) { + runMapping(new MapVoidAction("setOrientation") { + @Override + public void map() { + ((JSlider) getSource()).setOrientation(i); + } + }); + } + + /** + * Maps {@code JSlider.setPaintLabels(boolean)} through queue + */ + public void setPaintLabels(final boolean b) { + runMapping(new MapVoidAction("setPaintLabels") { + @Override + public void map() { + ((JSlider) getSource()).setPaintLabels(b); + } + }); + } + + /** + * Maps {@code JSlider.setPaintTicks(boolean)} through queue + */ + public void setPaintTicks(final boolean b) { + runMapping(new MapVoidAction("setPaintTicks") { + @Override + public void map() { + ((JSlider) getSource()).setPaintTicks(b); + } + }); + } + + /** + * Maps {@code JSlider.setPaintTrack(boolean)} through queue + */ + public void setPaintTrack(final boolean b) { + runMapping(new MapVoidAction("setPaintTrack") { + @Override + public void map() { + ((JSlider) getSource()).setPaintTrack(b); + } + }); + } + + /** + * Maps {@code JSlider.setSnapToTicks(boolean)} through queue + */ + public void setSnapToTicks(final boolean b) { + runMapping(new MapVoidAction("setSnapToTicks") { + @Override + public void map() { + ((JSlider) getSource()).setSnapToTicks(b); + } + }); + } + + /** + * Maps {@code JSlider.setUI(SliderUI)} through queue + */ + public void setUI(final SliderUI sliderUI) { + runMapping(new MapVoidAction("setUI") { + @Override + public void map() { + ((JSlider) getSource()).setUI(sliderUI); + } + }); + } + + /** + * Maps {@code JSlider.setValue(int)} through queue + */ + public void setValue(final int i) { + runMapping(new MapVoidAction("setValue") { + @Override + public void map() { + ((JSlider) getSource()).setValue(i); + } + }); + } + + /** + * Maps {@code JSlider.setValueIsAdjusting(boolean)} through queue + */ + public void setValueIsAdjusting(final boolean b) { + runMapping(new MapVoidAction("setValueIsAdjusting") { + @Override + 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; + } + + @Override + 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); + } + } + + @Override + public int getScrollOrientation() { + return getOrientation(); + } + + @Override + public String getDescription() { + return "Scroll to " + Integer.toString(value) + " value"; + } + + @Override + public String toString() { + return "ValueScrollAdjuster{" + "value=" + value + '}'; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JSpinnerOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JSpinnerOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1296 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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 {@code javax.swing.JSpinner} component + *
+ * + * @see NumberSpinnerOperator + * @see ListSpinnerOperator + * @see DateSpinnerOperator + * + * @author Alexandre Iline (alexandre.iline@oracle.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 + * {@code 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); + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + public void setTimeouts(Timeouts timeouts) { + this.timeouts = timeouts; + super.setTimeouts(timeouts); + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + /** + * Returns an instance of {@code NumberSpinnerOperator} operator, the + * operator used for {@code JSpinner} having + * {@code SpinnerNumberModel} model. + * + * @return a {@code NumberSpinnerOperator} created for the same + * {@code JSpinner} as this operator. + * @throws SpinnerModelException if an operator's model is not an instance + * of {@code SpinnerNumberModel} + */ + public NumberSpinnerOperator getNumberSpinner() { + return new NumberSpinnerOperator(this); + } + + /** + * Returns an instance of {@code ListSpinnerOperator} operator, the + * operator used for {@code JSpinner} having + * {@code SpinnerListModel} model. + * + * @return a {@code ListSpinnerOperator} created for the same + * {@code JSpinner} as this operator. + * @throws SpinnerModelException if an operator's model is not an instance + * of {@code SpinnerListModel} + */ + public ListSpinnerOperator getListSpinner() { + return new ListSpinnerOperator(this); + } + + /** + * Returns an instance of {@code DateSpinnerOperator} operator, the + * operator used for {@code JSpinner} having + * {@code SpinnerDateModel} model. + * + * @return a {@code DateSpinnerOperator} created for the same + * {@code JSpinner} as this operator. + * @throws SpinnerModelException if an operator's model is not an instance + * of {@code SpinnerDateModel} + */ + public DateSpinnerOperator getDateSpinner() { + return new DateSpinnerOperator(this); + } + + /** + * Scrolls to reach a condition specified by {@code ScrollAdjuster} + * + * @param adj scrolling criteria. + */ + public void scrollTo(final ScrollAdjuster adj) { + produceTimeRestricted(new Action() { + @Override + public Void launch(Void obj) { + driver.scroll(JSpinnerOperator.this, adj); + return null; + } + + @Override + public String getDescription() { + return "Scrolling"; + } + + @Override + public String toString() { + return "JSpinnerOperator.scrollTo.Action{description = " + getDescription() + '}'; + } + }, "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() { + @Override + public Void launch(Void obj) { + driver.scrollToMaximum(JSpinnerOperator.this, SwingConstants.VERTICAL); + return null; + } + + @Override + public String getDescription() { + return "Scrolling"; + } + + @Override + public String toString() { + return "JSpinnerOperator.scrollToMaximum.Action{description = " + getDescription() + '}'; + } + }, "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() { + @Override + public Void launch(Void obj) { + driver.scrollToMinimum(JSpinnerOperator.this, SwingConstants.VERTICAL); + return null; + } + + @Override + public String getDescription() { + return "Scrolling"; + } + + @Override + public String toString() { + return "JSpinnerOperator.scrollToMinimum.Action{description = " + getDescription() + '}'; + } + }, "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 + * {@code 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 + * {@code ScrollAdjuster.*_SCROLL_DIRECTION} fields. + */ + public void scrollToString(String pattern, StringComparator comparator, int direction) { + scrollTo(new ToStringScrollAdjuster(this, pattern, comparator, direction)); + } + + /** + * Scrolls to matching of {@code getValue().toString()} with the + * pattern. Uses {@code StringComparator} assigned to the operator. + * + * @param pattern a pattern to compare with + * @param direction a scrolling direction - one of + * {@code 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: {@code javax.swing.SpinnerDateModel}, + * {@code javax.swing.SpinnerListModel}, + * {@code 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: {@code javax.swing.SpinnerDateModel}, + * {@code javax.swing.SpinnerListModel}, + * {@code 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; + } + } + + @Override + public Hashtable getDump() { + Hashtable result = super.getDump(); + result.put(VALUE_DPROP, ((JSpinner) getSource()).getValue().toString()); + return result; + } + + //////////////////////////////////////////////////////// + //Mapping // + /** + * Maps {@code JSpinner.getValue()} through queue + */ + public Object getValue() { + return (runMapping(new MapAction("getValue") { + @Override + public Object map() { + return ((JSpinner) getSource()).getValue(); + } + })); + } + + /** + * Maps {@code JSpinner.setValue(Object)} through queue + */ + public void setValue(final Object object) { + runMapping(new MapVoidAction("setValue") { + @Override + public void map() { + ((JSpinner) getSource()).setValue(object); + } + }); + } + + /** + * Maps {@code JSpinner.getUI()} through queue + */ + public SpinnerUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public SpinnerUI map() { + return ((JSpinner) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JSpinner.setUI(SpinnerUI)} through queue + */ + public void setUI(final SpinnerUI spinnerUI) { + runMapping(new MapVoidAction("setUI") { + @Override + public void map() { + ((JSpinner) getSource()).setUI(spinnerUI); + } + }); + } + + /** + * Maps {@code JSpinner.setModel(SpinnerModel)} through queue + */ + public void setModel(final SpinnerModel spinnerModel) { + runMapping(new MapVoidAction("setModel") { + @Override + public void map() { + ((JSpinner) getSource()).setModel(spinnerModel); + } + }); + } + + /** + * Maps {@code JSpinner.getModel()} through queue + */ + public SpinnerModel getModel() { + return (runMapping(new MapAction("getModel") { + @Override + public SpinnerModel map() { + return ((JSpinner) getSource()).getModel(); + } + })); + } + + /** + * Maps {@code JSpinner.getNextValue()} through queue + */ + public Object getNextValue() { + return (runMapping(new MapAction("getNextValue") { + @Override + public Object map() { + return ((JSpinner) getSource()).getNextValue(); + } + })); + } + + /** + * Maps {@code JSpinner.addChangeListener(ChangeListener)} through queue + */ + public void addChangeListener(final ChangeListener changeListener) { + runMapping(new MapVoidAction("addChangeListener") { + @Override + public void map() { + ((JSpinner) getSource()).addChangeListener(changeListener); + } + }); + } + + /** + * Maps {@code JSpinner.removeChangeListener(ChangeListener)} through queue + */ + public void removeChangeListener(final ChangeListener changeListener) { + runMapping(new MapVoidAction("removeChangeListener") { + @Override + public void map() { + ((JSpinner) getSource()).removeChangeListener(changeListener); + } + }); + } + + /** + * Maps {@code JSpinner.getChangeListeners()} through queue + */ + public ChangeListener[] getChangeListeners() { + return ((ChangeListener[]) runMapping(new MapAction("getChangeListeners") { + @Override + public Object map() { + return ((JSpinner) getSource()).getChangeListeners(); + } + })); + } + + /** + * Maps {@code JSpinner.getPreviousValue()} through queue + */ + public Object getPreviousValue() { + return (runMapping(new MapAction("getPreviousValue") { + @Override + public Object map() { + return ((JSpinner) getSource()).getPreviousValue(); + } + })); + } + + /** + * Maps {@code JSpinner.setEditor(JComponent)} through queue + */ + public void setEditor(final JComponent jComponent) { + runMapping(new MapVoidAction("setEditor") { + @Override + public void map() { + ((JSpinner) getSource()).setEditor(jComponent); + } + }); + } + + /** + * Maps {@code JSpinner.getEditor()} through queue + */ + public JComponent getEditor() { + return (runMapping(new MapAction("getEditor") { + @Override + public JComponent map() { + return ((JSpinner) getSource()).getEditor(); + } + })); + } + + /** + * Maps {@code JSpinner.commitEdit()} through queue + */ + public void commitEdit() { + runMapping(new MapVoidAction("commitEdit") { + @Override + 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()); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof JSpinner) { + if (((JSpinner) comp).getValue() != null) { + return (comparator.equals(((JSpinner) comp).getValue().toString(), + label)); + } + } + return false; + } + + @Override + public String getDescription() { + return "JSpinner with text \"" + label + "\""; + } + + @Override + public String toString() { + return "JSpinnerByTextFinder{" + "label=" + label + ", comparator=" + comparator + '}'; + } + } + + /** + * 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 {@code ScrollAdjuster} to be used for {@code JSpinner} + * component having {@code SpinnerNumberModel} model. + * + * @see NumberSpinnerOperator + */ + public static class NumberScrollAdjuster implements ScrollAdjuster { + + SpinnerNumberModel model; + double value; + + /** + * Constructs a {@code 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 {@code 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()); + } + + @Override + 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; + } + } + + @Override + public int getScrollOrientation() { + return SwingConstants.VERTICAL; + } + + @Override + public String getDescription() { + return "Spin to " + value + " value"; + } + + @Override + public String toString() { + return "NumberScrollAdjuster{" + "model=" + model + ", value=" + value + '}'; + } + } + + /** + * A {@code ScrollAdjuster} to be used for {@code JSpinner} + * component having {@code 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 {@code 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 {@code 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; + } + + @Override + 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; + } + } + + @Override + public int getScrollOrientation() { + return SwingConstants.VERTICAL; + } + + @Override + public String getDescription() { + return "Spin to " + Integer.toString(itemIndex) + "'th item"; + } + + @Override + public String toString() { + return "ListScrollAdjuster{" + "model=" + model + ", itemIndex=" + itemIndex + ", elements=" + elements + '}'; + } + } + + /** + * A {@code ScrollAdjuster} to be used for {@code JSpinner} + * component having {@code SpinnerDateModel} model. + * + * @see DateSpinnerOperator + */ + public static class DateScrollAdjuster implements ScrollAdjuster { + + Date date; + SpinnerDateModel model; + + /** + * Constructs a {@code 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(); + } + + @Override + 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; + } + } + + @Override + public int getScrollOrientation() { + return SwingConstants.VERTICAL; + } + + @Override + public String getDescription() { + return "Spin to " + date.toString() + " date"; + } + + @Override + public String toString() { + return "DateScrollAdjuster{" + "date=" + date + ", model=" + model + '}'; + } + } + + /** + * Abstract class for a scrolling of a spinner having unknown model type. A + * subclass needs to override {@code reached(Object)} method to specify a + * criteria of successful scrolling. + */ + public abstract static class ObjectScrollAdjuster implements ScrollAdjuster { + + SpinnerModel model; + int direction; + + /** + * Constructs a {@code ObjectScrollAdjuster} object. + * + * @param oper an operator to work with. + * @param direction a scrolling direction - one of + * {@code ScrollAdjuster.*_SCROLL_DIRECTION} fields. + */ + public ObjectScrollAdjuster(JSpinnerOperator oper, int direction) { + this.direction = direction; + model = oper.getModel(); + } + + @Override + public int getScrollDirection() { + if (reached(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 reached(Object curvalue); + + @Override + 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 {@code ExactScrollAdjuster} object. + * + * @param oper an operator to work with. + * @param direction a scrolling direction - one of + * {@code ScrollAdjuster.*_SCROLL_DIRECTION} fields. + */ + public ExactScrollAdjuster(JSpinnerOperator oper, Object obj, int direction) { + super(oper, direction); + this.obj = obj; + } + + @Override + public boolean reached(Object curvalue) { + return curvalue != null && curvalue.equals(obj); + } + + @Override + public String getDescription() { + return "Spin to " + obj.toString() + " value"; + } + + @Override + public String toString() { + return "ExactScrollAdjuster{" + "obj=" + obj + '}'; + } + + @Override + 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 {@code 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 + * {@code 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 {@code ToStringScrollAdjuster} object. Uses + * {@code 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 + * {@code ScrollAdjuster.*_SCROLL_DIRECTION} fields. + */ + public ToStringScrollAdjuster(JSpinnerOperator oper, String pattern, int direction) { + this(oper, pattern, oper.getComparator(), direction); + } + + @Override + public boolean reached(Object curvalue) { + return curvalue != null && comparator.equals(curvalue.toString(), pattern); + } + + @Override + public String getDescription() { + return "Spin to \"" + pattern + "\" value"; + } + + @Override + public String toString() { + return "ToStringScrollAdjuster{" + "pattern=" + pattern + ", comparator=" + comparator + '}'; + } + + @Override + public int getScrollOrientation() { + return SwingConstants.VERTICAL; + } + } + + /** + * Provides some specific functionality for {@code JSpinner} components + * having {@code SpinnerNumberModel} model. Constructor of this object + * is private - it cannot be received only from another JSpinnerOperator + * instance. + * + * @see #getNumberSpinner + */ + public static 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 {@code JSpinner} components + * having {@code SpinnerListModel} model. Constructor of this object is + * private - it cannot be received only from another JSpinnerOperator + * instance. + * + * @see #getListSpinner + */ + public static 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 {@code 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 {@code toString()} matching + * a specified pattern. Uses a {@code 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 {@code 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 {@code getValue().toString()} match a specified + * pattern. Uses a {@code StringComparator} assigned to the + * operator. + * + * @param pattern a string pattern + */ + public void scrollToString(String pattern) { + scrollToString(pattern, getComparator()); + } + } + + /** + * Provides some specific functionality for {@code JSpinner} components + * having {@code SpinnerDateModel} model. Constructor of this object is + * private - it cannot be received only from another JSpinnerOperator + * instance. + * + * @see #getDateSpinner + */ + public static 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 { + + private static final long serialVersionUID = 42L; + + /** + * Constructs a {@code SpinnerModelException} object. + * + * @param message error message. + * @param comp a spinner which model cased the exception. + */ + public SpinnerModelException(String message, Component comp) { + super(message, comp); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JSplitPaneOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JSplitPaneOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,914 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + 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); + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + 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() { + @Override + public boolean checkComponent(Component comp) { + return comp instanceof BasicSplitPaneDivider; + } + + @Override + public String getDescription() { + return ""; + } + + @Override + public String toString() { + return "JSplitPaneOperator.findDivider.ComponentChooser{description = " + getDescription() + '}'; + } + })); + } + + /** + * 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() { + @Override + public Void launch(Void obj) { + driver.scroll(JSplitPaneOperator.this, adj); + return null; + } + + @Override + public String getDescription() { + return "Moving a divider"; + } + + @Override + public String toString() { + return "JSplitPaneOperator.scrollTo.Action{description = " + getDescription() + '}'; + } + }, "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() { + @Override + public Void launch(Void obj) { + driver.scrollToMinimum(JSplitPaneOperator.this, getOrientation()); + return null; + } + + @Override + public String getDescription() { + return "Scrolling"; + } + + @Override + public String toString() { + return "JSplitPaneOperator.moveToMinimum.Action{description = " + getDescription() + '}'; + } + }, "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() { + @Override + public Void launch(Void obj) { + driver.scrollToMaximum(JSplitPaneOperator.this, getOrientation()); + return null; + } + + @Override + public String getDescription() { + return "Scrolling"; + } + + @Override + public String toString() { + return "JSplitPaneOperator.moveToMaximum.Action{description = " + getDescription() + '}'; + } + }, "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); + } + + @Override + 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 {@code JSplitPane.getBottomComponent()} through queue + */ + public Component getBottomComponent() { + return (runMapping(new MapAction("getBottomComponent") { + @Override + public Component map() { + return ((JSplitPane) getSource()).getBottomComponent(); + } + })); + } + + /** + * Maps {@code JSplitPane.getDividerLocation()} through queue + */ + public int getDividerLocation() { + return (runMapping(new MapIntegerAction("getDividerLocation") { + @Override + public int map() { + return ((JSplitPane) getSource()).getDividerLocation(); + } + })); + } + + /** + * Maps {@code JSplitPane.getDividerSize()} through queue + */ + public int getDividerSize() { + return (runMapping(new MapIntegerAction("getDividerSize") { + @Override + public int map() { + return ((JSplitPane) getSource()).getDividerSize(); + } + })); + } + + /** + * Maps {@code JSplitPane.getLastDividerLocation()} through queue + */ + public int getLastDividerLocation() { + return (runMapping(new MapIntegerAction("getLastDividerLocation") { + @Override + public int map() { + return ((JSplitPane) getSource()).getLastDividerLocation(); + } + })); + } + + /** + * Maps {@code JSplitPane.getLeftComponent()} through queue + */ + public Component getLeftComponent() { + return (runMapping(new MapAction("getLeftComponent") { + @Override + public Component map() { + return ((JSplitPane) getSource()).getLeftComponent(); + } + })); + } + + /** + * Maps {@code JSplitPane.getMaximumDividerLocation()} through queue + */ + public int getMaximumDividerLocation() { + return (runMapping(new MapIntegerAction("getMaximumDividerLocation") { + @Override + public int map() { + return ((JSplitPane) getSource()).getMaximumDividerLocation(); + } + })); + } + + /** + * Maps {@code JSplitPane.getMinimumDividerLocation()} through queue + */ + public int getMinimumDividerLocation() { + return (runMapping(new MapIntegerAction("getMinimumDividerLocation") { + @Override + public int map() { + return ((JSplitPane) getSource()).getMinimumDividerLocation(); + } + })); + } + + /** + * Maps {@code JSplitPane.getOrientation()} through queue + */ + public int getOrientation() { + return (runMapping(new MapIntegerAction("getOrientation") { + @Override + public int map() { + return ((JSplitPane) getSource()).getOrientation(); + } + })); + } + + /** + * Maps {@code JSplitPane.getRightComponent()} through queue + */ + public Component getRightComponent() { + return (runMapping(new MapAction("getRightComponent") { + @Override + public Component map() { + return ((JSplitPane) getSource()).getRightComponent(); + } + })); + } + + /** + * Maps {@code JSplitPane.getTopComponent()} through queue + */ + public Component getTopComponent() { + return (runMapping(new MapAction("getTopComponent") { + @Override + public Component map() { + return ((JSplitPane) getSource()).getTopComponent(); + } + })); + } + + /** + * Maps {@code JSplitPane.getUI()} through queue + */ + public SplitPaneUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public SplitPaneUI map() { + return ((JSplitPane) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JSplitPane.isContinuousLayout()} through queue + */ + public boolean isContinuousLayout() { + return (runMapping(new MapBooleanAction("isContinuousLayout") { + @Override + public boolean map() { + return ((JSplitPane) getSource()).isContinuousLayout(); + } + })); + } + + /** + * Maps {@code JSplitPane.isOneTouchExpandable()} through queue + */ + public boolean isOneTouchExpandable() { + return (runMapping(new MapBooleanAction("isOneTouchExpandable") { + @Override + public boolean map() { + return ((JSplitPane) getSource()).isOneTouchExpandable(); + } + })); + } + + /** + * Maps {@code JSplitPane.resetToPreferredSizes()} through queue + */ + public void resetToPreferredSizes() { + runMapping(new MapVoidAction("resetToPreferredSizes") { + @Override + public void map() { + ((JSplitPane) getSource()).resetToPreferredSizes(); + } + }); + } + + /** + * Maps {@code JSplitPane.setBottomComponent(Component)} through queue + */ + public void setBottomComponent(final Component component) { + runMapping(new MapVoidAction("setBottomComponent") { + @Override + public void map() { + ((JSplitPane) getSource()).setBottomComponent(component); + } + }); + } + + /** + * Maps {@code JSplitPane.setContinuousLayout(boolean)} through queue + */ + public void setContinuousLayout(final boolean b) { + runMapping(new MapVoidAction("setContinuousLayout") { + @Override + public void map() { + ((JSplitPane) getSource()).setContinuousLayout(b); + } + }); + } + + /** + * Maps {@code JSplitPane.setDividerLocation(double)} through queue + */ + public void setDividerLocation(final double d) { + runMapping(new MapVoidAction("setDividerLocation") { + @Override + public void map() { + ((JSplitPane) getSource()).setDividerLocation(d); + } + }); + } + + /** + * Maps {@code JSplitPane.setDividerLocation(int)} through queue + */ + public void setDividerLocation(final int i) { + runMapping(new MapVoidAction("setDividerLocation") { + @Override + public void map() { + ((JSplitPane) getSource()).setDividerLocation(i); + } + }); + } + + /** + * Maps {@code JSplitPane.setDividerSize(int)} through queue + */ + public void setDividerSize(final int i) { + runMapping(new MapVoidAction("setDividerSize") { + @Override + public void map() { + ((JSplitPane) getSource()).setDividerSize(i); + } + }); + } + + /** + * Maps {@code JSplitPane.setLastDividerLocation(int)} through queue + */ + public void setLastDividerLocation(final int i) { + runMapping(new MapVoidAction("setLastDividerLocation") { + @Override + public void map() { + ((JSplitPane) getSource()).setLastDividerLocation(i); + } + }); + } + + /** + * Maps {@code JSplitPane.setLeftComponent(Component)} through queue + */ + public void setLeftComponent(final Component component) { + runMapping(new MapVoidAction("setLeftComponent") { + @Override + public void map() { + ((JSplitPane) getSource()).setLeftComponent(component); + } + }); + } + + /** + * Maps {@code JSplitPane.setOneTouchExpandable(boolean)} through queue + */ + public void setOneTouchExpandable(final boolean b) { + runMapping(new MapVoidAction("setOneTouchExpandable") { + @Override + public void map() { + ((JSplitPane) getSource()).setOneTouchExpandable(b); + } + }); + } + + /** + * Maps {@code JSplitPane.setOrientation(int)} through queue + */ + public void setOrientation(final int i) { + runMapping(new MapVoidAction("setOrientation") { + @Override + public void map() { + ((JSplitPane) getSource()).setOrientation(i); + } + }); + } + + /** + * Maps {@code JSplitPane.setRightComponent(Component)} through queue + */ + public void setRightComponent(final Component component) { + runMapping(new MapVoidAction("setRightComponent") { + @Override + public void map() { + ((JSplitPane) getSource()).setRightComponent(component); + } + }); + } + + /** + * Maps {@code JSplitPane.setTopComponent(Component)} through queue + */ + public void setTopComponent(final Component component) { + runMapping(new MapVoidAction("setTopComponent") { + @Override + public void map() { + ((JSplitPane) getSource()).setTopComponent(component); + } + }); + } + + /** + * Maps {@code JSplitPane.setUI(SplitPaneUI)} through queue + */ + public void setUI(final SplitPaneUI splitPaneUI) { + runMapping(new MapVoidAction("setUI") { + @Override + 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; + } + + @Override + 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); + } + } + + @Override + public int getScrollOrientation() { + return getOrientation(); + } + + @Override + public String getDescription() { + return "Scroll to " + Integer.toString(value) + " value"; + } + + @Override + public String toString() { + return "ValueScrollAdjuster{" + "value=" + value + '}'; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JTabbedPaneOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JTabbedPaneOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1168 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void setOutput(TestOut output) { + super.setOutput(output.createErrorOutput()); + this.output = output; + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + 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) + */ + @Deprecated + 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) + */ + @Deprecated + 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) + */ + @Deprecated + 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. + */ + @Deprecated + 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() { + @Override + public boolean checkComponent(Component comp) { + return findPage(chooser) > -1; + } + + @Override + public String getDescription() { + return "Tabbed with " + chooser.getDescription() + " page."; + } + + @Override + public String toString() { + return "JTabbedPaneOperator.waitPage.Action{description = " + getDescription() + '}'; + } + }); + 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() { + @Override + public boolean checkComponent(Component comp) { + return getSelectedIndex() == pageIndex; + } + + @Override + public String getDescription() { + return Integer.toString(pageIndex) + "'th page has been selected"; + } + + @Override + public String toString() { + return "JTabbedPaneOperator.waitSelected.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + /** + * 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)); + } + + @Override + 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 {@code JTabbedPane.addChangeListener(ChangeListener)} through queue + */ + public void addChangeListener(final ChangeListener changeListener) { + runMapping(new MapVoidAction("addChangeListener") { + @Override + public void map() { + ((JTabbedPane) getSource()).addChangeListener(changeListener); + } + }); + } + + /** + * Maps {@code JTabbedPane.addTab(String, Component)} through queue + */ + public void addTab(final String string, final Component component) { + runMapping(new MapVoidAction("addTab") { + @Override + public void map() { + ((JTabbedPane) getSource()).addTab(string, component); + } + }); + } + + /** + * Maps {@code JTabbedPane.addTab(String, Icon, Component)} through queue + */ + public void addTab(final String string, final Icon icon, final Component component) { + runMapping(new MapVoidAction("addTab") { + @Override + public void map() { + ((JTabbedPane) getSource()).addTab(string, icon, component); + } + }); + } + + /** + * Maps {@code 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") { + @Override + public void map() { + ((JTabbedPane) getSource()).addTab(string, icon, component, string1); + } + }); + } + + /** + * Maps {@code JTabbedPane.getBackgroundAt(int)} through queue + */ + public Color getBackgroundAt(final int i) { + return (runMapping(new MapAction("getBackgroundAt") { + @Override + public Color map() { + return ((JTabbedPane) getSource()).getBackgroundAt(i); + } + })); + } + + /** + * Maps {@code JTabbedPane.getBoundsAt(int)} through queue + */ + public Rectangle getBoundsAt(final int i) { + return (runMapping(new MapAction("getBoundsAt") { + @Override + public Rectangle map() { + return ((JTabbedPane) getSource()).getBoundsAt(i); + } + })); + } + + /** + * Maps {@code JTabbedPane.getComponentAt(int)} through queue + */ + public Component getComponentAt(final int i) { + return (runMapping(new MapAction("getComponentAt") { + @Override + public Component map() { + return ((JTabbedPane) getSource()).getComponentAt(i); + } + })); + } + + /** + * Maps {@code JTabbedPane.getDisabledIconAt(int)} through queue + */ + public Icon getDisabledIconAt(final int i) { + return (runMapping(new MapAction("getDisabledIconAt") { + @Override + public Icon map() { + return ((JTabbedPane) getSource()).getDisabledIconAt(i); + } + })); + } + + /** + * Maps {@code JTabbedPane.getForegroundAt(int)} through queue + */ + public Color getForegroundAt(final int i) { + return (runMapping(new MapAction("getForegroundAt") { + @Override + public Color map() { + return ((JTabbedPane) getSource()).getForegroundAt(i); + } + })); + } + + /** + * Maps {@code JTabbedPane.getIconAt(int)} through queue + */ + public Icon getIconAt(final int i) { + return (runMapping(new MapAction("getIconAt") { + @Override + public Icon map() { + return ((JTabbedPane) getSource()).getIconAt(i); + } + })); + } + + /** + * Maps {@code JTabbedPane.getModel()} through queue + */ + public SingleSelectionModel getModel() { + return (runMapping(new MapAction("getModel") { + @Override + public SingleSelectionModel map() { + return ((JTabbedPane) getSource()).getModel(); + } + })); + } + + /** + * Maps {@code JTabbedPane.getSelectedComponent()} through queue + */ + public Component getSelectedComponent() { + return (runMapping(new MapAction("getSelectedComponent") { + @Override + public Component map() { + return ((JTabbedPane) getSource()).getSelectedComponent(); + } + })); + } + + /** + * Maps {@code JTabbedPane.getSelectedIndex()} through queue + */ + public int getSelectedIndex() { + return (runMapping(new MapIntegerAction("getSelectedIndex") { + @Override + public int map() { + return ((JTabbedPane) getSource()).getSelectedIndex(); + } + })); + } + + /** + * Maps {@code JTabbedPane.getTabCount()} through queue + */ + public int getTabCount() { + return (runMapping(new MapIntegerAction("getTabCount") { + @Override + public int map() { + return ((JTabbedPane) getSource()).getTabCount(); + } + })); + } + + /** + * Maps {@code JTabbedPane.getTabPlacement()} through queue + */ + public int getTabPlacement() { + return (runMapping(new MapIntegerAction("getTabPlacement") { + @Override + public int map() { + return ((JTabbedPane) getSource()).getTabPlacement(); + } + })); + } + + /** + * Maps {@code JTabbedPane.getTabRunCount()} through queue + */ + public int getTabRunCount() { + return (runMapping(new MapIntegerAction("getTabRunCount") { + @Override + public int map() { + return ((JTabbedPane) getSource()).getTabRunCount(); + } + })); + } + + /** + * Maps {@code JTabbedPane.getTitleAt(int)} through queue + */ + public String getTitleAt(final int i) { + return (runMapping(new MapAction("getTitleAt") { + @Override + public String map() { + return ((JTabbedPane) getSource()).getTitleAt(i); + } + })); + } + + /** + * Maps {@code JTabbedPane.getUI()} through queue + */ + public TabbedPaneUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public TabbedPaneUI map() { + return ((JTabbedPane) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JTabbedPane.indexOfComponent(Component)} through queue + */ + public int indexOfComponent(final Component component) { + return (runMapping(new MapIntegerAction("indexOfComponent") { + @Override + public int map() { + return ((JTabbedPane) getSource()).indexOfComponent(component); + } + })); + } + + /** + * Maps {@code JTabbedPane.indexOfTab(String)} through queue + */ + public int indexOfTab(final String string) { + return (runMapping(new MapIntegerAction("indexOfTab") { + @Override + public int map() { + return ((JTabbedPane) getSource()).indexOfTab(string); + } + })); + } + + /** + * Maps {@code JTabbedPane.indexOfTab(Icon)} through queue + */ + public int indexOfTab(final Icon icon) { + return (runMapping(new MapIntegerAction("indexOfTab") { + @Override + public int map() { + return ((JTabbedPane) getSource()).indexOfTab(icon); + } + })); + } + + /** + * Maps + * {@code 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") { + @Override + public void map() { + ((JTabbedPane) getSource()).insertTab(string, icon, component, string1, i); + } + }); + } + + /** + * Maps {@code JTabbedPane.isEnabledAt(int)} through queue + */ + public boolean isEnabledAt(final int i) { + return (runMapping(new MapBooleanAction("isEnabledAt") { + @Override + public boolean map() { + return ((JTabbedPane) getSource()).isEnabledAt(i); + } + })); + } + + /** + * Maps {@code JTabbedPane.removeChangeListener(ChangeListener)} + * through queue + */ + public void removeChangeListener(final ChangeListener changeListener) { + runMapping(new MapVoidAction("removeChangeListener") { + @Override + public void map() { + ((JTabbedPane) getSource()).removeChangeListener(changeListener); + } + }); + } + + /** + * Maps {@code JTabbedPane.removeTabAt(int)} through queue + */ + public void removeTabAt(final int i) { + runMapping(new MapVoidAction("removeTabAt") { + @Override + public void map() { + ((JTabbedPane) getSource()).removeTabAt(i); + } + }); + } + + /** + * Maps {@code JTabbedPane.setBackgroundAt(int, Color)} through queue + */ + public void setBackgroundAt(final int i, final Color color) { + runMapping(new MapVoidAction("setBackgroundAt") { + @Override + public void map() { + ((JTabbedPane) getSource()).setBackgroundAt(i, color); + } + }); + } + + /** + * Maps {@code JTabbedPane.setComponentAt(int, Component)} through queue + */ + public void setComponentAt(final int i, final Component component) { + runMapping(new MapVoidAction("setComponentAt") { + @Override + public void map() { + ((JTabbedPane) getSource()).setComponentAt(i, component); + } + }); + } + + /** + * Maps {@code JTabbedPane.setDisabledIconAt(int, Icon)} through queue + */ + public void setDisabledIconAt(final int i, final Icon icon) { + runMapping(new MapVoidAction("setDisabledIconAt") { + @Override + public void map() { + ((JTabbedPane) getSource()).setDisabledIconAt(i, icon); + } + }); + } + + /** + * Maps {@code JTabbedPane.setEnabledAt(int, boolean)} through queue + */ + public void setEnabledAt(final int i, final boolean b) { + runMapping(new MapVoidAction("setEnabledAt") { + @Override + public void map() { + ((JTabbedPane) getSource()).setEnabledAt(i, b); + } + }); + } + + /** + * Maps {@code JTabbedPane.setForegroundAt(int, Color)} through queue + */ + public void setForegroundAt(final int i, final Color color) { + runMapping(new MapVoidAction("setForegroundAt") { + @Override + public void map() { + ((JTabbedPane) getSource()).setForegroundAt(i, color); + } + }); + } + + /** + * Maps {@code JTabbedPane.setIconAt(int, Icon)} through queue + */ + public void setIconAt(final int i, final Icon icon) { + runMapping(new MapVoidAction("setIconAt") { + @Override + public void map() { + ((JTabbedPane) getSource()).setIconAt(i, icon); + } + }); + } + + /** + * Maps {@code JTabbedPane.setModel(SingleSelectionModel)} through queue + */ + public void setModel(final SingleSelectionModel singleSelectionModel) { + runMapping(new MapVoidAction("setModel") { + @Override + public void map() { + ((JTabbedPane) getSource()).setModel(singleSelectionModel); + } + }); + } + + /** + * Maps {@code JTabbedPane.setSelectedComponent(Component)} through queue + */ + public void setSelectedComponent(final Component component) { + runMapping(new MapVoidAction("setSelectedComponent") { + @Override + public void map() { + ((JTabbedPane) getSource()).setSelectedComponent(component); + } + }); + } + + /** + * Maps {@code JTabbedPane.setSelectedIndex(int)} through queue + */ + public void setSelectedIndex(final int i) { + runMapping(new MapVoidAction("setSelectedIndex") { + @Override + public void map() { + ((JTabbedPane) getSource()).setSelectedIndex(i); + } + }); + } + + /** + * Maps {@code JTabbedPane.setTabPlacement(int)} through queue + */ + public void setTabPlacement(final int i) { + runMapping(new MapVoidAction("setTabPlacement") { + @Override + public void map() { + ((JTabbedPane) getSource()).setTabPlacement(i); + } + }); + } + + /** + * Maps {@code JTabbedPane.setTitleAt(int, String)} through queue + */ + public void setTitleAt(final int i, final String string) { + runMapping(new MapVoidAction("setTitleAt") { + @Override + public void map() { + ((JTabbedPane) getSource()).setTitleAt(i, string); + } + }); + } + + /** + * Maps {@code JTabbedPane.setUI(TabbedPaneUI)} through queue + */ + public void setUI(final TabbedPaneUI tabbedPaneUI) { + runMapping(new MapVoidAction("setUI") { + @Override + 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 { + + private static final long serialVersionUID = 42L; + + /** + * 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()); + } + + @Override + 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; + } + + @Override + public String getDescription() { + return ("JTabbedPane with text \"" + title + "\" in " + + itemIndex + "'th item"); + } + + @Override + public String toString() { + return "JTabbedPaneByItemFinder{" + "title=" + title + ", itemIndex=" + itemIndex + ", comparator=" + comparator + '}'; + } + } + + /** + * 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 static class BySubStringTabPageChooser implements TabPageChooser { + + String title; + StringComparator comparator; + + public BySubStringTabPageChooser(String title, StringComparator comparator) { + this.title = title; + this.comparator = comparator; + } + + @Override + public boolean checkPage(JTabbedPaneOperator oper, int index) { + return (comparator.equals(oper.getTitleAt(index), + title)); + } + + @Override + public String getDescription() { + return "Page having \"" + title + "\" title."; + } + + @Override + public String toString() { + return "BySubStringTabPageChooser{" + "title=" + title + ", comparator=" + comparator + '}'; + } + } + +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JTableHeaderOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JTableHeaderOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,571 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void setTimeouts(Timeouts times) { + this.timeouts = times; + super.setTimeouts(timeouts); + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output); + } + + @Override + 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)); + } + + @Override + public void copyEnvironment(Operator anotherOperator) { + super.copyEnvironment(anotherOperator); + driver + = (OrderedListDriver) DriverManager. + getDriver(DriverManager.ORDEREDLIST_DRIVER_ID, + getClass(), + anotherOperator.getProperties()); + } + + //////////////////////////////////////////////////////// + //Mapping // + /** + * Maps {@code JTableHeader.setTable(JTable)} through queue + */ + public void setTable(final JTable jTable) { + runMapping(new MapVoidAction("setTable") { + @Override + public void map() { + ((JTableHeader) getSource()).setTable(jTable); + } + }); + } + + /** + * Maps {@code JTableHeader.getTable()} through queue + */ + public JTable getTable() { + return (runMapping(new MapAction("getTable") { + @Override + public JTable map() { + return ((JTableHeader) getSource()).getTable(); + } + })); + } + + /** + * Maps {@code JTableHeader.setReorderingAllowed(boolean)} through queue + */ + public void setReorderingAllowed(final boolean b) { + runMapping(new MapVoidAction("setReorderingAllowed") { + @Override + public void map() { + ((JTableHeader) getSource()).setReorderingAllowed(b); + } + }); + } + + /** + * Maps {@code JTableHeader.getReorderingAllowed()} through queue + */ + public boolean getReorderingAllowed() { + return (runMapping(new MapBooleanAction("getReorderingAllowed") { + @Override + public boolean map() { + return ((JTableHeader) getSource()).getReorderingAllowed(); + } + })); + } + + /** + * Maps {@code JTableHeader.setResizingAllowed(boolean)} through queue + */ + public void setResizingAllowed(final boolean b) { + runMapping(new MapVoidAction("setResizingAllowed") { + @Override + public void map() { + ((JTableHeader) getSource()).setResizingAllowed(b); + } + }); + } + + /** + * Maps {@code JTableHeader.getResizingAllowed()} through queue + */ + public boolean getResizingAllowed() { + return (runMapping(new MapBooleanAction("getResizingAllowed") { + @Override + public boolean map() { + return ((JTableHeader) getSource()).getResizingAllowed(); + } + })); + } + + /** + * Maps {@code JTableHeader.getDraggedColumn()} through queue + */ + public TableColumn getDraggedColumn() { + return (runMapping(new MapAction("getDraggedColumn") { + @Override + public TableColumn map() { + return ((JTableHeader) getSource()).getDraggedColumn(); + } + })); + } + + /** + * Maps {@code JTableHeader.getDraggedDistance()} through queue + */ + public int getDraggedDistance() { + return (runMapping(new MapIntegerAction("getDraggedDistance") { + @Override + public int map() { + return ((JTableHeader) getSource()).getDraggedDistance(); + } + })); + } + + /** + * Maps {@code JTableHeader.getResizingColumn()} through queue + */ + public TableColumn getResizingColumn() { + return (runMapping(new MapAction("getResizingColumn") { + @Override + public TableColumn map() { + return ((JTableHeader) getSource()).getResizingColumn(); + } + })); + } + + /** + * Maps {@code JTableHeader.setUpdateTableInRealTime(boolean)} through queue + */ + public void setUpdateTableInRealTime(final boolean b) { + runMapping(new MapVoidAction("setUpdateTableInRealTime") { + @Override + public void map() { + ((JTableHeader) getSource()).setUpdateTableInRealTime(b); + } + }); + } + + /** + * Maps {@code JTableHeader.getUpdateTableInRealTime()} through queue + */ + public boolean getUpdateTableInRealTime() { + return (runMapping(new MapBooleanAction("getUpdateTableInRealTime") { + @Override + public boolean map() { + return ((JTableHeader) getSource()).getUpdateTableInRealTime(); + } + })); + } + + /** + * Maps {@code JTableHeader.setDefaultRenderer(TableCellRenderer)} + * through queue + */ + public void setDefaultRenderer(final TableCellRenderer tableCellRenderer) { + runMapping(new MapVoidAction("setDefaultRenderer") { + @Override + public void map() { + ((JTableHeader) getSource()).setDefaultRenderer(tableCellRenderer); + } + }); + } + + /** + * Maps {@code JTableHeader.getDefaultRenderer()} through queue + */ + public TableCellRenderer getDefaultRenderer() { + return (runMapping(new MapAction("getDefaultRenderer") { + @Override + public TableCellRenderer map() { + return ((JTableHeader) getSource()).getDefaultRenderer(); + } + })); + } + + /** + * Maps {@code JTableHeader.columnAtPoint(Point)} through queue + */ + public int columnAtPoint(final Point point) { + return (runMapping(new MapIntegerAction("columnAtPoint") { + @Override + public int map() { + return ((JTableHeader) getSource()).columnAtPoint(point); + } + })); + } + + /** + * Maps {@code JTableHeader.getHeaderRect(int)} through queue + */ + public Rectangle getHeaderRect(final int i) { + return (runMapping(new MapAction("getHeaderRect") { + @Override + public Rectangle map() { + return ((JTableHeader) getSource()).getHeaderRect(i); + } + })); + } + + /** + * Maps {@code JTableHeader.getUI()} through queue + */ + public TableHeaderUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public TableHeaderUI map() { + return ((JTableHeader) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JTableHeader.setUI(TableHeaderUI)} through queue + */ + public void setUI(final TableHeaderUI tableHeaderUI) { + runMapping(new MapVoidAction("setUI") { + @Override + public void map() { + ((JTableHeader) getSource()).setUI(tableHeaderUI); + } + }); + } + + /** + * Maps {@code JTableHeader.setColumnModel(TableColumnModel)} through queue + */ + public void setColumnModel(final TableColumnModel tableColumnModel) { + runMapping(new MapVoidAction("setColumnModel") { + @Override + public void map() { + ((JTableHeader) getSource()).setColumnModel(tableColumnModel); + } + }); + } + + /** + * Maps {@code JTableHeader.getColumnModel()} through queue + */ + public TableColumnModel getColumnModel() { + return (runMapping(new MapAction("getColumnModel") { + @Override + public TableColumnModel map() { + return ((JTableHeader) getSource()).getColumnModel(); + } + })); + } + + /** + * Maps {@code JTableHeader.columnAdded(TableColumnModelEvent)} through queue + */ + public void columnAdded(final TableColumnModelEvent tableColumnModelEvent) { + runMapping(new MapVoidAction("columnAdded") { + @Override + public void map() { + ((JTableHeader) getSource()).columnAdded(tableColumnModelEvent); + } + }); + } + + /** + * Maps {@code JTableHeader.columnRemoved(TableColumnModelEvent)} + * through queue + */ + public void columnRemoved(final TableColumnModelEvent tableColumnModelEvent) { + runMapping(new MapVoidAction("columnRemoved") { + @Override + public void map() { + ((JTableHeader) getSource()).columnRemoved(tableColumnModelEvent); + } + }); + } + + /** + * Maps {@code JTableHeader.columnMoved(TableColumnModelEvent)} through queue + */ + public void columnMoved(final TableColumnModelEvent tableColumnModelEvent) { + runMapping(new MapVoidAction("columnMoved") { + @Override + public void map() { + ((JTableHeader) getSource()).columnMoved(tableColumnModelEvent); + } + }); + } + + /** + * Maps {@code JTableHeader.columnMarginChanged(ChangeEvent)} through queue + */ + public void columnMarginChanged(final ChangeEvent changeEvent) { + runMapping(new MapVoidAction("columnMarginChanged") { + @Override + public void map() { + ((JTableHeader) getSource()).columnMarginChanged(changeEvent); + } + }); + } + + /** + * Maps {@code JTableHeader.columnSelectionChanged(ListSelectionEvent)} + * through queue + */ + public void columnSelectionChanged(final ListSelectionEvent listSelectionEvent) { + runMapping(new MapVoidAction("columnSelectionChanged") { + @Override + public void map() { + ((JTableHeader) getSource()).columnSelectionChanged(listSelectionEvent); + } + }); + } + + /** + * Maps {@code JTableHeader.resizeAndRepaint()} through queue + */ + public void resizeAndRepaint() { + runMapping(new MapVoidAction("resizeAndRepaint") { + @Override + public void map() { + ((JTableHeader) getSource()).resizeAndRepaint(); + } + }); + } + + /** + * Maps {@code JTableHeader.setDraggedColumn(TableColumn)} through queue + */ + public void setDraggedColumn(final TableColumn tableColumn) { + runMapping(new MapVoidAction("setDraggedColumn") { + @Override + public void map() { + ((JTableHeader) getSource()).setDraggedColumn(tableColumn); + } + }); + } + + /** + * Maps {@code JTableHeader.setDraggedDistance(int)} through queue + */ + public void setDraggedDistance(final int i) { + runMapping(new MapVoidAction("setDraggedDistance") { + @Override + public void map() { + ((JTableHeader) getSource()).setDraggedDistance(i); + } + }); + } + + /** + * Maps {@code JTableHeader.setResizingColumn(TableColumn)} through queue + */ + public void setResizingColumn(final TableColumn tableColumn) { + runMapping(new MapVoidAction("setResizingColumn") { + @Override + 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; + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof JTableHeader) { + return subFinder.checkComponent(comp); + } + return false; + } + + @Override + public String getDescription() { + return subFinder.getDescription(); + } + + @Override + public String toString() { + return "JTableHeaderFinder{" + "subFinder=" + subFinder + '}'; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JTableOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JTableOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,2760 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 // + //////////////////////////////////////////////////////// + @Override + public void setTimeouts(Timeouts times) { + this.timeouts = times; + super.setTimeouts(timeouts); + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output); + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + 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) + */ + @Deprecated + 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) + */ + @Deprecated + 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) + */ + @Deprecated + 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) + */ + @Deprecated + 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 realRow : realRows) { + for (int realColumn : realColumns) { + if (chooser.checkCell(this, realRow, realColumn)) { + if (count == index) { + return new Point(realColumn, realRow); + } 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") { + @Override + public Void 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 + */ + @Deprecated + 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 {@code 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 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 + * {@code 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. + */ + @Override + 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 {@code JTable.addColumn(TableColumn)} through queue + */ + public void addColumn(final TableColumn tableColumn) { + runMapping(new MapVoidAction("addColumn") { + @Override + public void map() { + ((JTable) getSource()).addColumn(tableColumn); + } + }); + } + + /** + * Maps {@code JTable.addColumnSelectionInterval(int, int)} through queue + */ + public void addColumnSelectionInterval(final int i, final int i1) { + runMapping(new MapVoidAction("addColumnSelectionInterval") { + @Override + public void map() { + ((JTable) getSource()).addColumnSelectionInterval(i, i1); + } + }); + } + + /** + * Maps {@code JTable.addRowSelectionInterval(int, int)} through queue + */ + public void addRowSelectionInterval(final int i, final int i1) { + runMapping(new MapVoidAction("addRowSelectionInterval") { + @Override + public void map() { + ((JTable) getSource()).addRowSelectionInterval(i, i1); + } + }); + } + + /** + * Maps {@code JTable.clearSelection()} through queue + */ + public void clearSelection() { + runMapping(new MapVoidAction("clearSelection") { + @Override + public void map() { + ((JTable) getSource()).clearSelection(); + } + }); + } + + /** + * Maps {@code JTable.columnAdded(TableColumnModelEvent)} through queue + */ + public void columnAdded(final TableColumnModelEvent tableColumnModelEvent) { + runMapping(new MapVoidAction("columnAdded") { + @Override + public void map() { + ((JTable) getSource()).columnAdded(tableColumnModelEvent); + } + }); + } + + /** + * Maps {@code JTable.columnAtPoint(Point)} through queue + */ + public int columnAtPoint(final Point point) { + return (runMapping(new MapIntegerAction("columnAtPoint") { + @Override + public int map() { + return ((JTable) getSource()).columnAtPoint(point); + } + })); + } + + /** + * Maps {@code JTable.columnMarginChanged(ChangeEvent)} through queue + */ + public void columnMarginChanged(final ChangeEvent changeEvent) { + runMapping(new MapVoidAction("columnMarginChanged") { + @Override + public void map() { + ((JTable) getSource()).columnMarginChanged(changeEvent); + } + }); + } + + /** + * Maps {@code JTable.columnMoved(TableColumnModelEvent)} through queue + */ + public void columnMoved(final TableColumnModelEvent tableColumnModelEvent) { + runMapping(new MapVoidAction("columnMoved") { + @Override + public void map() { + ((JTable) getSource()).columnMoved(tableColumnModelEvent); + } + }); + } + + /** + * Maps {@code JTable.columnRemoved(TableColumnModelEvent)} through queue + */ + public void columnRemoved(final TableColumnModelEvent tableColumnModelEvent) { + runMapping(new MapVoidAction("columnRemoved") { + @Override + public void map() { + ((JTable) getSource()).columnRemoved(tableColumnModelEvent); + } + }); + } + + /** + * Maps {@code JTable.columnSelectionChanged(ListSelectionEvent)} + * through queue + */ + public void columnSelectionChanged(final ListSelectionEvent listSelectionEvent) { + runMapping(new MapVoidAction("columnSelectionChanged") { + @Override + public void map() { + ((JTable) getSource()).columnSelectionChanged(listSelectionEvent); + } + }); + } + + /** + * Maps {@code JTable.convertColumnIndexToModel(int)} through queue + */ + public int convertColumnIndexToModel(final int i) { + return (runMapping(new MapIntegerAction("convertColumnIndexToModel") { + @Override + public int map() { + return ((JTable) getSource()).convertColumnIndexToModel(i); + } + })); + } + + /** + * Maps {@code JTable.convertColumnIndexToView(int)} through queue + */ + public int convertColumnIndexToView(final int i) { + return (runMapping(new MapIntegerAction("convertColumnIndexToView") { + @Override + public int map() { + return ((JTable) getSource()).convertColumnIndexToView(i); + } + })); + } + + /** + * Maps {@code JTable.createDefaultColumnsFromModel()} through queue + */ + public void createDefaultColumnsFromModel() { + runMapping(new MapVoidAction("createDefaultColumnsFromModel") { + @Override + public void map() { + ((JTable) getSource()).createDefaultColumnsFromModel(); + } + }); + } + + /** + * Maps {@code JTable.editCellAt(int, int)} through queue + */ + public boolean editCellAt(final int i, final int i1) { + return (runMapping(new MapBooleanAction("editCellAt") { + @Override + public boolean map() { + return ((JTable) getSource()).editCellAt(i, i1); + } + })); + } + + /** + * Maps {@code JTable.editCellAt(int, int, EventObject)} through queue + */ + public boolean editCellAt(final int i, final int i1, final EventObject eventObject) { + return (runMapping(new MapBooleanAction("editCellAt") { + @Override + public boolean map() { + return ((JTable) getSource()).editCellAt(i, i1, eventObject); + } + })); + } + + /** + * Maps {@code JTable.editingCanceled(ChangeEvent)} through queue + */ + public void editingCanceled(final ChangeEvent changeEvent) { + runMapping(new MapVoidAction("editingCanceled") { + @Override + public void map() { + ((JTable) getSource()).editingCanceled(changeEvent); + } + }); + } + + /** + * Maps {@code JTable.editingStopped(ChangeEvent)} through queue + */ + public void editingStopped(final ChangeEvent changeEvent) { + runMapping(new MapVoidAction("editingStopped") { + @Override + public void map() { + ((JTable) getSource()).editingStopped(changeEvent); + } + }); + } + + /** + * Maps {@code JTable.getAutoCreateColumnsFromModel()} through queue + */ + public boolean getAutoCreateColumnsFromModel() { + return (runMapping(new MapBooleanAction("getAutoCreateColumnsFromModel") { + @Override + public boolean map() { + return ((JTable) getSource()).getAutoCreateColumnsFromModel(); + } + })); + } + + /** + * Maps {@code JTable.getAutoResizeMode()} through queue + */ + public int getAutoResizeMode() { + return (runMapping(new MapIntegerAction("getAutoResizeMode") { + @Override + public int map() { + return ((JTable) getSource()).getAutoResizeMode(); + } + })); + } + + /** + * Maps {@code JTable.getCellEditor()} through queue + */ + public TableCellEditor getCellEditor() { + return (runMapping(new MapAction("getCellEditor") { + @Override + public TableCellEditor map() { + return ((JTable) getSource()).getCellEditor(); + } + })); + } + + /** + * Maps {@code JTable.getCellEditor(int, int)} through queue + */ + public TableCellEditor getCellEditor(final int i, final int i1) { + return (runMapping(new MapAction("getCellEditor") { + @Override + public TableCellEditor map() { + return ((JTable) getSource()).getCellEditor(i, i1); + } + })); + } + + /** + * Maps {@code JTable.getCellRect(int, int, boolean)} through queue + */ + public Rectangle getCellRect(final int i, final int i1, final boolean b) { + return (runMapping(new MapAction("getCellRect") { + @Override + public Rectangle map() { + return ((JTable) getSource()).getCellRect(i, i1, b); + } + })); + } + + /** + * Maps {@code JTable.getCellRenderer(int, int)} through queue + */ + public TableCellRenderer getCellRenderer(final int i, final int i1) { + return (runMapping(new MapAction("getCellRenderer") { + @Override + public TableCellRenderer map() { + return ((JTable) getSource()).getCellRenderer(i, i1); + } + })); + } + + /** + * Maps {@code JTable.getCellSelectionEnabled()} through queue + */ + public boolean getCellSelectionEnabled() { + return (runMapping(new MapBooleanAction("getCellSelectionEnabled") { + @Override + public boolean map() { + return ((JTable) getSource()).getCellSelectionEnabled(); + } + })); + } + + /** + * Maps {@code JTable.getColumn(Object)} through queue + */ + public TableColumn getColumn(final Object object) { + return (runMapping(new MapAction("getColumn") { + @Override + public TableColumn map() { + return ((JTable) getSource()).getColumn(object); + } + })); + } + + /** + * Maps {@code JTable.getColumnClass(int)} through queue + */ + public Class getColumnClass(final int i) { + return (runMapping(new MapAction>("getColumnClass") { + @Override + public Class map() { + return ((JTable) getSource()).getColumnClass(i); + } + })); + } + + /** + * Maps {@code JTable.getColumnCount()} through queue + */ + public int getColumnCount() { + return (runMapping(new MapIntegerAction("getColumnCount") { + @Override + public int map() { + return ((JTable) getSource()).getColumnCount(); + } + })); + } + + /** + * Maps {@code JTable.getColumnModel()} through queue + */ + public TableColumnModel getColumnModel() { + return (runMapping(new MapAction("getColumnModel") { + @Override + public TableColumnModel map() { + return ((JTable) getSource()).getColumnModel(); + } + })); + } + + /** + * Maps {@code JTable.getColumnName(int)} through queue + */ + public String getColumnName(final int i) { + return (runMapping(new MapAction("getColumnName") { + @Override + public String map() { + return ((JTable) getSource()).getColumnName(i); + } + })); + } + + /** + * Maps {@code JTable.getColumnSelectionAllowed()} through queue + */ + public boolean getColumnSelectionAllowed() { + return (runMapping(new MapBooleanAction("getColumnSelectionAllowed") { + @Override + public boolean map() { + return ((JTable) getSource()).getColumnSelectionAllowed(); + } + })); + } + + /** + * Maps {@code JTable.getDefaultEditor(Class)} through queue + */ + public TableCellEditor getDefaultEditor(final Class clss) { + return (runMapping(new MapAction("getDefaultEditor") { + @Override + public TableCellEditor map() { + return ((JTable) getSource()).getDefaultEditor(clss); + } + })); + } + + /** + * Maps {@code JTable.getDefaultRenderer(Class)} through queue + */ + public TableCellRenderer getDefaultRenderer(final Class clss) { + return (runMapping(new MapAction("getDefaultRenderer") { + @Override + public TableCellRenderer map() { + return ((JTable) getSource()).getDefaultRenderer(clss); + } + })); + } + + /** + * Maps {@code JTable.getEditingColumn()} through queue + */ + public int getEditingColumn() { + return (runMapping(new MapIntegerAction("getEditingColumn") { + @Override + public int map() { + return ((JTable) getSource()).getEditingColumn(); + } + })); + } + + /** + * Maps {@code JTable.getEditingRow()} through queue + */ + public int getEditingRow() { + return (runMapping(new MapIntegerAction("getEditingRow") { + @Override + public int map() { + return ((JTable) getSource()).getEditingRow(); + } + })); + } + + /** + * Maps {@code JTable.getEditorComponent()} through queue + */ + public Component getEditorComponent() { + return (runMapping(new MapAction("getEditorComponent") { + @Override + public Component map() { + return ((JTable) getSource()).getEditorComponent(); + } + })); + } + + /** + * Maps {@code JTable.getGridColor()} through queue + */ + public Color getGridColor() { + return (runMapping(new MapAction("getGridColor") { + @Override + public Color map() { + return ((JTable) getSource()).getGridColor(); + } + })); + } + + /** + * Maps {@code JTable.getIntercellSpacing()} through queue + */ + public Dimension getIntercellSpacing() { + return (runMapping(new MapAction("getIntercellSpacing") { + @Override + public Dimension map() { + return ((JTable) getSource()).getIntercellSpacing(); + } + })); + } + + /** + * Maps {@code JTable.getModel()} through queue + */ + public TableModel getModel() { + return (runMapping(new MapAction("getModel") { + @Override + public TableModel map() { + return ((JTable) getSource()).getModel(); + } + })); + } + + /** + * Maps {@code JTable.getPreferredScrollableViewportSize()} through queue + */ + public Dimension getPreferredScrollableViewportSize() { + return (runMapping(new MapAction("getPreferredScrollableViewportSize") { + @Override + public Dimension map() { + return ((JTable) getSource()).getPreferredScrollableViewportSize(); + } + })); + } + + /** + * Maps {@code JTable.getRowCount()} through queue + */ + public int getRowCount() { + return (runMapping(new MapIntegerAction("getRowCount") { + @Override + public int map() { + return ((JTable) getSource()).getRowCount(); + } + })); + } + + /** + * Maps {@code JTable.getRowHeight()} through queue + */ + public int getRowHeight() { + return (runMapping(new MapIntegerAction("getRowHeight") { + @Override + public int map() { + return ((JTable) getSource()).getRowHeight(); + } + })); + } + + /** + * Maps {@code JTable.getRowMargin()} through queue + */ + public int getRowMargin() { + return (runMapping(new MapIntegerAction("getRowMargin") { + @Override + public int map() { + return ((JTable) getSource()).getRowMargin(); + } + })); + } + + /** + * Maps {@code JTable.getRowSelectionAllowed()} through queue + */ + public boolean getRowSelectionAllowed() { + return (runMapping(new MapBooleanAction("getRowSelectionAllowed") { + @Override + public boolean map() { + return ((JTable) getSource()).getRowSelectionAllowed(); + } + })); + } + + /** + * Maps {@code JTable.getScrollableBlockIncrement(Rectangle, int, int)} + * through queue + */ + public int getScrollableBlockIncrement(final Rectangle rectangle, final int i, final int i1) { + return (runMapping(new MapIntegerAction("getScrollableBlockIncrement") { + @Override + public int map() { + return ((JTable) getSource()).getScrollableBlockIncrement(rectangle, i, i1); + } + })); + } + + /** + * Maps {@code JTable.getScrollableTracksViewportHeight()} through queue + */ + public boolean getScrollableTracksViewportHeight() { + return (runMapping(new MapBooleanAction("getScrollableTracksViewportHeight") { + @Override + public boolean map() { + return ((JTable) getSource()).getScrollableTracksViewportHeight(); + } + })); + } + + /** + * Maps {@code JTable.getScrollableTracksViewportWidth()} through queue + */ + public boolean getScrollableTracksViewportWidth() { + return (runMapping(new MapBooleanAction("getScrollableTracksViewportWidth") { + @Override + public boolean map() { + return ((JTable) getSource()).getScrollableTracksViewportWidth(); + } + })); + } + + /** + * Maps {@code JTable.getScrollableUnitIncrement(Rectangle, int, int)} + * through queue + */ + public int getScrollableUnitIncrement(final Rectangle rectangle, final int i, final int i1) { + return (runMapping(new MapIntegerAction("getScrollableUnitIncrement") { + @Override + public int map() { + return ((JTable) getSource()).getScrollableUnitIncrement(rectangle, i, i1); + } + })); + } + + /** + * Maps {@code JTable.getSelectedColumn()} through queue + */ + public int getSelectedColumn() { + return (runMapping(new MapIntegerAction("getSelectedColumn") { + @Override + public int map() { + return ((JTable) getSource()).getSelectedColumn(); + } + })); + } + + /** + * Maps {@code JTable.getSelectedColumnCount()} through queue + */ + public int getSelectedColumnCount() { + return (runMapping(new MapIntegerAction("getSelectedColumnCount") { + @Override + public int map() { + return ((JTable) getSource()).getSelectedColumnCount(); + } + })); + } + + /** + * Maps {@code JTable.getSelectedColumns()} through queue + */ + public int[] getSelectedColumns() { + return ((int[]) runMapping(new MapAction("getSelectedColumns") { + @Override + public Object map() { + return ((JTable) getSource()).getSelectedColumns(); + } + })); + } + + /** + * Maps {@code JTable.getSelectedRow()} through queue + */ + public int getSelectedRow() { + return (runMapping(new MapIntegerAction("getSelectedRow") { + @Override + public int map() { + return ((JTable) getSource()).getSelectedRow(); + } + })); + } + + /** + * Maps {@code JTable.getSelectedRowCount()} through queue + */ + public int getSelectedRowCount() { + return (runMapping(new MapIntegerAction("getSelectedRowCount") { + @Override + public int map() { + return ((JTable) getSource()).getSelectedRowCount(); + } + })); + } + + /** + * Maps {@code JTable.getSelectedRows()} through queue + */ + public int[] getSelectedRows() { + return ((int[]) runMapping(new MapAction("getSelectedRows") { + @Override + public Object map() { + return ((JTable) getSource()).getSelectedRows(); + } + })); + } + + /** + * Maps {@code JTable.getSelectionBackground()} through queue + */ + public Color getSelectionBackground() { + return (runMapping(new MapAction("getSelectionBackground") { + @Override + public Color map() { + return ((JTable) getSource()).getSelectionBackground(); + } + })); + } + + /** + * Maps {@code JTable.getSelectionForeground()} through queue + */ + public Color getSelectionForeground() { + return (runMapping(new MapAction("getSelectionForeground") { + @Override + public Color map() { + return ((JTable) getSource()).getSelectionForeground(); + } + })); + } + + /** + * Maps {@code JTable.getSelectionModel()} through queue + */ + public ListSelectionModel getSelectionModel() { + return (runMapping(new MapAction("getSelectionModel") { + @Override + public ListSelectionModel map() { + return ((JTable) getSource()).getSelectionModel(); + } + })); + } + + /** + * Maps {@code JTable.getShowHorizontalLines()} through queue + */ + public boolean getShowHorizontalLines() { + return (runMapping(new MapBooleanAction("getShowHorizontalLines") { + @Override + public boolean map() { + return ((JTable) getSource()).getShowHorizontalLines(); + } + })); + } + + /** + * Maps {@code JTable.getShowVerticalLines()} through queue + */ + public boolean getShowVerticalLines() { + return (runMapping(new MapBooleanAction("getShowVerticalLines") { + @Override + public boolean map() { + return ((JTable) getSource()).getShowVerticalLines(); + } + })); + } + + /** + * Maps {@code JTable.getTableHeader()} through queue + */ + public JTableHeader getTableHeader() { + return (runMapping(new MapAction("getTableHeader") { + @Override + public JTableHeader map() { + return ((JTable) getSource()).getTableHeader(); + } + })); + } + + /** + * Maps {@code JTable.getUI()} through queue + */ + public TableUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public TableUI map() { + return ((JTable) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JTable.getValueAt(int, int)} through queue + */ + public Object getValueAt(final int i, final int i1) { + return (runMapping(new MapAction("getValueAt") { + @Override + public Object map() { + return ((JTable) getSource()).getValueAt(i, i1); + } + })); + } + + /** + * Maps {@code JTable.isCellEditable(int, int)} through queue + */ + public boolean isCellEditable(final int i, final int i1) { + return (runMapping(new MapBooleanAction("isCellEditable") { + @Override + public boolean map() { + return ((JTable) getSource()).isCellEditable(i, i1); + } + })); + } + + /** + * Maps {@code JTable.isCellSelected(int, int)} through queue + */ + public boolean isCellSelected(final int i, final int i1) { + return (runMapping(new MapBooleanAction("isCellSelected") { + @Override + public boolean map() { + return ((JTable) getSource()).isCellSelected(i, i1); + } + })); + } + + /** + * Maps {@code JTable.isColumnSelected(int)} through queue + */ + public boolean isColumnSelected(final int i) { + return (runMapping(new MapBooleanAction("isColumnSelected") { + @Override + public boolean map() { + return ((JTable) getSource()).isColumnSelected(i); + } + })); + } + + /** + * Maps {@code JTable.isEditing()} through queue + */ + public boolean isEditing() { + return (runMapping(new MapBooleanAction("isEditing") { + @Override + public boolean map() { + return ((JTable) getSource()).isEditing(); + } + })); + } + + /** + * Maps {@code JTable.isRowSelected(int)} through queue + */ + public boolean isRowSelected(final int i) { + return (runMapping(new MapBooleanAction("isRowSelected") { + @Override + public boolean map() { + return ((JTable) getSource()).isRowSelected(i); + } + })); + } + + /** + * Maps {@code JTable.moveColumn(int, int)} through queue + */ + public void moveColumn(final int i, final int i1) { + runMapping(new MapVoidAction("moveColumn") { + @Override + public void map() { + ((JTable) getSource()).moveColumn(i, i1); + } + }); + } + + /** + * Maps {@code JTable.prepareEditor(TableCellEditor, int, int)} through queue + */ + public Component prepareEditor(final TableCellEditor tableCellEditor, final int i, final int i1) { + return (runMapping(new MapAction("prepareEditor") { + @Override + public Component map() { + return ((JTable) getSource()).prepareEditor(tableCellEditor, i, i1); + } + })); + } + + /** + * Maps {@code JTable.prepareRenderer(TableCellRenderer, int, int)} + * through queue + */ + public Component prepareRenderer(final TableCellRenderer tableCellRenderer, final int i, final int i1) { + return (runMapping(new MapAction("prepareRenderer") { + @Override + public Component map() { + return ((JTable) getSource()).prepareRenderer(tableCellRenderer, i, i1); + } + })); + } + + /** + * Maps {@code JTable.removeColumn(TableColumn)} through queue + */ + public void removeColumn(final TableColumn tableColumn) { + runMapping(new MapVoidAction("removeColumn") { + @Override + public void map() { + ((JTable) getSource()).removeColumn(tableColumn); + } + }); + } + + /** + * Maps {@code JTable.removeColumnSelectionInterval(int, int)} through queue + */ + public void removeColumnSelectionInterval(final int i, final int i1) { + runMapping(new MapVoidAction("removeColumnSelectionInterval") { + @Override + public void map() { + ((JTable) getSource()).removeColumnSelectionInterval(i, i1); + } + }); + } + + /** + * Maps {@code JTable.removeEditor()} through queue + */ + public void removeEditor() { + runMapping(new MapVoidAction("removeEditor") { + @Override + public void map() { + ((JTable) getSource()).removeEditor(); + } + }); + } + + /** + * Maps {@code JTable.removeRowSelectionInterval(int, int)} through queue + */ + public void removeRowSelectionInterval(final int i, final int i1) { + runMapping(new MapVoidAction("removeRowSelectionInterval") { + @Override + public void map() { + ((JTable) getSource()).removeRowSelectionInterval(i, i1); + } + }); + } + + /** + * Maps {@code JTable.rowAtPoint(Point)} through queue + */ + public int rowAtPoint(final Point point) { + return (runMapping(new MapIntegerAction("rowAtPoint") { + @Override + public int map() { + return ((JTable) getSource()).rowAtPoint(point); + } + })); + } + + /** + * Maps {@code JTable.selectAll()} through queue + */ + public void selectAll() { + runMapping(new MapVoidAction("selectAll") { + @Override + public void map() { + ((JTable) getSource()).selectAll(); + } + }); + } + + /** + * Maps {@code JTable.setAutoCreateColumnsFromModel(boolean)} through queue + */ + public void setAutoCreateColumnsFromModel(final boolean b) { + runMapping(new MapVoidAction("setAutoCreateColumnsFromModel") { + @Override + public void map() { + ((JTable) getSource()).setAutoCreateColumnsFromModel(b); + } + }); + } + + /** + * Maps {@code JTable.setAutoResizeMode(int)} through queue + */ + public void setAutoResizeMode(final int i) { + runMapping(new MapVoidAction("setAutoResizeMode") { + @Override + public void map() { + ((JTable) getSource()).setAutoResizeMode(i); + } + }); + } + + /** + * Maps {@code JTable.setCellEditor(TableCellEditor)} through queue + */ + public void setCellEditor(final TableCellEditor tableCellEditor) { + runMapping(new MapVoidAction("setCellEditor") { + @Override + public void map() { + ((JTable) getSource()).setCellEditor(tableCellEditor); + } + }); + } + + /** + * Maps {@code JTable.setCellSelectionEnabled(boolean)} through queue + */ + public void setCellSelectionEnabled(final boolean b) { + runMapping(new MapVoidAction("setCellSelectionEnabled") { + @Override + public void map() { + ((JTable) getSource()).setCellSelectionEnabled(b); + } + }); + } + + /** + * Maps {@code JTable.setColumnModel(TableColumnModel)} through queue + */ + public void setColumnModel(final TableColumnModel tableColumnModel) { + runMapping(new MapVoidAction("setColumnModel") { + @Override + public void map() { + ((JTable) getSource()).setColumnModel(tableColumnModel); + } + }); + } + + /** + * Maps {@code JTable.setColumnSelectionAllowed(boolean)} through queue + */ + public void setColumnSelectionAllowed(final boolean b) { + runMapping(new MapVoidAction("setColumnSelectionAllowed") { + @Override + public void map() { + ((JTable) getSource()).setColumnSelectionAllowed(b); + } + }); + } + + /** + * Maps {@code JTable.setColumnSelectionInterval(int, int)} through queue + */ + public void setColumnSelectionInterval(final int i, final int i1) { + runMapping(new MapVoidAction("setColumnSelectionInterval") { + @Override + public void map() { + ((JTable) getSource()).setColumnSelectionInterval(i, i1); + } + }); + } + + /** + * Maps {@code JTable.setDefaultEditor(Class, TableCellEditor)} through queue + */ + public void setDefaultEditor(final Class clss, final TableCellEditor tableCellEditor) { + runMapping(new MapVoidAction("setDefaultEditor") { + @Override + public void map() { + ((JTable) getSource()).setDefaultEditor(clss, tableCellEditor); + } + }); + } + + /** + * Maps {@code JTable.setDefaultRenderer(Class, TableCellRenderer)} + * through queue + */ + public void setDefaultRenderer(final Class clss, final TableCellRenderer tableCellRenderer) { + runMapping(new MapVoidAction("setDefaultRenderer") { + @Override + public void map() { + ((JTable) getSource()).setDefaultRenderer(clss, tableCellRenderer); + } + }); + } + + /** + * Maps {@code JTable.setEditingColumn(int)} through queue + */ + public void setEditingColumn(final int i) { + runMapping(new MapVoidAction("setEditingColumn") { + @Override + public void map() { + ((JTable) getSource()).setEditingColumn(i); + } + }); + } + + /** + * Maps {@code JTable.setEditingRow(int)} through queue + */ + public void setEditingRow(final int i) { + runMapping(new MapVoidAction("setEditingRow") { + @Override + public void map() { + ((JTable) getSource()).setEditingRow(i); + } + }); + } + + /** + * Maps {@code JTable.setGridColor(Color)} through queue + */ + public void setGridColor(final Color color) { + runMapping(new MapVoidAction("setGridColor") { + @Override + public void map() { + ((JTable) getSource()).setGridColor(color); + } + }); + } + + /** + * Maps {@code JTable.setIntercellSpacing(Dimension)} through queue + */ + public void setIntercellSpacing(final Dimension dimension) { + runMapping(new MapVoidAction("setIntercellSpacing") { + @Override + public void map() { + ((JTable) getSource()).setIntercellSpacing(dimension); + } + }); + } + + /** + * Maps {@code JTable.setModel(TableModel)} through queue + */ + public void setModel(final TableModel tableModel) { + runMapping(new MapVoidAction("setModel") { + @Override + public void map() { + ((JTable) getSource()).setModel(tableModel); + } + }); + } + + /** + * Maps {@code JTable.setPreferredScrollableViewportSize(Dimension)} + * through queue + */ + public void setPreferredScrollableViewportSize(final Dimension dimension) { + runMapping(new MapVoidAction("setPreferredScrollableViewportSize") { + @Override + public void map() { + ((JTable) getSource()).setPreferredScrollableViewportSize(dimension); + } + }); + } + + /** + * Maps {@code JTable.setRowHeight(int)} through queue + */ + public void setRowHeight(final int i) { + runMapping(new MapVoidAction("setRowHeight") { + @Override + public void map() { + ((JTable) getSource()).setRowHeight(i); + } + }); + } + + /** + * Maps {@code JTable.setRowMargin(int)} through queue + */ + public void setRowMargin(final int i) { + runMapping(new MapVoidAction("setRowMargin") { + @Override + public void map() { + ((JTable) getSource()).setRowMargin(i); + } + }); + } + + /** + * Maps {@code JTable.setRowSelectionAllowed(boolean)} through queue + */ + public void setRowSelectionAllowed(final boolean b) { + runMapping(new MapVoidAction("setRowSelectionAllowed") { + @Override + public void map() { + ((JTable) getSource()).setRowSelectionAllowed(b); + } + }); + } + + /** + * Maps {@code JTable.setRowSelectionInterval(int, int)} through queue + */ + public void setRowSelectionInterval(final int i, final int i1) { + runMapping(new MapVoidAction("setRowSelectionInterval") { + @Override + public void map() { + ((JTable) getSource()).setRowSelectionInterval(i, i1); + } + }); + } + + /** + * Maps {@code JTable.setSelectionBackground(Color)} through queue + */ + public void setSelectionBackground(final Color color) { + runMapping(new MapVoidAction("setSelectionBackground") { + @Override + public void map() { + ((JTable) getSource()).setSelectionBackground(color); + } + }); + } + + /** + * Maps {@code JTable.setSelectionForeground(Color)} through queue + */ + public void setSelectionForeground(final Color color) { + runMapping(new MapVoidAction("setSelectionForeground") { + @Override + public void map() { + ((JTable) getSource()).setSelectionForeground(color); + } + }); + } + + /** + * Maps {@code JTable.setSelectionMode(int)} through queue + */ + public void setSelectionMode(final int i) { + runMapping(new MapVoidAction("setSelectionMode") { + @Override + public void map() { + ((JTable) getSource()).setSelectionMode(i); + } + }); + } + + /** + * Maps {@code JTable.setSelectionModel(ListSelectionModel)} through queue + */ + public void setSelectionModel(final ListSelectionModel listSelectionModel) { + runMapping(new MapVoidAction("setSelectionModel") { + @Override + public void map() { + ((JTable) getSource()).setSelectionModel(listSelectionModel); + } + }); + } + + /** + * Maps {@code JTable.setShowGrid(boolean)} through queue + */ + public void setShowGrid(final boolean b) { + runMapping(new MapVoidAction("setShowGrid") { + @Override + public void map() { + ((JTable) getSource()).setShowGrid(b); + } + }); + } + + /** + * Maps {@code JTable.setShowHorizontalLines(boolean)} through queue + */ + public void setShowHorizontalLines(final boolean b) { + runMapping(new MapVoidAction("setShowHorizontalLines") { + @Override + public void map() { + ((JTable) getSource()).setShowHorizontalLines(b); + } + }); + } + + /** + * Maps {@code JTable.setShowVerticalLines(boolean)} through queue + */ + public void setShowVerticalLines(final boolean b) { + runMapping(new MapVoidAction("setShowVerticalLines") { + @Override + public void map() { + ((JTable) getSource()).setShowVerticalLines(b); + } + }); + } + + /** + * Maps {@code JTable.setTableHeader(JTableHeader)} through queue + */ + public void setTableHeader(final JTableHeader jTableHeader) { + runMapping(new MapVoidAction("setTableHeader") { + @Override + public void map() { + ((JTable) getSource()).setTableHeader(jTableHeader); + } + }); + } + + /** + * Maps {@code JTable.setUI(TableUI)} through queue + */ + public void setUI(final TableUI tableUI) { + runMapping(new MapVoidAction("setUI") { + @Override + public void map() { + ((JTable) getSource()).setUI(tableUI); + } + }); + } + + /** + * Maps {@code JTable.setValueAt(Object, int, int)} through queue + */ + public void setValueAt(final Object object, final int i, final int i1) { + runMapping(new MapVoidAction("setValueAt") { + @Override + public void map() { + ((JTable) getSource()).setValueAt(object, i, i1); + } + }); + } + + /** + * Maps {@code JTable.tableChanged(TableModelEvent)} through queue + */ + public void tableChanged(final TableModelEvent tableModelEvent) { + runMapping(new MapVoidAction("tableChanged") { + @Override + public void map() { + ((JTable) getSource()).tableChanged(tableModelEvent); + } + }); + } + + /** + * Maps {@code JTable.valueChanged(ListSelectionEvent)} through queue + */ + public void valueChanged(final ListSelectionEvent listSelectionEvent) { + runMapping(new MapVoidAction("valueChanged") { + @Override + 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 static class BySubStringTableCellChooser implements TableCellChooser { + + String subString; + StringComparator comparator; + + public BySubStringTableCellChooser(String subString, StringComparator comparator) { + this.subString = subString; + this.comparator = comparator; + } + + @Override + 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)); + } + + @Override + public String getDescription() { + return "Cell containing \"" + subString + "\" string"; + } + + @Override + public String toString() { + return "BySubStringTableCellChooser{" + "subString=" + subString + ", comparator=" + comparator + '}'; + } + } + + private static class ByRenderedComponentTableCellChooser implements TableCellChooser { + + ComponentChooser chooser; + + public ByRenderedComponentTableCellChooser(ComponentChooser chooser) { + this.chooser = chooser; + } + + @Override + public boolean checkCell(JTableOperator oper, int row, int column) { + return chooser.checkComponent(oper.getRenderedComponent(row, column)); + } + + @Override + public String getDescription() { + return chooser.getDescription(); + } + + @Override + public String toString() { + return "ByRenderedComponentTableCellChooser{" + "chooser=" + chooser + '}'; + } + } + + /** + * 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()); + } + + @Override + 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; + } + + @Override + public String getDescription() { + return ("JTable with text \"" + label + "\" in (" + + row + ", " + + column + ") cell"); + } + + @Override + public String toString() { + return "JTableByCellFinder{" + "label=" + label + ", row=" + row + ", column=" + column + ", comparator=" + comparator + '}'; + } + } + + /** + * 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; + } + + @Override + public Component actionProduced(Void obj) { + Point pnt = getPointToClick(row, column); + Component comp = getComponentAt(pnt.x, pnt.y); + if (comp != null + && chooser.checkComponent(comp)) { + return comp; + } else { + return null; + } + } + + @Override + public String getDescription() { + return chooser.getDescription(); + } + + @Override + public String toString() { + return "CellComponentWaiter{" + "chooser=" + chooser + ", row=" + row + ", column=" + column + '}'; + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JTextAreaOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JTextAreaOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,658 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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); + } + + @Override + public void setTimeouts(Timeouts times) { + timeouts = times; + super.setTimeouts(timeouts); + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + 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. + */ + @Deprecated + 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.getInnerThrowable() instanceof BadLocationException)) { + throw (e); + } + } + int endPos = getText().length(); + try { + endPos = getLineStartOffset(endRow) + endColumn; + } catch (JemmyException e) { + if (!(e.getInnerThrowable() 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. + */ + @Override + 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 {@code JTextArea.append(String)} through queue + */ + public void append(final String string) { + runMapping(new MapVoidAction("append") { + @Override + public void map() { + ((JTextArea) getSource()).append(string); + } + }); + } + + /** + * Maps {@code JTextArea.getColumns()} through queue + */ + public int getColumns() { + return (runMapping(new MapIntegerAction("getColumns") { + @Override + public int map() { + return ((JTextArea) getSource()).getColumns(); + } + })); + } + + /** + * Maps {@code JTextArea.getLineCount()} through queue + */ + public int getLineCount() { + return (runMapping(new MapIntegerAction("getLineCount") { + @Override + public int map() { + return ((JTextArea) getSource()).getLineCount(); + } + })); + } + + /** + * Maps {@code JTextArea.getLineEndOffset(int)} through queue + */ + public int getLineEndOffset(final int i) { + return (runMapping(new MapIntegerAction("getLineEndOffset") { + @Override + public int map() throws BadLocationException { + return ((JTextArea) getSource()).getLineEndOffset(i); + } + })); + } + + /** + * Maps {@code JTextArea.getLineOfOffset(int)} through queue + */ + public int getLineOfOffset(final int i) { + return (runMapping(new MapIntegerAction("getLineOfOffset") { + @Override + public int map() throws BadLocationException { + return ((JTextArea) getSource()).getLineOfOffset(i); + } + })); + } + + /** + * Maps {@code JTextArea.getLineStartOffset(int)} through queue + */ + public int getLineStartOffset(final int i) { + return (runMapping(new MapIntegerAction("getLineStartOffset") { + @Override + public int map() throws BadLocationException { + return ((JTextArea) getSource()).getLineStartOffset(i); + } + })); + } + + /** + * Maps {@code JTextArea.getLineWrap()} through queue + */ + public boolean getLineWrap() { + return (runMapping(new MapBooleanAction("getLineWrap") { + @Override + public boolean map() { + return ((JTextArea) getSource()).getLineWrap(); + } + })); + } + + /** + * Maps {@code JTextArea.getRows()} through queue + */ + public int getRows() { + return (runMapping(new MapIntegerAction("getRows") { + @Override + public int map() { + return ((JTextArea) getSource()).getRows(); + } + })); + } + + /** + * Maps {@code JTextArea.getTabSize()} through queue + */ + public int getTabSize() { + return (runMapping(new MapIntegerAction("getTabSize") { + @Override + public int map() { + return ((JTextArea) getSource()).getTabSize(); + } + })); + } + + /** + * Maps {@code JTextArea.getWrapStyleWord()} through queue + */ + public boolean getWrapStyleWord() { + return (runMapping(new MapBooleanAction("getWrapStyleWord") { + @Override + public boolean map() { + return ((JTextArea) getSource()).getWrapStyleWord(); + } + })); + } + + /** + * Maps {@code JTextArea.insert(String, int)} through queue + */ + public void insert(final String string, final int i) { + runMapping(new MapVoidAction("insert") { + @Override + public void map() { + ((JTextArea) getSource()).insert(string, i); + } + }); + } + + /** + * Maps {@code JTextArea.replaceRange(String, int, int)} through queue + */ + public void replaceRange(final String string, final int i, final int i1) { + runMapping(new MapVoidAction("replaceRange") { + @Override + public void map() { + ((JTextArea) getSource()).replaceRange(string, i, i1); + } + }); + } + + /** + * Maps {@code JTextArea.setColumns(int)} through queue + */ + public void setColumns(final int i) { + runMapping(new MapVoidAction("setColumns") { + @Override + public void map() { + ((JTextArea) getSource()).setColumns(i); + } + }); + } + + /** + * Maps {@code JTextArea.setLineWrap(boolean)} through queue + */ + public void setLineWrap(final boolean b) { + runMapping(new MapVoidAction("setLineWrap") { + @Override + public void map() { + ((JTextArea) getSource()).setLineWrap(b); + } + }); + } + + /** + * Maps {@code JTextArea.setRows(int)} through queue + */ + public void setRows(final int i) { + runMapping(new MapVoidAction("setRows") { + @Override + public void map() { + ((JTextArea) getSource()).setRows(i); + } + }); + } + + /** + * Maps {@code JTextArea.setTabSize(int)} through queue + */ + public void setTabSize(final int i) { + runMapping(new MapVoidAction("setTabSize") { + @Override + public void map() { + ((JTextArea) getSource()).setTabSize(i); + } + }); + } + + /** + * Maps {@code JTextArea.setWrapStyleWord(boolean)} through queue + */ + public void setWrapStyleWord(final boolean b) { + runMapping(new MapVoidAction("setWrapStyleWord") { + @Override + 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JTextComponentOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JTextComponentOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,1599 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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. + */ + @Deprecated + 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); + } + + @Override + public void setTimeouts(Timeouts times) { + timeouts = times; + timeouts.setTimeout("ComponentOperator.PushKeyTimeout", + timeouts.getTimeout("JTextComponentOperator.PushKeyTimeout")); + super.setTimeouts(timeouts); + } + + @Override + public Timeouts getTimeouts() { + return timeouts; + } + + @Override + public void setOutput(TestOut out) { + output = out; + super.setOutput(output.createErrorOutput()); + } + + @Override + public TestOut getOutput() { + return output; + } + + @Override + 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() { + @Override + public boolean checkPosition(Document doc, int offset) { + return true; + } + + @Override + public String getDescription() { + return "any"; + } + + @Override + public String toString() { + return "JTextComponentOperator.getPositionByText.TextChooser{description = " + getDescription() + '}'; + } + }, 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. Shouldn't include final '\n'. + * @throws TimeoutExpiredException + */ + public void enterText(final String text) { + makeComponentVisible(); + produceTimeRestricted(new Action() { + @Override + public Void launch(Void obj) { + driver.enterText(JTextComponentOperator.this, text); + return null; + } + + @Override + public String getDescription() { + return "Text entering"; + } + + @Override + public String toString() { + return "JTextComponentOperator.enterText.Action{description = " + getDescription() + '}'; + } + }, "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() { + @Override + public Void launch(Void obj) { + driver.changeCaretPosition(JTextComponentOperator.this, position); + return null; + } + + @Override + public String getDescription() { + return "Caret moving"; + } + + @Override + public String toString() { + return "JTextComponentOperator.changeCaretPosition.Action{description = " + getDescription() + '}'; + } + }, "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() { + @Override + public Void launch(Void obj) { + driver.typeText(JTextComponentOperator.this, text, caretPosition); + return null; + } + + @Override + public String getDescription() { + return "Text typing"; + } + + @Override + public String toString() { + return "JTextComponentOperator.typeText.Action{description = " + getDescription() + '}'; + } + }, "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() { + @Override + public Void launch(Void obj) { + driver.selectText(JTextComponentOperator.this, startPosition, finalPosition); + return null; + } + + @Override + public String getDescription() { + return "Text selecting"; + } + + @Override + public String toString() { + return "JTextComponentOperator.selectText.Action{description = " + getDescription() + '}'; + } + }, "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() { + @Override + public Void launch(Void obj) { + driver.clearText(JTextComponentOperator.this); + return null; + } + + @Override + public String getDescription() { + return "Text clearing"; + } + + @Override + public String toString() { + return "JTextComponentOperator.clearText.Action{description = " + getDescription() + '}'; + } + }, "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 + * {@code getText()} and {@code getDisplayedText()} are different + * if text component is used to display + * {@code 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() { + @Override + 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; + } + } + + @Override + public String getDescription() { + return ("Has \"" + text + "\" text starting from " + + Integer.toString(position) + " position"); + } + + @Override + public String toString() { + return "JTextComponentOperator.waitText.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + /** + * 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() { + @Override + public boolean checkComponent(Component comp) { + return getCaretPosition() == position; + } + + @Override + public String getDescription() { + return "Has caret at " + Integer.toString(position) + " position"; + } + + @Override + public String toString() { + return "JTextComponentOperator.waitCaretPosition.ComponentChooser{description = " + getDescription() + '}'; + } + }); + } + + @Override + 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 {@code JTextComponent.addCaretListener(CaretListener)} through queue + */ + public void addCaretListener(final CaretListener caretListener) { + runMapping(new MapVoidAction("addCaretListener") { + @Override + public void map() { + ((JTextComponent) getSource()).addCaretListener(caretListener); + } + }); + } + + /** + * Maps {@code JTextComponent.copy()} through queue + */ + public void copy() { + runMapping(new MapVoidAction("copy") { + @Override + public void map() { + ((JTextComponent) getSource()).copy(); + } + }); + } + + /** + * Maps {@code JTextComponent.cut()} through queue + */ + public void cut() { + runMapping(new MapVoidAction("cut") { + @Override + public void map() { + ((JTextComponent) getSource()).cut(); + } + }); + } + + /** + * Maps {@code JTextComponent.getActions()} through queue + */ + public javax.swing.Action[] getActions() { + return ((javax.swing.Action[]) runMapping(new MapAction("getActions") { + @Override + public Object map() { + return ((JTextComponent) getSource()).getActions(); + } + })); + } + + /** + * Maps {@code JTextComponent.getCaret()} through queue + */ + public Caret getCaret() { + return (runMapping(new MapAction("getCaret") { + @Override + public Caret map() { + return ((JTextComponent) getSource()).getCaret(); + } + })); + } + + /** + * Maps {@code JTextComponent.getCaretColor()} through queue + */ + public Color getCaretColor() { + return (runMapping(new MapAction("getCaretColor") { + @Override + public Color map() { + return ((JTextComponent) getSource()).getCaretColor(); + } + })); + } + + /** + * Maps {@code JTextComponent.getCaretPosition()} through queue + */ + public int getCaretPosition() { + return (runMapping(new MapIntegerAction("getCaretPosition") { + @Override + public int map() { + return ((JTextComponent) getSource()).getCaretPosition(); + } + })); + } + + /** + * Maps {@code JTextComponent.getDisabledTextColor()} through queue + */ + public Color getDisabledTextColor() { + return (runMapping(new MapAction("getDisabledTextColor") { + @Override + public Color map() { + return ((JTextComponent) getSource()).getDisabledTextColor(); + } + })); + } + + /** + * Maps {@code JTextComponent.getDocument()} through queue + */ + public Document getDocument() { + return (runMapping(new MapAction("getDocument") { + @Override + public Document map() { + return ((JTextComponent) getSource()).getDocument(); + } + })); + } + + /** + * Maps {@code JTextComponent.getFocusAccelerator()} through queue + */ + public char getFocusAccelerator() { + return (runMapping(new MapCharacterAction("getFocusAccelerator") { + @Override + public char map() { + return ((JTextComponent) getSource()).getFocusAccelerator(); + } + })); + } + + /** + * Maps {@code JTextComponent.getHighlighter()} through queue + */ + public Highlighter getHighlighter() { + return (runMapping(new MapAction("getHighlighter") { + @Override + public Highlighter map() { + return ((JTextComponent) getSource()).getHighlighter(); + } + })); + } + + /** + * Maps {@code JTextComponent.getKeymap()} through queue + */ + public Keymap getKeymap() { + return (runMapping(new MapAction("getKeymap") { + @Override + public Keymap map() { + return ((JTextComponent) getSource()).getKeymap(); + } + })); + } + + /** + * Maps {@code JTextComponent.getMargin()} through queue + */ + public Insets getMargin() { + return (runMapping(new MapAction("getMargin") { + @Override + public Insets map() { + return ((JTextComponent) getSource()).getMargin(); + } + })); + } + + /** + * Maps {@code JTextComponent.getPreferredScrollableViewportSize()} + * through queue + */ + public Dimension getPreferredScrollableViewportSize() { + return (runMapping(new MapAction("getPreferredScrollableViewportSize") { + @Override + public Dimension map() { + return ((JTextComponent) getSource()).getPreferredScrollableViewportSize(); + } + })); + } + + /** + * Maps + * {@code JTextComponent.getScrollableBlockIncrement(Rectangle, int, int)} + * through queue + */ + public int getScrollableBlockIncrement(final Rectangle rectangle, final int i, final int i1) { + return (runMapping(new MapIntegerAction("getScrollableBlockIncrement") { + @Override + public int map() { + return ((JTextComponent) getSource()).getScrollableBlockIncrement(rectangle, i, i1); + } + })); + } + + /** + * Maps {@code JTextComponent.getScrollableTracksViewportHeight()} + * through queue + */ + public boolean getScrollableTracksViewportHeight() { + return (runMapping(new MapBooleanAction("getScrollableTracksViewportHeight") { + @Override + public boolean map() { + return ((JTextComponent) getSource()).getScrollableTracksViewportHeight(); + } + })); + } + + /** + * Maps {@code JTextComponent.getScrollableTracksViewportWidth()} + * through queue + */ + public boolean getScrollableTracksViewportWidth() { + return (runMapping(new MapBooleanAction("getScrollableTracksViewportWidth") { + @Override + public boolean map() { + return ((JTextComponent) getSource()).getScrollableTracksViewportWidth(); + } + })); + } + + /** + * Maps + * {@code JTextComponent.getScrollableUnitIncrement(Rectangle, int, int)} + * through queue + */ + public int getScrollableUnitIncrement(final Rectangle rectangle, final int i, final int i1) { + return (runMapping(new MapIntegerAction("getScrollableUnitIncrement") { + @Override + public int map() { + return ((JTextComponent) getSource()).getScrollableUnitIncrement(rectangle, i, i1); + } + })); + } + + /** + * Maps {@code JTextComponent.getSelectedText()} through queue + */ + public String getSelectedText() { + return (runMapping(new MapAction("getSelectedText") { + @Override + public String map() { + return ((JTextComponent) getSource()).getSelectedText(); + } + })); + } + + /** + * Maps {@code JTextComponent.getSelectedTextColor()} through queue + */ + public Color getSelectedTextColor() { + return (runMapping(new MapAction("getSelectedTextColor") { + @Override + public Color map() { + return ((JTextComponent) getSource()).getSelectedTextColor(); + } + })); + } + + /** + * Maps {@code JTextComponent.getSelectionColor()} through queue + */ + public Color getSelectionColor() { + return (runMapping(new MapAction("getSelectionColor") { + @Override + public Color map() { + return ((JTextComponent) getSource()).getSelectionColor(); + } + })); + } + + /** + * Maps {@code JTextComponent.getSelectionEnd()} through queue + */ + public int getSelectionEnd() { + return (runMapping(new MapIntegerAction("getSelectionEnd") { + @Override + public int map() { + return ((JTextComponent) getSource()).getSelectionEnd(); + } + })); + } + + /** + * Maps {@code JTextComponent.getSelectionStart()} through queue + */ + public int getSelectionStart() { + return (runMapping(new MapIntegerAction("getSelectionStart") { + @Override + public int map() { + return ((JTextComponent) getSource()).getSelectionStart(); + } + })); + } + + /** + * Maps {@code JTextComponent.getText()} through queue + */ + public String getText() { + return (runMapping(new MapAction("getText") { + @Override + public String map() { + return ((JTextComponent) getSource()).getText(); + } + })); + } + + /** + * Maps {@code JTextComponent.getText(int, int)} through queue + */ + public String getText(final int i, final int i1) { + return (runMapping(new MapAction("getText") { + @Override + public String map() throws BadLocationException { + return ((JTextComponent) getSource()).getText(i, i1); + } + })); + } + + /** + * Maps {@code JTextComponent.getUI()} through queue + */ + public TextUI getUI() { + return (runMapping(new MapAction("getUI") { + @Override + public TextUI map() { + return ((JTextComponent) getSource()).getUI(); + } + })); + } + + /** + * Maps {@code JTextComponent.isEditable()} through queue + */ + public boolean isEditable() { + return (runMapping(new MapBooleanAction("isEditable") { + @Override + public boolean map() { + return ((JTextComponent) getSource()).isEditable(); + } + })); + } + + /** + * Maps {@code JTextComponent.modelToView(int)} through queue + */ + public Rectangle modelToView(final int i) { + return (runMapping(new MapAction("modelToView") { + @Override + public Rectangle map() throws BadLocationException { + return ((JTextComponent) getSource()).modelToView(i); + } + })); + } + + /** + * Maps {@code JTextComponent.moveCaretPosition(int)} through queue + */ + public void moveCaretPosition(final int i) { + runMapping(new MapVoidAction("moveCaretPosition") { + @Override + public void map() { + ((JTextComponent) getSource()).moveCaretPosition(i); + } + }); + } + + /** + * Maps {@code JTextComponent.paste()} through queue + */ + public void paste() { + runMapping(new MapVoidAction("paste") { + @Override + public void map() { + ((JTextComponent) getSource()).paste(); + } + }); + } + + /** + * Maps {@code JTextComponent.read(Reader, Object)} through queue + */ + public void read(final Reader reader, final Object object) { + runMapping(new MapVoidAction("read") { + @Override + public void map() throws IOException { + ((JTextComponent) getSource()).read(reader, object); + } + }); + } + + /** + * Maps {@code JTextComponent.removeCaretListener(CaretListener)} + * through queue + */ + public void removeCaretListener(final CaretListener caretListener) { + runMapping(new MapVoidAction("removeCaretListener") { + @Override + public void map() { + ((JTextComponent) getSource()).removeCaretListener(caretListener); + } + }); + } + + /** + * Maps {@code JTextComponent.replaceSelection(String)} through queue + */ + public void replaceSelection(final String string) { + runMapping(new MapVoidAction("replaceSelection") { + @Override + public void map() { + ((JTextComponent) getSource()).replaceSelection(string); + } + }); + } + + /** + * Maps {@code JTextComponent.select(int, int)} through queue + */ + public void select(final int i, final int i1) { + runMapping(new MapVoidAction("select") { + @Override + public void map() { + ((JTextComponent) getSource()).select(i, i1); + } + }); + } + + /** + * Maps {@code JTextComponent.selectAll()} through queue + */ + public void selectAll() { + runMapping(new MapVoidAction("selectAll") { + @Override + public void map() { + ((JTextComponent) getSource()).selectAll(); + } + }); + } + + /** + * Maps {@code JTextComponent.setCaret(Caret)} through queue + */ + public void setCaret(final Caret caret) { + runMapping(new MapVoidAction("setCaret") { + @Override + public void map() { + ((JTextComponent) getSource()).setCaret(caret); + } + }); + } + + /** + * Maps {@code JTextComponent.setCaretColor(Color)} through queue + */ + public void setCaretColor(final Color color) { + runMapping(new MapVoidAction("setCaretColor") { + @Override + public void map() { + ((JTextComponent) getSource()).setCaretColor(color); + } + }); + } + + /** + * Maps {@code JTextComponent.setCaretPosition(int)} through queue + */ + public void setCaretPosition(final int i) { + runMapping(new MapVoidAction("setCaretPosition") { + @Override + public void map() { + ((JTextComponent) getSource()).setCaretPosition(i); + } + }); + } + + /** + * Maps {@code JTextComponent.setDisabledTextColor(Color)} through queue + */ + public void setDisabledTextColor(final Color color) { + runMapping(new MapVoidAction("setDisabledTextColor") { + @Override + public void map() { + ((JTextComponent) getSource()).setDisabledTextColor(color); + } + }); + } + + /** + * Maps {@code JTextComponent.setDocument(Document)} through queue + */ + public void setDocument(final Document document) { + runMapping(new MapVoidAction("setDocument") { + @Override + public void map() { + ((JTextComponent) getSource()).setDocument(document); + } + }); + } + + /** + * Maps {@code JTextComponent.setEditable(boolean)} through queue + */ + public void setEditable(final boolean b) { + runMapping(new MapVoidAction("setEditable") { + @Override + public void map() { + ((JTextComponent) getSource()).setEditable(b); + } + }); + } + + /** + * Maps {@code JTextComponent.setFocusAccelerator(char)} through queue + */ + public void setFocusAccelerator(final char c) { + runMapping(new MapVoidAction("setFocusAccelerator") { + @Override + public void map() { + ((JTextComponent) getSource()).setFocusAccelerator(c); + } + }); + } + + /** + * Maps {@code JTextComponent.setHighlighter(Highlighter)} through queue + */ + public void setHighlighter(final Highlighter highlighter) { + runMapping(new MapVoidAction("setHighlighter") { + @Override + public void map() { + ((JTextComponent) getSource()).setHighlighter(highlighter); + } + }); + } + + /** + * Maps {@code JTextComponent.setKeymap(Keymap)} through queue + */ + public void setKeymap(final Keymap keymap) { + runMapping(new MapVoidAction("setKeymap") { + @Override + public void map() { + ((JTextComponent) getSource()).setKeymap(keymap); + } + }); + } + + /** + * Maps {@code JTextComponent.setMargin(Insets)} through queue + */ + public void setMargin(final Insets insets) { + runMapping(new MapVoidAction("setMargin") { + @Override + public void map() { + ((JTextComponent) getSource()).setMargin(insets); + } + }); + } + + /** + * Maps {@code JTextComponent.setSelectedTextColor(Color)} through queue + */ + public void setSelectedTextColor(final Color color) { + runMapping(new MapVoidAction("setSelectedTextColor") { + @Override + public void map() { + ((JTextComponent) getSource()).setSelectedTextColor(color); + } + }); + } + + /** + * Maps {@code JTextComponent.setSelectionColor(Color)} through queue + */ + public void setSelectionColor(final Color color) { + runMapping(new MapVoidAction("setSelectionColor") { + @Override + public void map() { + ((JTextComponent) getSource()).setSelectionColor(color); + } + }); + } + + /** + * Maps {@code JTextComponent.setSelectionEnd(int)} through queue + */ + public void setSelectionEnd(final int i) { + runMapping(new MapVoidAction("setSelectionEnd") { + @Override + public void map() { + ((JTextComponent) getSource()).setSelectionEnd(i); + } + }); + } + + /** + * Maps {@code JTextComponent.setSelectionStart(int)} through queue + */ + public void setSelectionStart(final int i) { + runMapping(new MapVoidAction("setSelectionStart") { + @Override + public void map() { + ((JTextComponent) getSource()).setSelectionStart(i); + } + }); + } + + /** + * Maps {@code JTextComponent.setText(String)} through queue + */ + public void setText(final String string) { + runMapping(new MapVoidAction("setText") { + @Override + public void map() { + ((JTextComponent) getSource()).setText(string); + } + }); + } + + /** + * Maps {@code JTextComponent.setUI(TextUI)} through queue + */ + public void setUI(final TextUI textUI) { + runMapping(new MapVoidAction("setUI") { + @Override + public void map() { + ((JTextComponent) getSource()).setUI(textUI); + } + }); + } + + /** + * Maps {@code JTextComponent.viewToModel(Point)} through queue + */ + public int viewToModel(final Point point) { + return (runMapping(new MapIntegerAction("viewToModel") { + @Override + public int map() { + return ((JTextComponent) getSource()).viewToModel(point); + } + })); + } + + /** + * Maps {@code JTextComponent.write(Writer)} through queue + */ + public void write(final Writer writer) { + runMapping(new MapVoidAction("write") { + @Override + 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 { + + private static final long serialVersionUID = 42L; + + /** + * 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()); + } + + @Override + public boolean checkComponent(Component comp) { + if (comp instanceof JTextComponent) { + if (((JTextComponent) comp).getText() != null) { + return (comparator.equals(((JTextComponent) comp).getText(), + label)); + } + } + return false; + } + + @Override + public String getDescription() { + return "JTextComponent with text \"" + label + "\""; + } + + @Override + public String toString() { + return "JTextComponentByTextFinder{" + "label=" + label + ", comparator=" + comparator + '}'; + } + } + + /** + * 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JTextFieldOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JTextFieldOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,451 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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. + */ + @Override + public void waitText(String text, int position) { + super.waitText(removeNewLines(text), position); + } + + /** + * Wait some text to be displayed. + * + * @param text a text to wait. + */ + @Override + public void waitText(String text) { + super.waitText(removeNewLines(text)); + } + + //////////////////////////////////////////////////////// + //Mapping // + /** + * Maps {@code JTextField.addActionListener(ActionListener)} through queue + */ + public void addActionListener(final ActionListener actionListener) { + runMapping(new MapVoidAction("addActionListener") { + @Override + public void map() { + ((JTextField) getSource()).addActionListener(actionListener); + } + }); + } + + /** + * Maps {@code JTextField.getColumns()} through queue + */ + public int getColumns() { + return (runMapping(new MapIntegerAction("getColumns") { + @Override + public int map() { + return ((JTextField) getSource()).getColumns(); + } + })); + } + + /** + * Maps {@code JTextField.getHorizontalAlignment()} through queue + */ + public int getHorizontalAlignment() { + return (runMapping(new MapIntegerAction("getHorizontalAlignment") { + @Override + public int map() { + return ((JTextField) getSource()).getHorizontalAlignment(); + } + })); + } + + /** + * Maps {@code JTextField.getHorizontalVisibility()} through queue + */ + public BoundedRangeModel getHorizontalVisibility() { + return (runMapping(new MapAction("getHorizontalVisibility") { + @Override + public BoundedRangeModel map() { + return ((JTextField) getSource()).getHorizontalVisibility(); + } + })); + } + + /** + * Maps {@code JTextField.getScrollOffset()} through queue + */ + public int getScrollOffset() { + return (runMapping(new MapIntegerAction("getScrollOffset") { + @Override + public int map() { + return ((JTextField) getSource()).getScrollOffset(); + } + })); + } + + /** + * Maps {@code JTextField.postActionEvent()} through queue + */ + public void postActionEvent() { + runMapping(new MapVoidAction("postActionEvent") { + @Override + public void map() { + ((JTextField) getSource()).postActionEvent(); + } + }); + } + + /** + * Maps {@code JTextField.removeActionListener(ActionListener)} through queue + */ + public void removeActionListener(final ActionListener actionListener) { + runMapping(new MapVoidAction("removeActionListener") { + @Override + public void map() { + ((JTextField) getSource()).removeActionListener(actionListener); + } + }); + } + + /** + * Maps {@code JTextField.setActionCommand(String)} through queue + */ + public void setActionCommand(final String string) { + runMapping(new MapVoidAction("setActionCommand") { + @Override + public void map() { + ((JTextField) getSource()).setActionCommand(string); + } + }); + } + + /** + * Maps {@code JTextField.setColumns(int)} through queue + */ + public void setColumns(final int i) { + runMapping(new MapVoidAction("setColumns") { + @Override + public void map() { + ((JTextField) getSource()).setColumns(i); + } + }); + } + + /** + * Maps {@code JTextField.setHorizontalAlignment(int)} through queue + */ + public void setHorizontalAlignment(final int i) { + runMapping(new MapVoidAction("setHorizontalAlignment") { + @Override + public void map() { + ((JTextField) getSource()).setHorizontalAlignment(i); + } + }); + } + + /** + * Maps {@code JTextField.setScrollOffset(int)} through queue + */ + public void setScrollOffset(final int i) { + runMapping(new MapVoidAction("setScrollOffset") { + @Override + 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); + } + } +} diff -r 64f6ae06310e -r eda408d4f253 jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JTextPaneOperator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/sanity/client/lib/jemmy/src/org/netbeans/jemmy/operators/JTextPaneOperator.java Tue Apr 05 15:39:35 2016 -0400 @@ -0,0 +1,450 @@ +/* + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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@oracle.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 {@code JTextPane.addStyle(String, Style)} through queue + */ + public Style addStyle(final String string, final Style style) { + return (runMapping(new MapAction