diff --git a/.hgtags b/.hgtags index 36ba8ab267f..f50083fb987 100644 --- a/.hgtags +++ b/.hgtags @@ -256,3 +256,5 @@ efe7dbc6088691757404e0c8745f894e3ca9c022 jdk9-b09 0809c9a4d36e6291f1c4384604c4bbf29e975722 jdk9-b11 0d1f816217dce5e72187f167cc1816080cbeb453 jdk9-b12 1a30593dcb9802faec3b6edb24d86ca088594e4e jdk9-b13 +97932f6ad950ae5a73a9da5c96e6e58503ff646b jdk9-b14 +74eb0778e4f2dbff6628e718378449fba27c4265 jdk9-b15 diff --git a/.hgtags-top-repo b/.hgtags-top-repo index 3a93d7b6efe..e60713ac318 100644 --- a/.hgtags-top-repo +++ b/.hgtags-top-repo @@ -256,3 +256,5 @@ fa13f2b926f8426876ec03e7903f3ee0ee150f2e jdk9-b10 ab55a18a95e1990a588929d5d29db3eb9985fea0 jdk9-b11 59f6350295f9681fe5956d8bc889bf341914c6cb jdk9-b12 5800456add07e1a68170a229fb5e27376f8875e5 jdk9-b13 +4e3aa9723e9972623e3dafc321b368e7db7e9b3b jdk9-b14 +b114474fb25af4e73cb7219f7c04bd8994da03a5 jdk9-b15 diff --git a/README b/README index 40c9fbc6a77..e1fdec5d4ab 100644 --- a/README +++ b/README @@ -1,15 +1,15 @@ README: This file should be located at the top of the OpenJDK Mercurial root repository. A full OpenJDK repository set (forest) should also include - the following 6 nested repositories: - "jdk", "hotspot", "langtools", "corba", "jaxws" and "jaxp". + the following 7 nested repositories: + "jdk", "hotspot", "langtools", "nashorn", "corba", "jaxws" and "jaxp". The root repository can be obtained with something like: - hg clone http://hg.openjdk.java.net/jdk8/jdk8 openjdk8 + hg clone http://hg.openjdk.java.net/jdk9/jdk9 openjdk9 You can run the get_source.sh script located in the root repository to get the other needed repositories: - cd openjdk8 && sh ./get_source.sh + cd openjdk9 && sh ./get_source.sh People unfamiliar with Mercurial should read the first few chapters of the Mercurial book: http://hgbook.red-bean.com/read/ @@ -19,9 +19,9 @@ README: Simple Build Instructions: 0. Get the necessary system software/packages installed on your system, see - http://hg.openjdk.java.net/jdk8/jdk8/raw-file/tip/README-builds.html + http://hg.openjdk.java.net/jdk9/jdk9/raw-file/tip/README-builds.html - 1. If you don't have a jdk7u7 or newer jdk, download and install it from + 1. If you don't have a jdk8 or newer jdk, download and install it from http://java.sun.com/javase/downloads/index.jsp Add the /bin directory of this installation to your PATH environment variable. @@ -37,4 +37,4 @@ where make is GNU make 3.81 or newer, /usr/bin/make on Linux usually is 3.81 or newer. Note that on Solaris, GNU make is called "gmake". Complete details are available in the file: - http://hg.openjdk.java.net/jdk8/jdk8/raw-file/tip/README-builds.html + http://hg.openjdk.java.net/jdk9/jdk9/raw-file/tip/README-builds.html diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh index d36e2e5b486..86905690fb7 100644 --- a/common/autoconf/generated-configure.sh +++ b/common/autoconf/generated-configure.sh @@ -656,6 +656,9 @@ USE_EXTERNAL_LIBZ USE_EXTERNAL_LIBPNG PNG_LIBS PNG_CFLAGS +USE_EXTERNAL_LCMS +LCMS_LIBS +LCMS_CFLAGS USE_EXTERNAL_LIBGIF USE_EXTERNAL_LIBJPEG ALSA_LIBS @@ -1079,6 +1082,7 @@ with_alsa with_alsa_include with_alsa_lib with_giflib +with_lcms with_libpng with_zlib with_stdc__lib @@ -1192,6 +1196,8 @@ FREETYPE_CFLAGS FREETYPE_LIBS ALSA_CFLAGS ALSA_LIBS +LCMS_CFLAGS +LCMS_LIBS PNG_CFLAGS PNG_LIBS LIBFFI_CFLAGS @@ -1934,6 +1940,8 @@ Optional Packages: --with-alsa-lib specify directory for the alsa library --with-giflib use giflib from build system or OpenJDK source (system, bundled) [bundled] + --with-lcms use lcms2 from build system or OpenJDK source + (system, bundled) [bundled] --with-libpng use libpng from build system or OpenJDK source (system, bundled) [bundled] --with-zlib use zlib from build system or OpenJDK source @@ -2060,6 +2068,8 @@ Some influential environment variables: linker flags for FREETYPE, overriding pkg-config ALSA_CFLAGS C compiler flags for ALSA, overriding pkg-config ALSA_LIBS linker flags for ALSA, overriding pkg-config + LCMS_CFLAGS C compiler flags for LCMS, overriding pkg-config + LCMS_LIBS linker flags for LCMS, overriding pkg-config PNG_CFLAGS C compiler flags for PNG, overriding pkg-config PNG_LIBS linker flags for PNG, overriding pkg-config LIBFFI_CFLAGS @@ -47307,6 +47317,115 @@ fi fi + ############################################################################### + # + # Check for the lcms2 library + # + + +# Check whether --with-lcms was given. +if test "${with_lcms+set}" = set; then : + withval=$with_lcms; +fi + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for which lcms to use" >&5 +$as_echo_n "checking for which lcms to use... " >&6; } + + DEFAULT_LCMS=bundled + + # + # If user didn't specify, use DEFAULT_LCMS + # + if test "x${with_lcms}" = "x"; then + with_lcms=${DEFAULT_LCMS} + fi + + if test "x${with_lcms}" = "xbundled"; then + USE_EXTERNAL_LCMS=false + { $as_echo "$as_me:${as_lineno-$LINENO}: result: bundled" >&5 +$as_echo "bundled" >&6; } + elif test "x${with_lcms}" = "xsystem"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: system" >&5 +$as_echo "system" >&6; } + +pkg_failed=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for LCMS" >&5 +$as_echo_n "checking for LCMS... " >&6; } + +if test -n "$LCMS_CFLAGS"; then + pkg_cv_LCMS_CFLAGS="$LCMS_CFLAGS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"lcms2\""; } >&5 + ($PKG_CONFIG --exists --print-errors "lcms2") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_LCMS_CFLAGS=`$PKG_CONFIG --cflags "lcms2" 2>/dev/null` +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi +if test -n "$LCMS_LIBS"; then + pkg_cv_LCMS_LIBS="$LCMS_LIBS" + elif test -n "$PKG_CONFIG"; then + if test -n "$PKG_CONFIG" && \ + { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"lcms2\""; } >&5 + ($PKG_CONFIG --exists --print-errors "lcms2") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then + pkg_cv_LCMS_LIBS=`$PKG_CONFIG --libs "lcms2" 2>/dev/null` +else + pkg_failed=yes +fi + else + pkg_failed=untried +fi + + + +if test $pkg_failed = yes; then + +if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then + _pkg_short_errors_supported=yes +else + _pkg_short_errors_supported=no +fi + if test $_pkg_short_errors_supported = yes; then + LCMS_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors "lcms2" 2>&1` + else + LCMS_PKG_ERRORS=`$PKG_CONFIG --print-errors "lcms2" 2>&1` + fi + # Put the nasty error message in config.log where it belongs + echo "$LCMS_PKG_ERRORS" >&5 + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + LCMS_FOUND=no +elif test $pkg_failed = untried; then + LCMS_FOUND=no +else + LCMS_CFLAGS=$pkg_cv_LCMS_CFLAGS + LCMS_LIBS=$pkg_cv_LCMS_LIBS + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + LCMS_FOUND=yes +fi + if test "x${LCMS_FOUND}" = "xyes"; then + USE_EXTERNAL_LCMS=true + else + as_fn_error $? "--with-lcms=system specified, but no lcms found!" "$LINENO" 5 + fi + else + as_fn_error $? "Invalid value for --with-lcms: ${with_lcms}, use 'system' or 'bundled'" "$LINENO" 5 + fi + + + ############################################################################### # # Check for the png library diff --git a/common/autoconf/libraries.m4 b/common/autoconf/libraries.m4 index 88bdfe30de3..6ee3221ad96 100644 --- a/common/autoconf/libraries.m4 +++ b/common/autoconf/libraries.m4 @@ -664,6 +664,42 @@ AC_DEFUN_ONCE([LIB_SETUP_MISC_LIBS], fi AC_SUBST(USE_EXTERNAL_LIBGIF) + ############################################################################### + # + # Check for the lcms2 library + # + + AC_ARG_WITH(lcms, [AS_HELP_STRING([--with-lcms], + [use lcms2 from build system or OpenJDK source (system, bundled) @<:@bundled@:>@])]) + + AC_MSG_CHECKING([for which lcms to use]) + + DEFAULT_LCMS=bundled + + # + # If user didn't specify, use DEFAULT_LCMS + # + if test "x${with_lcms}" = "x"; then + with_lcms=${DEFAULT_LCMS} + fi + + if test "x${with_lcms}" = "xbundled"; then + USE_EXTERNAL_LCMS=false + AC_MSG_RESULT([bundled]) + elif test "x${with_lcms}" = "xsystem"; then + AC_MSG_RESULT([system]) + PKG_CHECK_MODULES([LCMS], [lcms2], [LCMS_FOUND=yes], [LCMS_FOUND=no]) + if test "x${LCMS_FOUND}" = "xyes"; then + USE_EXTERNAL_LCMS=true + else + AC_MSG_ERROR([--with-lcms=system specified, but no lcms found!]) + fi + else + AC_MSG_ERROR([Invalid value for --with-lcms: ${with_lcms}, use 'system' or 'bundled']) + fi + + AC_SUBST(USE_EXTERNAL_LCMS) + ############################################################################### # # Check for the png library diff --git a/common/autoconf/spec.gmk.in b/common/autoconf/spec.gmk.in index 47861fcf2b8..2f6d7bd3746 100644 --- a/common/autoconf/spec.gmk.in +++ b/common/autoconf/spec.gmk.in @@ -652,6 +652,10 @@ INSTALL_SYSCONFDIR=@sysconfdir@ # Libraries # +USE_EXTERNAL_LCMS:=@USE_EXTERNAL_LCMS@ +LCMS_CFLAGS:=@LCMS_CFLAGS@ +LCMS_LIBS:=@LCMS_LIBS@ + USE_EXTERNAL_LIBPNG:=@USE_EXTERNAL_LIBPNG@ PNG_LIBS:=@PNG_LIBS@ PNG_CFLAGS:=@PNG_CFLAGS@ diff --git a/corba/.hgtags b/corba/.hgtags index 18cf4e05c86..29ff1978725 100644 --- a/corba/.hgtags +++ b/corba/.hgtags @@ -256,3 +256,5 @@ a4bf701ac316946c2e5e83138ad8e687da6a4b30 jdk9-b06 77ea0a2503582a28e4e66be7239a49a0d1dd313f jdk9-b11 e212cdcc8c11f0ba5acf6f5ddb596c4c545a93f9 jdk9-b12 088eec4c36f4d7f250fcd19c4969bf698e3d2cdc jdk9-b13 +a2b82f863ba95a596da555a4c1b871c404863e7e jdk9-b14 +e54022d0dd92106fff7f7fe670010cd7e6517ee3 jdk9-b15 diff --git a/hotspot/.hgtags b/hotspot/.hgtags index 97ea5ccc8bc..ab6aa356e85 100644 --- a/hotspot/.hgtags +++ b/hotspot/.hgtags @@ -416,3 +416,5 @@ ebc44d040cd149d2120d69fe183a3dae7840f4b4 jdk9-b10 783309c3a1a629a452673399dcfa83ef7eca94d8 jdk9-b11 1c383bb39e2849ca62cb763f4e182a29b421d60a jdk9-b12 456ad9c99133803d4e1433124c85a6fd141b9ac9 jdk9-b13 +bd333491bb6c012d7b606939406d0fa9a5ac7ffd jdk9-b14 +170f6d733d7aec062f743a6b8c1cce940a7a984a jdk9-b15 diff --git a/hotspot/src/share/vm/classfile/classLoaderData.cpp b/hotspot/src/share/vm/classfile/classLoaderData.cpp index 54f2225d3fe..bc88beb4343 100644 --- a/hotspot/src/share/vm/classfile/classLoaderData.cpp +++ b/hotspot/src/share/vm/classfile/classLoaderData.cpp @@ -274,6 +274,8 @@ void ClassLoaderData::add_class(Klass* k) { MutexLockerEx ml(metaspace_lock(), Mutex::_no_safepoint_check_flag); Klass* old_value = _klasses; k->set_next_link(old_value); + // Make sure linked class is stable, since the class list is walked without a lock + OrderAccess::storestore(); // link the new item into the list _klasses = k; diff --git a/hotspot/src/share/vm/classfile/verifier.cpp b/hotspot/src/share/vm/classfile/verifier.cpp index 923a6f70d2c..c7eca2d011b 100644 --- a/hotspot/src/share/vm/classfile/verifier.cpp +++ b/hotspot/src/share/vm/classfile/verifier.cpp @@ -2036,7 +2036,7 @@ void ClassVerifier::verify_switch( while ((bcp + padding_offset) < aligned_bcp) { if(*(bcp + padding_offset) != 0) { verify_error(ErrorContext::bad_code(bci), - "Nonzero padding byte in lookswitch or tableswitch"); + "Nonzero padding byte in lookupswitch or tableswitch"); return; } padding_offset++; diff --git a/hotspot/src/share/vm/compiler/compilerOracle.cpp b/hotspot/src/share/vm/compiler/compilerOracle.cpp index c58fb169309..b646158af28 100644 --- a/hotspot/src/share/vm/compiler/compilerOracle.cpp +++ b/hotspot/src/share/vm/compiler/compilerOracle.cpp @@ -307,6 +307,9 @@ bool CompilerOracle::should_print(methodHandle method) { return (check_predicate(PrintCommand, method)); } +bool CompilerOracle::should_print_methods() { + return lists[PrintCommand] != NULL; +} bool CompilerOracle::should_log(methodHandle method) { if (!LogCompilation) return false; diff --git a/hotspot/src/share/vm/compiler/compilerOracle.hpp b/hotspot/src/share/vm/compiler/compilerOracle.hpp index f736a4eebfc..df025f76be5 100644 --- a/hotspot/src/share/vm/compiler/compilerOracle.hpp +++ b/hotspot/src/share/vm/compiler/compilerOracle.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -73,6 +73,9 @@ class CompilerOracle : AllStatic { // For updating the oracle file static void append_comment_to_file(const char* message); static void append_exclude_to_file(methodHandle method); + + // Tells whether there are any methods to print for print_method_statistics() + static bool should_print_methods(); }; #endif // SHARE_VM_COMPILER_COMPILERORACLE_HPP diff --git a/hotspot/src/share/vm/memory/metaspace.cpp b/hotspot/src/share/vm/memory/metaspace.cpp index 11e72d4ed27..cd5fceff2d0 100644 --- a/hotspot/src/share/vm/memory/metaspace.cpp +++ b/hotspot/src/share/vm/memory/metaspace.cpp @@ -3095,7 +3095,7 @@ void Metaspace::ergo_initialize() { void Metaspace::global_initialize() { // Initialize the alignment for shared spaces. - int max_alignment = os::vm_page_size(); + int max_alignment = os::vm_allocation_granularity(); size_t cds_total = 0; MetaspaceShared::set_max_alignment(max_alignment); diff --git a/hotspot/src/share/vm/oops/instanceKlass.cpp b/hotspot/src/share/vm/oops/instanceKlass.cpp index 9c4c9b8fbf5..34907dd55a5 100644 --- a/hotspot/src/share/vm/oops/instanceKlass.cpp +++ b/hotspot/src/share/vm/oops/instanceKlass.cpp @@ -1273,6 +1273,12 @@ bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDesc void InstanceKlass::methods_do(void f(Method* method)) { + // Methods aren't stable until they are loaded. This can be read outside + // a lock through the ClassLoaderData for profiling + if (!is_loaded()) { + return; + } + int len = methods()->length(); for (int index = 0; index < len; index++) { Method* m = methods()->at(index); diff --git a/hotspot/src/share/vm/prims/jvmtiEnv.cpp b/hotspot/src/share/vm/prims/jvmtiEnv.cpp index 6dcf2e1bf95..765cbcd6290 100644 --- a/hotspot/src/share/vm/prims/jvmtiEnv.cpp +++ b/hotspot/src/share/vm/prims/jvmtiEnv.cpp @@ -307,9 +307,9 @@ JvmtiEnv::GetObjectSize(jobject object, jlong* size_ptr) { !java_lang_Class::is_primitive(mirror)) { Klass* k = java_lang_Class::as_Klass(mirror); assert(k != NULL, "class for non-primitive mirror must exist"); - *size_ptr = k->size() * wordSize; + *size_ptr = (jlong)k->size() * wordSize; } else { - *size_ptr = mirror->size() * wordSize; + *size_ptr = (jlong)mirror->size() * wordSize; } return JVMTI_ERROR_NONE; } /* end GetObjectSize */ diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp index 5ebe1cf251c..91e485e7aed 100644 --- a/hotspot/src/share/vm/runtime/arguments.cpp +++ b/hotspot/src/share/vm/runtime/arguments.cpp @@ -1449,7 +1449,7 @@ bool verify_object_alignment() { return true; } -uintx Arguments::max_heap_for_compressed_oops() { +size_t Arguments::max_heap_for_compressed_oops() { // Avoid sign flip. assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size"); // We need to fit both the NULL page and the heap into the memory budget, while diff --git a/hotspot/src/share/vm/runtime/java.cpp b/hotspot/src/share/vm/runtime/java.cpp index 7ba83996f46..e852b56ef54 100644 --- a/hotspot/src/share/vm/runtime/java.cpp +++ b/hotspot/src/share/vm/runtime/java.cpp @@ -120,7 +120,8 @@ void collect_profiled_methods(Method* m) { } void print_method_profiling_data() { - if (ProfileInterpreter COMPILER1_PRESENT(|| C1UpdateMethodData)) { + if (ProfileInterpreter COMPILER1_PRESENT(|| C1UpdateMethodData) && + (PrintMethodData || CompilerOracle::should_print_methods())) { ResourceMark rm; HandleMark hm; collected_profiled_methods = new GrowableArray(1024); diff --git a/hotspot/src/share/vm/runtime/sharedRuntimeMath.hpp b/hotspot/src/share/vm/runtime/sharedRuntimeMath.hpp new file mode 100644 index 00000000000..4259227c3b3 --- /dev/null +++ b/hotspot/src/share/vm/runtime/sharedRuntimeMath.hpp @@ -0,0 +1,97 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#ifndef SHARE_VM_RUNTIME_SHAREDRUNTIMEMATH_HPP +#define SHARE_VM_RUNTIME_SHAREDRUNTIMEMATH_HPP + +#include + +// VM_LITTLE_ENDIAN is #defined appropriately in the Makefiles +// [jk] this is not 100% correct because the float word order may different +// from the byte order (e.g. on ARM FPA) +#ifdef VM_LITTLE_ENDIAN +# define __HI(x) *(1+(int*)&x) +# define __LO(x) *(int*)&x +#else +# define __HI(x) *(int*)&x +# define __LO(x) *(1+(int*)&x) +#endif + +static double copysignA(double x, double y) { + __HI(x) = (__HI(x)&0x7fffffff)|(__HI(y)&0x80000000); + return x; +} + +/* + * ==================================================== + * Copyright (c) 1998 Oracle and/or its affiliates. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +/* + * scalbn (double x, int n) + * scalbn(x,n) returns x* 2**n computed by exponent + * manipulation rather than by actually performing an + * exponentiation or a multiplication. + */ + +static const double +two54 = 1.80143985094819840000e+16, /* 0x43500000, 0x00000000 */ +twom54 = 5.55111512312578270212e-17, /* 0x3C900000, 0x00000000 */ +hugeX = 1.0e+300, +tiny = 1.0e-300; + +static double scalbnA (double x, int n) { + int k,hx,lx; + hx = __HI(x); + lx = __LO(x); + k = (hx&0x7ff00000)>>20; /* extract exponent */ + if (k==0) { /* 0 or subnormal x */ + if ((lx|(hx&0x7fffffff))==0) return x; /* +-0 */ + x *= two54; + hx = __HI(x); + k = ((hx&0x7ff00000)>>20) - 54; + if (n< -50000) return tiny*x; /*underflow*/ + } + if (k==0x7ff) return x+x; /* NaN or Inf */ + k = k+n; + if (k > 0x7fe) return hugeX*copysignA(hugeX,x); /* overflow */ + if (k > 0) /* normal result */ + {__HI(x) = (hx&0x800fffff)|(k<<20); return x;} + if (k <= -54) { + if (n > 50000) /* in case integer overflow in n+k */ + return hugeX*copysignA(hugeX,x); /*overflow*/ + else return tiny*copysignA(tiny,x); /*underflow*/ + } + k += 54; /* subnormal result */ + __HI(x) = (hx&0x800fffff)|(k<<20); + return x*twom54; +} + +#endif // SHARE_VM_RUNTIME_SHAREDRUNTIMEMATH_HPP diff --git a/hotspot/src/share/vm/runtime/sharedRuntimeTrans.cpp b/hotspot/src/share/vm/runtime/sharedRuntimeTrans.cpp index c5fb4e2e3e4..69feb28bdfb 100644 --- a/hotspot/src/share/vm/runtime/sharedRuntimeTrans.cpp +++ b/hotspot/src/share/vm/runtime/sharedRuntimeTrans.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -43,78 +43,7 @@ # pragma optimize ( "", off ) #endif -#include - -// VM_LITTLE_ENDIAN is #defined appropriately in the Makefiles -// [jk] this is not 100% correct because the float word order may different -// from the byte order (e.g. on ARM) -#ifdef VM_LITTLE_ENDIAN -# define __HI(x) *(1+(int*)&x) -# define __LO(x) *(int*)&x -#else -# define __HI(x) *(int*)&x -# define __LO(x) *(1+(int*)&x) -#endif - -#if !defined(AIX) -double copysign(double x, double y) { - __HI(x) = (__HI(x)&0x7fffffff)|(__HI(y)&0x80000000); - return x; -} -#endif - -/* - * ==================================================== - * Copyright (c) 1998 Oracle and/or its affiliates. All rights reserved. - * - * Developed at SunSoft, a Sun Microsystems, Inc. business. - * Permission to use, copy, modify, and distribute this - * software is freely granted, provided that this notice - * is preserved. - * ==================================================== - */ - -/* - * scalbn (double x, int n) - * scalbn(x,n) returns x* 2**n computed by exponent - * manipulation rather than by actually performing an - * exponentiation or a multiplication. - */ - -static const double -two54 = 1.80143985094819840000e+16, /* 0x43500000, 0x00000000 */ - twom54 = 5.55111512312578270212e-17, /* 0x3C900000, 0x00000000 */ - hugeX = 1.0e+300, - tiny = 1.0e-300; - -#if !defined(AIX) -double scalbn (double x, int n) { - int k,hx,lx; - hx = __HI(x); - lx = __LO(x); - k = (hx&0x7ff00000)>>20; /* extract exponent */ - if (k==0) { /* 0 or subnormal x */ - if ((lx|(hx&0x7fffffff))==0) return x; /* +-0 */ - x *= two54; - hx = __HI(x); - k = ((hx&0x7ff00000)>>20) - 54; - if (n< -50000) return tiny*x; /*underflow*/ - } - if (k==0x7ff) return x+x; /* NaN or Inf */ - k = k+n; - if (k > 0x7fe) return hugeX*copysign(hugeX,x); /* overflow */ - if (k > 0) /* normal result */ - {__HI(x) = (hx&0x800fffff)|(k<<20); return x;} - if (k <= -54) { - if (n > 50000) /* in case integer overflow in n+k */ - return hugeX*copysign(hugeX,x); /*overflow*/ - else return tiny*copysign(tiny,x); /*underflow*/ - } - k += 54; /* subnormal result */ - __HI(x) = (hx&0x800fffff)|(k<<20); - return x*twom54; -} -#endif +#include "runtime/sharedRuntimeMath.hpp" /* __ieee754_log(x) * Return the logarithm of x @@ -719,7 +648,7 @@ double __ieee754_pow(double x, double y) { z = one-(r-z); j = __HI(z); j += (n<<20); - if((j>>20)<=0) z = scalbn(z,n); /* subnormal output */ + if((j>>20)<=0) z = scalbnA(z,n); /* subnormal output */ else __HI(z) += (n<<20); return s*z; } diff --git a/hotspot/src/share/vm/runtime/sharedRuntimeTrig.cpp b/hotspot/src/share/vm/runtime/sharedRuntimeTrig.cpp index 7c499d84165..1691bdf7690 100644 --- a/hotspot/src/share/vm/runtime/sharedRuntimeTrig.cpp +++ b/hotspot/src/share/vm/runtime/sharedRuntimeTrig.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -63,63 +63,7 @@ #define SAFEBUF #endif -#include - -// VM_LITTLE_ENDIAN is #defined appropriately in the Makefiles -// [jk] this is not 100% correct because the float word order may different -// from the byte order (e.g. on ARM) -#ifdef VM_LITTLE_ENDIAN -# define __HI(x) *(1+(int*)&x) -# define __LO(x) *(int*)&x -#else -# define __HI(x) *(int*)&x -# define __LO(x) *(1+(int*)&x) -#endif - -static double copysignA(double x, double y) { - __HI(x) = (__HI(x)&0x7fffffff)|(__HI(y)&0x80000000); - return x; -} - -/* - * scalbn (double x, int n) - * scalbn(x,n) returns x* 2**n computed by exponent - * manipulation rather than by actually performing an - * exponentiation or a multiplication. - */ - -static const double -two54 = 1.80143985094819840000e+16, /* 0x43500000, 0x00000000 */ -twom54 = 5.55111512312578270212e-17, /* 0x3C900000, 0x00000000 */ -hugeX = 1.0e+300, -tiny = 1.0e-300; - -static double scalbnA (double x, int n) { - int k,hx,lx; - hx = __HI(x); - lx = __LO(x); - k = (hx&0x7ff00000)>>20; /* extract exponent */ - if (k==0) { /* 0 or subnormal x */ - if ((lx|(hx&0x7fffffff))==0) return x; /* +-0 */ - x *= two54; - hx = __HI(x); - k = ((hx&0x7ff00000)>>20) - 54; - if (n< -50000) return tiny*x; /*underflow*/ - } - if (k==0x7ff) return x+x; /* NaN or Inf */ - k = k+n; - if (k > 0x7fe) return hugeX*copysignA(hugeX,x); /* overflow */ - if (k > 0) /* normal result */ - {__HI(x) = (hx&0x800fffff)|(k<<20); return x;} - if (k <= -54) { - if (n > 50000) /* in case integer overflow in n+k */ - return hugeX*copysignA(hugeX,x); /*overflow*/ - else return tiny*copysignA(tiny,x); /*underflow*/ - } - k += 54; /* subnormal result */ - __HI(x) = (hx&0x800fffff)|(k<<20); - return x*twom54; -} +#include "runtime/sharedRuntimeMath.hpp" /* * __kernel_rem_pio2(x,y,e0,nx,prec,ipio2) diff --git a/hotspot/test/TEST.groups b/hotspot/test/TEST.groups index 8d7427dd313..d138789e265 100644 --- a/hotspot/test/TEST.groups +++ b/hotspot/test/TEST.groups @@ -83,6 +83,7 @@ needs_jdk = \ runtime/RedefineObject/TestRedefineObject.java \ runtime/XCheckJniJsig/XCheckJSig.java \ serviceability/attach/AttachWithStalePidFile.java \ + serviceability/jvmti/8036666/GetObjectLockCount.java \ serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java \ serviceability/dcmd/DynLibDcmdTest.java @@ -135,6 +136,8 @@ needs_compact3 = \ gc/parallelScavenge/TestDynShrinkHeap.java \ runtime/InternalApi/ThreadCpuTimesDeadlock.java \ serviceability/threads/TestFalseDeadLock.java \ + serviceability/jvmti/GetObjectSizeOverflow.java \ + serviceability/jvmti/TestRedefineWithUnresolvedClass.java \ compiler/tiered/NonTieredLevelsTest.java \ compiler/tiered/TieredLevelsTest.java \ compiler/intrinsics/bmi/verifycode \ diff --git a/hotspot/test/gc/parallelScavenge/TestDynShrinkHeap.java b/hotspot/test/gc/parallelScavenge/TestDynShrinkHeap.java index 944efcc3956..6f9b02de270 100644 --- a/hotspot/test/gc/parallelScavenge/TestDynShrinkHeap.java +++ b/hotspot/test/gc/parallelScavenge/TestDynShrinkHeap.java @@ -26,7 +26,7 @@ * @bug 8016479 * @summary Verify that the heap shrinks after full GC according to the current values of the Min/MaxHeapFreeRatio flags * @library /testlibrary - * @run main/othervm -XX:+UseAdaptiveSizePolicyWithSystemGC -XX:+UseParallelGC -XX:MinHeapFreeRatio=0 -XX:MaxHeapFreeRatio=100 -verbose:gc TestDynShrinkHeap + * @run main/othervm -XX:+UseAdaptiveSizePolicyWithSystemGC -XX:+UseParallelGC -XX:MinHeapFreeRatio=0 -XX:MaxHeapFreeRatio=100 -Xmx1g -verbose:gc TestDynShrinkHeap */ import com.oracle.java.testlibrary.DynamicVMOption; import java.lang.management.ManagementFactory; @@ -41,7 +41,7 @@ public class TestDynShrinkHeap { public static final String MAX_FREE_RATIO_FLAG_NAME = "MaxHeapFreeRatio"; private static ArrayList list = new ArrayList<>(0); - private static final int M = 1024 * 1024; // to make heap more manageable by test code + private static final int LEN = 512 * 1024 + 1; public TestDynShrinkHeap() { } @@ -69,12 +69,12 @@ public class TestDynShrinkHeap { } private void eat() { - for (int i = 0; i < M; i++) { + for (int i = 0; i < LEN; i++) { list.add(new byte[1024]); } - MemoryUsagePrinter.printMemoryUsage("allocated " + M + " arrays"); + MemoryUsagePrinter.printMemoryUsage("allocated " + LEN + " arrays"); - list.subList(0, M / 2).clear(); + list.subList(0, LEN / 2).clear(); System.gc(); MemoryUsagePrinter.printMemoryUsage("array halved"); } diff --git a/hotspot/test/runtime/6929067/T.java b/hotspot/test/runtime/6929067/T.java deleted file mode 100644 index 48c48857b95..00000000000 --- a/hotspot/test/runtime/6929067/T.java +++ /dev/null @@ -1,12 +0,0 @@ -public class T -{ - public static boolean foo(boolean bar) - { - return bar; - } - - public static void printIt() - { - System.out.println("Hello"); - } -} diff --git a/hotspot/test/runtime/6929067/invoke.c b/hotspot/test/runtime/6929067/invoke.c deleted file mode 100644 index 8dde2cd671b..00000000000 --- a/hotspot/test/runtime/6929067/invoke.c +++ /dev/null @@ -1,90 +0,0 @@ -#include -#include -#include - -#include - -union env_union -{ - void *void_env; - JNIEnv *jni_env; -}; - -union env_union tmp; -JNIEnv* env; -JavaVM* jvm; -JavaVMInitArgs vm_args; -JavaVMOption options[1]; -jclass class_id; -jmethodID method_id; -jint result; - -long product(unsigned long n, unsigned long m) { - if (m == 1) { - return n; - } else { - int *p = alloca(sizeof (int)); - *p = n; - return product (n, m-1) + *p; - } -} - -void * -floobydust (void *p) -{ - (*jvm)->AttachCurrentThread(jvm, &tmp.void_env, NULL); - env = tmp.jni_env; - - class_id = (*env)->FindClass (env, "T"); - assert (class_id); - - method_id = (*env)->GetStaticMethodID (env, class_id, "printIt", "()V"); - assert (method_id); - - (*env)->CallStaticVoidMethod (env, class_id, method_id, NULL); - - (*jvm)->DetachCurrentThread(jvm); - - printf("%ld\n", product(5000,5000)); - - (*jvm)->AttachCurrentThread(jvm, &tmp.void_env, NULL); - env = tmp.jni_env; - - class_id = (*env)->FindClass (env, "T"); - assert (class_id); - - method_id = (*env)->GetStaticMethodID (env, class_id, "printIt", "()V"); - assert (method_id); - - (*env)->CallStaticVoidMethod (env, class_id, method_id, NULL); - - (*jvm)->DetachCurrentThread(jvm); - - printf("%ld\n", product(5000,5000)); - - return NULL; -} - -int -main (int argc, const char** argv) -{ - options[0].optionString = "-Xss320k"; - - vm_args.version = JNI_VERSION_1_2; - vm_args.ignoreUnrecognized = JNI_TRUE; - vm_args.options = options; - vm_args.nOptions = 1; - - result = JNI_CreateJavaVM (&jvm, &tmp.void_env, &vm_args); - assert (result >= 0); - - env = tmp.jni_env; - - floobydust (NULL); - - pthread_t thr; - pthread_create (&thr, NULL, floobydust, NULL); - pthread_join (thr, NULL); - - return 0; -} diff --git a/hotspot/test/runtime/InitialThreadOverflow/testme.sh b/hotspot/test/runtime/InitialThreadOverflow/testme.sh deleted file mode 100644 index d5d0eb223ff..00000000000 --- a/hotspot/test/runtime/InitialThreadOverflow/testme.sh +++ /dev/null @@ -1,77 +0,0 @@ -#!/bin/sh - -# Copyright (c) 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. -# -# This code is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please 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 testme.sh -# @bug 8009062 -# @summary Poor performance of JNI AttachCurrentThread after fix for 7017193 -# @compile DoOverflow.java -# @run shell testme.sh - -set -x -if [ "${TESTSRC}" = "" ] -then - TESTSRC=${PWD} - echo "TESTSRC not set. Using "${TESTSRC}" as default" -fi -echo "TESTSRC=${TESTSRC}" -## Adding common setup Variables for running shell tests. -. ${TESTSRC}/../../test_env.sh - -if [ "${VM_OS}" != "linux" ] -then - echo "Test only valid for Linux" - exit 0 -fi - -gcc_cmd=`which gcc` -if [ "x$gcc_cmd" = "x" ]; then - echo "WARNING: gcc not found. Cannot execute test." 2>&1 - exit 0; -fi - -CFLAGS="-m${VM_BITS}" - -LD_LIBRARY_PATH=.:${TESTJAVA}/jre/lib/${VM_CPU}/${VM_TYPE}:/usr/lib:$LD_LIBRARY_PATH -export LD_LIBRARY_PATH - -cp ${TESTSRC}/invoke.c . - -# Copy the result of our @compile action: -cp ${TESTCLASSES}/DoOverflow.class . - -echo "Architecture: ${VM_CPU}" -echo "Compilation flag: ${CFLAGS}" -echo "VM type: ${VM_TYPE}" -echo "LD_LIBRARY_PATH: ${LD_LIBRARY_PATH}" - -# Note pthread may not be found thus invoke creation will fail to be created. -# Check to ensure you have a /usr/lib/libpthread.so if you don't please look -# for /usr/lib/`uname -m`-linux-gnu version ensure to add that path to below compilation. - -$gcc_cmd -DLINUX ${CFLAGS} -o invoke \ - -I${TESTJAVA}/include -I${TESTJAVA}/include/linux \ - -L${TESTJAVA}/jre/lib/${VM_CPU}/${VM_TYPE} \ - -ljvm -lpthread invoke.c - -./invoke -exit $? diff --git a/hotspot/test/runtime/InitialThreadOverflow/DoOverflow.java b/hotspot/test/runtime/StackGuardPages/DoOverflow.java similarity index 87% rename from hotspot/test/runtime/InitialThreadOverflow/DoOverflow.java rename to hotspot/test/runtime/StackGuardPages/DoOverflow.java index 958285ca915..4b9c45b62e8 100644 --- a/hotspot/test/runtime/InitialThreadOverflow/DoOverflow.java +++ b/hotspot/test/runtime/StackGuardPages/DoOverflow.java @@ -30,12 +30,16 @@ public class DoOverflow { overflow(); } + public static void printAlive() { + System.out.println("Java thread is alive."); + } + public static void printIt() { System.out.println("Going to overflow stack"); try { new DoOverflow().overflow(); } catch(java.lang.StackOverflowError e) { - System.out.println("Overflow OK " + count); + System.out.println("Test PASSED. Got StackOverflowError at " + count + " iteration"); } } } diff --git a/hotspot/test/runtime/StackGuardPages/invoke.c b/hotspot/test/runtime/StackGuardPages/invoke.c new file mode 100644 index 00000000000..483ac0b98e7 --- /dev/null +++ b/hotspot/test/runtime/StackGuardPages/invoke.c @@ -0,0 +1,266 @@ +/* + * Copyright (c) 2010, 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 code tests the fact that we actually remove stack guard page when calling + * JavaThread::exit() i.e. when detaching from current thread. + * We overflow the stack and check that we get access error because of a guard page. + * Than we detach from vm thread and overflow stack once again. This time we shouldn't + * get access error because stack guard page is removed + * + * Notice: due a complicated interaction of signal handlers, the test may crash. + * It's OK - don't file a bug. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +JavaVM* _jvm; + +static jmp_buf context; + +static int _last_si_code = -1; +static int _failures = 0; +static int _rec_count = 0; +static int _kp_rec_count = 0; + +pid_t gettid() { + return (pid_t) syscall(SYS_gettid); +} + +static void handler(int sig, siginfo_t *si, void *unused) { + _last_si_code = si->si_code; + printf("Got SIGSEGV(%d) at address: 0x%lx\n",si->si_code, (long) si->si_addr); + longjmp(context, 1); +} + +void set_signal_handler() { + static char altstack[SIGSTKSZ]; + + stack_t ss = { + .ss_size = SIGSTKSZ, + .ss_flags = 0, + .ss_sp = altstack + }; + + struct sigaction sa = { + .sa_sigaction = handler, + .sa_flags = SA_ONSTACK | SA_SIGINFO | SA_RESETHAND + }; + + _last_si_code = -1; + + sigaltstack(&ss, 0); + sigemptyset(&sa.sa_mask); + if (sigaction(SIGSEGV, &sa, NULL) == -1) { + fprintf(stderr, "Test ERROR. Can't set sigaction (%d)\n", errno); + exit(7); + } +} + +void *run_java_overflow (void *p) { + JNIEnv *env; + jclass class_id; + jmethodID method_id; + int res; + + res = (*_jvm)->AttachCurrentThread(_jvm, (void**)&env, NULL); + if (res != JNI_OK) { + fprintf(stderr, "Test ERROR. Can't attach to current thread\n"); + exit(7); + } + + class_id = (*env)->FindClass (env, "DoOverflow"); + if (class_id == NULL) { + fprintf(stderr, "Test ERROR. Can't load class DoOverflow\n"); + exit(7); + } + + method_id = (*env)->GetStaticMethodID(env, class_id, "printIt", "()V"); + if (method_id == NULL) { + fprintf(stderr, "Test ERROR. Can't find method DoOverflow.printIt\n"); + exit(7); + } + + (*env)->CallStaticVoidMethod(env, class_id, method_id, NULL); + + res = (*_jvm)->DetachCurrentThread(_jvm); + if (res != JNI_OK) { + fprintf(stderr, "Test ERROR. Can't call detach from current thread\n"); + exit(7); + } +} + +void do_overflow(){ + int *p = alloca(sizeof(int)); + if (_kp_rec_count == 0 || _rec_count < _kp_rec_count) { + _rec_count ++; + do_overflow(); + } +} + +void *run_native_overflow(void *p) { + // Test that stack guard page is correctly set for initial and non initial thread + // and correctly removed for the initial thread + JNIEnv *env; + jclass class_id; + jmethodID method_id; + int res; + + printf("run_native_overflow %ld\n", (long) gettid()); + + res = (*_jvm)->AttachCurrentThread(_jvm, (void **)&env, NULL); + if (res != JNI_OK) { + fprintf(stderr, "Test ERROR. Can't attach to current thread\n"); + exit(7); + } + + class_id = (*env)->FindClass (env, "DoOverflow"); + if (class_id == NULL) { + fprintf(stderr, "Test ERROR. Can't load class DoOverflow\n"); + exit(7); + } + + method_id = (*env)->GetStaticMethodID (env, class_id, "printAlive", "()V"); + if (method_id == NULL) { + fprintf(stderr, "Test ERROR. Can't find method DoOverflow.printAlive\n"); + exit(7); + } + + (*env)->CallStaticVoidMethod (env, class_id, method_id, NULL); + + set_signal_handler(); + if (! setjmp(context)) { + do_overflow(); + } + + if (_last_si_code == SEGV_ACCERR) { + printf("Test PASSED. Got access violation accessing guard page at %d\n", _rec_count); + } + + res = (*_jvm)->DetachCurrentThread(_jvm); + if (res != JNI_OK) { + fprintf(stderr, "Test ERROR. Can't call detach from current thread\n"); + exit(7); + } + + if (getpid() != gettid()) { + // For non-initial thread we don't unmap the region but call os::uncommit_memory and keep PROT_NONE + // so if host has enough swap space we will get the same SEGV with code SEGV_ACCERR(2) trying + // to access it as if the guard page is present. + // We have no way to check this, so bail out, marking test as succeeded + printf("Test PASSED. Not initial thread\n"); + return NULL; + } + + // Limit depth of recursion for second run. It can't exceed one for first run. + _kp_rec_count = _rec_count; + _rec_count = 0; + + set_signal_handler(); + if (! setjmp(context)) { + do_overflow(); + } + + if (_last_si_code == SEGV_ACCERR) { + ++ _failures; + fprintf(stderr,"Test FAILED. Stack guard page is still there at %d\n", _rec_count); + } else if (_last_si_code == -1) { + printf("Test PASSED. No stack guard page is present. Maximum recursion level reached at %d\n", _rec_count); + } + else{ + printf("Test PASSED. No stack guard page is present. SIGSEGV(%d) at %d\n", _last_si_code, _rec_count); + } + + return NULL; +} + +void usage() { + fprintf(stderr, "Usage: invoke test_java_overflow\n"); + fprintf(stderr, " invoke test_native_overflow\n"); + exit(7); +} + + +int main (int argc, const char** argv) { + JavaVMInitArgs vm_args; + JavaVMOption options[2]; + JNIEnv* env; + + printf("Test started with pid: %ld\n", (long) getpid()); + + options[0].optionString = "-Xint"; + options[1].optionString = "-Xss320k"; + + vm_args.version = JNI_VERSION_1_2; + vm_args.ignoreUnrecognized = JNI_TRUE; + vm_args.options = options; + vm_args.nOptions = 2; + + if (JNI_CreateJavaVM (&_jvm, (void **)&env, &vm_args) < 0 ) { + fprintf(stderr, "Test ERROR. Can't create JavaVM\n"); + exit(7); + } + + pthread_t thr; + + if (argc > 1 && strcmp(argv[1], "test_java_overflow") == 0) { + printf("\nTesting JAVA_OVERFLOW\n"); + + printf("Testing stack guard page behaviour for other thread\n"); + pthread_create (&thr, NULL, run_java_overflow, NULL); + pthread_join (thr, NULL); + + printf("Testing stack guard page behaviour for initial thread\n"); + run_java_overflow(NULL); + // This test crash on error + exit(0); + } + + if (argc > 1 && strcmp(argv[1], "test_native_overflow") == 0) { + printf("\nTesting NATIVE_OVERFLOW\n"); + + printf("Testing stack guard page behaviour for other thread\n"); + pthread_create (&thr, NULL, run_native_overflow, NULL); + pthread_join (thr, NULL); + + printf("Testing stack guard page behaviour for initial thread\n"); + run_native_overflow(NULL); + + exit((_failures > 0) ? 1 : 0); + } + + fprintf(stderr, "Test ERROR. Unknown parameter %s\n", ((argc > 1) ? argv[1] : "none")); + usage(); +} diff --git a/hotspot/test/runtime/6929067/Test6929067.sh b/hotspot/test/runtime/StackGuardPages/testme.sh similarity index 62% rename from hotspot/test/runtime/6929067/Test6929067.sh rename to hotspot/test/runtime/StackGuardPages/testme.sh index e1fd6b78237..7f6a24a3d31 100644 --- a/hotspot/test/runtime/6929067/Test6929067.sh +++ b/hotspot/test/runtime/StackGuardPages/testme.sh @@ -1,13 +1,10 @@ #!/bin/sh -## -## @test Test6929067.sh -## @bug 6929067 -## @bug 8021296 -## @bug 8025519 -## @summary Stack guard pages should be removed when thread is detached -## @run shell Test6929067.sh -## +# +# @test testme.sh +# @summary Stack guard pages should be installed correctly and removed when thread is detached +# @run shell testme.sh +# if [ "${TESTSRC}" = "" ] then @@ -32,12 +29,9 @@ fi CFLAGS=-m${VM_BITS} -LD_LIBRARY_PATH=.:${TESTJAVA}/jre/lib/${VM_CPU}/${VM_TYPE}:/usr/lib:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=.:${TESTJAVA}/jre/lib/${VM_CPU}/${VM_TYPE}:${TESTJAVA}/lib/${VM_CPU}/${VM_TYPE}:/usr/lib:$LD_LIBRARY_PATH export LD_LIBRARY_PATH -cp ${TESTSRC}/*.java ${THIS_DIR} -${COMPILEJAVA}/bin/javac *.java - echo "Architecture: ${VM_CPU}" echo "Compilation flag: ${CFLAGS}" echo "VM type: ${VM_TYPE}" @@ -47,10 +41,20 @@ echo "LD_LIBRARY_PATH: ${LD_LIBRARY_PATH}" # Check to ensure you have a /usr/lib/libpthread.so if you don't please look # for /usr/lib/`uname -m`-linux-gnu version ensure to add that path to below compilation. -$gcc_cmd -DLINUX ${CFLAGS} -o invoke \ +cp ${TESTSRC}/DoOverflow.java . +${COMPILEJAVA}/bin/javac DoOverflow.java + +$gcc_cmd -DLINUX -g3 ${CFLAGS} -o invoke \ -I${TESTJAVA}/include -I${TESTJAVA}/include/linux \ -L${TESTJAVA}/jre/lib/${VM_CPU}/${VM_TYPE} \ + -L${TESTJAVA}/lib/${VM_CPU}/${VM_TYPE} \ ${TESTSRC}/invoke.c -ljvm -lpthread -./invoke +if [ $? -ne 0 ] ; then + echo "Compile failed, Ignoring failed compilation and forcing the test to pass" + exit 0 +fi + +./invoke test_java_overflow +./invoke test_native_overflow exit $? diff --git a/hotspot/test/serviceability/jvmti/GetObjectSizeOverflow.java b/hotspot/test/serviceability/jvmti/GetObjectSizeOverflow.java new file mode 100644 index 00000000000..ec33d813541 --- /dev/null +++ b/hotspot/test/serviceability/jvmti/GetObjectSizeOverflow.java @@ -0,0 +1,64 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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.PrintWriter; +import com.oracle.java.testlibrary.*; + +/* + * Test to verify GetObjectSize does not overflow on a 600M element int[] + * + * @test + * @bug 8027230 + * @library /testlibrary + * @build GetObjectSizeOverflowAgent + * @run main ClassFileInstaller GetObjectSizeOverflowAgent + * @run main GetObjectSizeOverflow + */ +public class GetObjectSizeOverflow { + public static void main(String[] args) throws Exception { + + if (!Platform.is64bit()) { + System.out.println("Test needs a 4GB heap and can only be run as a 64bit process, skipping."); + return; + } + + PrintWriter pw = new PrintWriter("MANIFEST.MF"); + pw.println("Premain-Class: GetObjectSizeOverflowAgent"); + pw.close(); + + ProcessBuilder pb = new ProcessBuilder(); + pb.command(new String[] { JDKToolFinder.getJDKTool("jar"), "cmf", "MANIFEST.MF", "agent.jar", "GetObjectSizeOverflowAgent.class"}); + pb.start().waitFor(); + + ProcessBuilder pt = ProcessTools.createJavaProcessBuilder(true, "-Xmx4000m", "-javaagent:agent.jar", "GetObjectSizeOverflowAgent"); + OutputAnalyzer output = new OutputAnalyzer(pt.start()); + + if (output.getStdout().contains("Could not reserve enough space") || output.getStderr().contains("java.lang.OutOfMemoryError")) { + System.out.println("stdout: " + output.getStdout()); + System.out.println("stderr: " + output.getStderr()); + System.out.println("Test could not reserve or allocate enough space, skipping"); + return; + } + + output.stdoutShouldContain("GetObjectSizeOverflow passed"); + } +} diff --git a/hotspot/test/serviceability/jvmti/GetObjectSizeOverflowAgent.java b/hotspot/test/serviceability/jvmti/GetObjectSizeOverflowAgent.java new file mode 100644 index 00000000000..8f7c2162364 --- /dev/null +++ b/hotspot/test/serviceability/jvmti/GetObjectSizeOverflowAgent.java @@ -0,0 +1,43 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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.lang.instrument.*; + +public class GetObjectSizeOverflowAgent { + + static Instrumentation instrumentation; + + public static void premain(String agentArgs, Instrumentation instrumentation) { + GetObjectSizeOverflowAgent.instrumentation = instrumentation; + } + + public static void main(String[] args) throws Exception { + int[] a = new int[600_000_000]; + long size = instrumentation.getObjectSize(a); + + if (size < 2_400_000_000L) { + throw new RuntimeException("Invalid size of array, expected >= 2400000000, got " + size); + } + + System.out.println("GetObjectSizeOverflow passed"); + } +} diff --git a/jaxp/.hgtags b/jaxp/.hgtags index f631e59bbe0..f6504ed115a 100644 --- a/jaxp/.hgtags +++ b/jaxp/.hgtags @@ -256,3 +256,5 @@ f93a792fe37279d4d37aea86a99f3abbdc6fe79b jdk9-b09 6b4280dceb00642f54d5bc1c2cb7d34c99a04992 jdk9-b11 e88cecf5a21b760ff7d7761c2db6bb8c82bc9f0c jdk9-b12 5eaf717f6e36037a6d3744ffeee0e4c88e64a0d2 jdk9-b13 +32b3fc4bc7374a34d52b7f4e2391b4b4b0c084e8 jdk9-b14 +6bad71866c7598587860e0981b0b0e51ec8c0476 jdk9-b15 diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Makefile.inc b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Makefile.inc deleted file mode 100644 index 8c1f57a8b18..00000000000 --- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Makefile.inc +++ /dev/null @@ -1,60 +0,0 @@ -########################################################################### -# reserved comment block -# DO NOT REMOVE OR ALTER! -########################################################################### -########################################################################## -# Copyright 2001-2004 The Apache Software Foundation. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -########################################################################## -# -# $Id: Makefile.inc,v 1.2 2004/02/17 16:32:49 minchau Exp $ -# -#################################################################### -# # -# Makefile.inc for XSLT compiler # -# # -#################################################################### - -#################################################################### -# Useful macros # -#################################################################### - -JAVAC = javac -#JAVAC_FLAGS = -g -d $(XSLT)/src/classes -JAVAC_FLAGS = -sourcepath $(XSLT)/src -JAVACC = javacc -JAVACC_FLAGS = -static=FALSE -JAVACUP = javacup -JAVACUP_FLAGS = -JAVALEX = jlex -JAVALEX_FLAGS = - -#################################################################### -# Explicit rules # -#################################################################### - -.SUFFIXES: .java .class .jj .lex .cup - -.java.class: - $(JAVAC) $(JAVAC_FLAGS) $< - -.jj.java: - $(JAVACC) $(JAVACC_FLAGS) $< - -.cup.java: - $(JAVACUP) $(JAVACUP_FLAGS) $< - -.lex.java: - $(JAVALEX) $(JAVALEX_FLAGS) $< - diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/javax.xml.transform.TransformerFactory b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/javax.xml.transform.TransformerFactory deleted file mode 100644 index a607891fefd..00000000000 --- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/javax.xml.transform.TransformerFactory +++ /dev/null @@ -1 +0,0 @@ -com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/dom/org.apache.xerces.dom.DOMImplementationSourceImpl b/jaxp/src/com/sun/org/apache/xerces/internal/dom/org.apache.xerces.dom.DOMImplementationSourceImpl deleted file mode 100644 index 79c33dd2078..00000000000 --- a/jaxp/src/com/sun/org/apache/xerces/internal/dom/org.apache.xerces.dom.DOMImplementationSourceImpl +++ /dev/null @@ -1 +0,0 @@ -com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/dom/org.w3c.dom.DOMImplementationSourceList b/jaxp/src/com/sun/org/apache/xerces/internal/dom/org.w3c.dom.DOMImplementationSourceList deleted file mode 100644 index 814f03139f0..00000000000 --- a/jaxp/src/com/sun/org/apache/xerces/internal/dom/org.w3c.dom.DOMImplementationSourceList +++ /dev/null @@ -1 +0,0 @@ -com.sun.org.apache.xerces.internal.dom.DOMXSImplementationSourceImpl diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/datatype/javax.xml.datatype.DatatypeFactory b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/datatype/javax.xml.datatype.DatatypeFactory deleted file mode 100644 index 4a5c28226b5..00000000000 --- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/datatype/javax.xml.datatype.DatatypeFactory +++ /dev/null @@ -1 +0,0 @@ -com.sun.org.apache.xerces.internal.jaxp.datatype.DatatypeFactoryImpl diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/javax.xml.parsers.DocumentBuilderFactory b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/javax.xml.parsers.DocumentBuilderFactory deleted file mode 100644 index dc39440e898..00000000000 --- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/javax.xml.parsers.DocumentBuilderFactory +++ /dev/null @@ -1 +0,0 @@ -com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/javax.xml.parsers.SAXParserFactory b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/javax.xml.parsers.SAXParserFactory deleted file mode 100644 index cd8406950db..00000000000 --- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/javax.xml.parsers.SAXParserFactory +++ /dev/null @@ -1 +0,0 @@ -com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/javax.xml.validation.SchemaFactory b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/javax.xml.validation.SchemaFactory deleted file mode 100644 index 51d33a674c7..00000000000 --- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/validation/javax.xml.validation.SchemaFactory +++ /dev/null @@ -1 +0,0 @@ -com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/org.apache.xerces.xni.parser.DTDConfiguration b/jaxp/src/com/sun/org/apache/xerces/internal/parsers/org.apache.xerces.xni.parser.DTDConfiguration deleted file mode 100644 index 8f6ac8baba9..00000000000 --- a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/org.apache.xerces.xni.parser.DTDConfiguration +++ /dev/null @@ -1 +0,0 @@ -com.sun.org.apache.xerces.internal.parsers.DTDConfiguration diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/org.apache.xerces.xni.parser.XML11Configuration b/jaxp/src/com/sun/org/apache/xerces/internal/parsers/org.apache.xerces.xni.parser.XML11Configuration deleted file mode 100644 index af1926488fd..00000000000 --- a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/org.apache.xerces.xni.parser.XML11Configuration +++ /dev/null @@ -1 +0,0 @@ -com.sun.org.apache.xerces.internal.parsers.XML11Configuration diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/org.apache.xerces.xni.parser.XMLParserConfiguration b/jaxp/src/com/sun/org/apache/xerces/internal/parsers/org.apache.xerces.xni.parser.XMLParserConfiguration deleted file mode 100644 index ca8bc3e7232..00000000000 --- a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/org.apache.xerces.xni.parser.XMLParserConfiguration +++ /dev/null @@ -1 +0,0 @@ -com.sun.org.apache.xerces.internal.parsers.XIncludeAwareParserConfiguration diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/org.xml.sax.driver b/jaxp/src/com/sun/org/apache/xerces/internal/parsers/org.xml.sax.driver deleted file mode 100644 index e1a387435c4..00000000000 --- a/jaxp/src/com/sun/org/apache/xerces/internal/parsers/org.xml.sax.driver +++ /dev/null @@ -1,2 +0,0 @@ -com.sun.org.apache.xerces.internal.parsers.SAXParser - diff --git a/jaxp/src/com/sun/xml/internal/stream/javax.xml.stream.XMLEventFactory b/jaxp/src/com/sun/xml/internal/stream/javax.xml.stream.XMLEventFactory deleted file mode 100644 index adc26b34340..00000000000 --- a/jaxp/src/com/sun/xml/internal/stream/javax.xml.stream.XMLEventFactory +++ /dev/null @@ -1 +0,0 @@ -com.sun.xml.internal.stream.events.XMLEventFactoryImpl diff --git a/jaxp/src/com/sun/xml/internal/stream/javax.xml.stream.XMLInputFactory b/jaxp/src/com/sun/xml/internal/stream/javax.xml.stream.XMLInputFactory deleted file mode 100644 index 456882c2cb3..00000000000 --- a/jaxp/src/com/sun/xml/internal/stream/javax.xml.stream.XMLInputFactory +++ /dev/null @@ -1 +0,0 @@ -com.sun.xml.internal.stream.XMLInputFactoryImpl diff --git a/jaxp/src/com/sun/xml/internal/stream/javax.xml.stream.XMLOutputFactory b/jaxp/src/com/sun/xml/internal/stream/javax.xml.stream.XMLOutputFactory deleted file mode 100644 index 3de51905314..00000000000 --- a/jaxp/src/com/sun/xml/internal/stream/javax.xml.stream.XMLOutputFactory +++ /dev/null @@ -1 +0,0 @@ -com.sun.xml.internal.stream.XMLOutputFactoryImpl diff --git a/jaxp/src/org/xml/sax/COPYING b/jaxp/src/org/xml/sax/COPYING deleted file mode 100644 index dd0b9813dbc..00000000000 --- a/jaxp/src/org/xml/sax/COPYING +++ /dev/null @@ -1,12 +0,0 @@ -SAX IS FREE ------------ - -I hereby abandon any property rights to SAX 2.0 (the Simple API for -XML), and release all of the SAX 2.0 source code, compiled code, and -documentation contained in this distribution into the Public Domain. -SAX comes with NO WARRANTY or guarantee of fitness for any purpose. - - -David Megginson -david@megginson.com -2000-01-14 diff --git a/jaxp/src/org/xml/sax/COPYING.txt b/jaxp/src/org/xml/sax/COPYING.txt deleted file mode 100644 index 27518b4b9cc..00000000000 --- a/jaxp/src/org/xml/sax/COPYING.txt +++ /dev/null @@ -1,39 +0,0 @@ - SAX COPYRIGHT STATUS - -Version 1.0 of the Simple API for XML (SAX), created collectively by -the membership of the XML-DEV mailing list, is hereby released into -the public domain. - -No one owns SAX: you may use it freely in both commercial and -non-commercial applications, bundle it with your software -distribution, include it on a CD-ROM, list the source code in a book, -mirror the documentation at your own web site, or use it in any other -way you see fit. - - - NO WARRANTY - -Because SAX is released to the public domain, there is no warranty for -the design or for the software implementation, to the extent permitted -by applicable law. Except when otherwise stated in writing the -copyright holders and/or other parties provide SAX "as is" without -warranty of any kind, either expressed or implied, including, but not -limited to, the implied warranties of merchantability and fitness for -a particular purpose. The entire risk as to the quality and -performance of SAX is with you. Should SAX prove defective, you -assume the cost of all necessary servicing, repair or correction. - -In no event unless required by applicable law or agreed to in writing -will any copyright holder, or any other party who may modify and/or -redistribute SAX, be liable to you for damages, including any general, -special, incidental or consequential damages arising out of the use or -inability to use SAX (including but not limited to loss of data or -data being rendered inaccurate or losses sustained by you or third -parties or a failure of the SAX to operate with any other programs), -even if such holder or other party has been advised of the possibility -of such damages. - - -David Megginson -1998-05-11 - diff --git a/jaxws/.hgtags b/jaxws/.hgtags index b2197334dde..7f510c46e5f 100644 --- a/jaxws/.hgtags +++ b/jaxws/.hgtags @@ -259,3 +259,5 @@ c9e8bb8c1144a966ca7b481142c6b5e55d14a29c jdk9-b09 1f953ba7db2b535e19f0354abfee6d67605e0684 jdk9-b11 779f8b21c75f83e3918dac8499e4d0ecb3a54ed7 jdk9-b12 3d42204854c9f703e3ccdc8891248e73057713ab jdk9-b13 +02e58850b7062825308413d420f2b02c1f25a724 jdk9-b14 +e9780330017a6b464a385356d77e5136f9de8d09 jdk9-b15 diff --git a/jaxws/src/share/jaxws_classes/com/sun/tools/etc/META-INF/services/com.sun.xml.internal.ws.spi.db.BindingContextFactory b/jaxws/src/share/jaxws_classes/com/sun/tools/etc/META-INF/services/com.sun.xml.internal.ws.spi.db.BindingContextFactory deleted file mode 100644 index 36ea2a98abe..00000000000 --- a/jaxws/src/share/jaxws_classes/com/sun/tools/etc/META-INF/services/com.sun.xml.internal.ws.spi.db.BindingContextFactory +++ /dev/null @@ -1,2 +0,0 @@ -com.sun.xml.internal.ws.db.glassfish.JAXBRIContextFactory -# com.sun.xml.internal.ws.db.toplink.JAXBContextFactory diff --git a/jaxws/src/share/jaxws_classes/com/sun/tools/internal/jxc/gen/config/config.rng b/jaxws/src/share/jaxws_classes/com/sun/tools/internal/jxc/gen/config/config.rng deleted file mode 100644 index 59bcb4e49bc..00000000000 --- a/jaxws/src/share/jaxws_classes/com/sun/tools/internal/jxc/gen/config/config.rng +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - - - - import java.util.List; - import java.util.ArrayList; - import java.io.File; - - - - private File baseDir; - private Classes classes; - private List schema = new ArrayList(); - public Classes getClasses() { return this.classes;} - public File getBaseDir() { return baseDir;} - public List getSchema() { return this.schema;} - - - - - bd = - baseDir = $runtime.getBaseDir(bd); - - - - (baseDir); - this.schema.add (_schema); - - - - - - - - import java.util.List; - import java.util.ArrayList; - - - private List includes = new ArrayList(); - public List getIncludes() { return $runtime.getIncludePatterns(this.includes);} - private List excludes = new ArrayList(); - public List getExcludes() { return $runtime.getExcludePatterns(this.excludes);} - - - - - - - - this.includes.add(include_content); - - - - - - - - - - this.excludes.add(exclude_content); - - - - - - - - - - - - import java.io.File; - - - private File location; - private String namespace; - public String getNamespace() { return this.namespace;} - public File getLocation() { return this.location;} - - - - - namespace = - - - - - - loc = - location = new File(baseDir,loc); - - - - - diff --git a/jaxws/src/share/jaxws_classes/com/sun/tools/internal/xjc/reader/dtd/bindinfo/bindingfile.rng b/jaxws/src/share/jaxws_classes/com/sun/tools/internal/xjc/reader/dtd/bindinfo/bindingfile.rng deleted file mode 100644 index 41c18ff0d1d..00000000000 --- a/jaxws/src/share/jaxws_classes/com/sun/tools/internal/xjc/reader/dtd/bindinfo/bindingfile.rng +++ /dev/null @@ -1,317 +0,0 @@ - - - - - - - - - - - 1.0ea2 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - class - - - - - - - - - - true - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sequence - choice - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - list - set - vector - - - - - - - - - - - - - - - - - - - - - - - - preserve - replace - collapse - - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jaxws/src/share/jaxws_classes/com/sun/tools/internal/xjc/reader/xmlschema/bindinfo/binding.rng b/jaxws/src/share/jaxws_classes/com/sun/tools/internal/xjc/reader/xmlschema/bindinfo/binding.rng deleted file mode 100644 index f689228d585..00000000000 --- a/jaxws/src/share/jaxws_classes/com/sun/tools/internal/xjc/reader/xmlschema/bindinfo/binding.rng +++ /dev/null @@ -1,913 +0,0 @@ - - - - -]> - - - - - import com.sun.codemodel.internal.*; - import com.sun.tools.internal.xjc.generator.bean.field.*; - import com.sun.tools.internal.xjc.model.*; - import com.sun.xml.internal.bind.api.impl.NameConverter; - import com.sun.xml.internal.bind.v2.WellKnownNamespace; - import com.sun.xml.internal.bind.marshaller.SAX2DOMEx; - import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.*; - import com.sun.tools.internal.xjc.reader.Const; - import org.xml.sax.*; - import org.w3c.dom.Document; - import org.xml.sax.helpers.DefaultHandler; - import java.util.*; - import javax.xml.namespace.QName; - import javax.xml.parsers.ParserConfigurationException; - - - - - - - - - - - - - - - - import java.io.StringWriter; - import com.sun.xml.internal.bind.marshaller.DataWriter; - - - // customization declarations - public BindInfo bi; - - private StringWriter w; - - private SAX2DOMEx sax2dom; - - - - bi = new BindInfo($runtime.copyLocator()); - $runtime.currentBindInfo = bi; - - - - - - - - - - result = - bi.addDecl(result); - - - - - - - - - if($runtime.isExtensionURI($uri)) { - // parse this sub-tree as an extension - try { - sax2dom = new SAX2DOMEx(); - } catch( ParserConfigurationException e ) { - throw new Error(e); // impossible - } - $runtime.redirectSubtree(sax2dom,$uri,$localName,$qname); - } else { - // ignore this sub-tree - sax2dom = null; - $runtime.redirectSubtree(new DefaultHandler(),$uri,$localName,$qname); - } - - - if(sax2dom!=null) { - bi.addDecl(new BIXPluginCustomization(((Document)sax2dom.getDOM()).getDocumentElement(),$runtime.copyLocator())); - } - - - - - - - - - - - - msg = - bi.appendDocumentation($runtime.truncateDocComment(msg),true); - - - - - w = new StringWriter(); - DataWriter xw = new DataWriter(w,"UTF-8"); - xw.setXmlDecl(false); - $runtime.redirectSubtree(xw,$uri,$localName,$qname); - - - - "+ - $runtime.escapeMarkup($runtime.truncateDocComment(w.toString()))+ - "", - false ); - w=null; - ]]> - - - - - - - - - - - - - - - - - private BIDeclaration result; - - - - result = - result = - result = - result = - result = - result = - result = - - - - - - - - - - private Locator loc; - private Map globalConvs = new HashMap(); - private NameConverter nameConverter = NameConverter.standard; - private String enableJavaNamingConvention = "true"; - private String fixedAttrToConstantProperty = "false"; - private String needIsSetMethod = "false"; - private String simpleTypeSubstitution = "false"; - private boolean flattenClasses = false; - private Set enumBaseTypes = new HashSet(); - private int defaultEnumSizeCap = 256; - private boolean generateEnumMemberName = false; - private boolean choiceContentPropertyWithModelGroupBinding = false; - private boolean xSmartWildcardDefaultBinding = false; - private boolean xSimpleMode; - private boolean generateValueClass = true; - private boolean generateElementClass = false; - private boolean generateMixedExtensions = false; - - public BIGlobalBinding makeResult() { - if( enumBaseTypes.size()==0 ) - enumBaseTypes.add(new QName(WellKnownNamespace.XML_SCHEMA,"NCName")); // defaults to NCName - - return new BIGlobalBinding( - globalConvs,nameConverter, - choiceContentPropertyWithModelGroupBinding, - generateValueClass, - generateElementClass, - $runtime.parseBoolean(enableJavaNamingConvention), - $runtime.parseBoolean(fixedAttrToConstantProperty), - $runtime.parseBoolean(needIsSetMethod), - $runtime.parseBoolean(simpleTypeSubstitution), - generateEnumMemberName, - flattenClasses, - enumBaseTypes, - defaultEnumSizeCap, - ct, - serializable, - xSuperClass, - xSuperInterface, - xSimpleMode, - xSmartWildcardDefaultBinding, - loc); - } - - - loc = $runtime.copyLocator(); - - - - - asWordSeparator - - asCharInWord - nameConverter = NameConverter.jaxrpcCompatible; - - - - - - - - enableJavaNamingConvention = - - - - - - fixedAttrToConstantProperty = - - - - - - needIsSetMethod = - - - - - - simpleTypeSubstitution = - - - - - - - - nested - flattenClasses = false; - - - toplevel - flattenClasses = true; - - - - - - - - ct = - - - - - - - generateError - - generateName - generateEnumMemberName = true; - - - - - - - - - - value = - QName qn = $runtime.parseQName(value); - enumBaseTypes.add( qn ); - - - - - - - - - - value = - defaultEnumSizeCap = Integer.parseInt(value); - - - - - - - - - value = - choiceContentPropertyWithModelGroupBinding = $runtime.parseBoolean(value); - - - - - - value = - generateValueClass = $runtime.parseBoolean(value); - - - - - - value = - generateElementClass = $runtime.parseBoolean(value); - - - - - - value = - generateMixedExtensions = $runtime.parseBoolean(value); - - - - - - - value = - if( $runtime.parseBoolean(value)==true ) - $runtime.reportUnsupportedFeature("enableValidation"); - - - - - value = - if( $runtime.parseBoolean(value)==true ) - $runtime.reportUnsupportedFeature("enableFailFastCheck"); - - - - - - - - - xmlType = - - conv = - - globalConvs.put( $runtime.parseQName(xmlType), conv ); - - - - - serialuid = - - - if(serialuid!=null) - serializable = new BISerializable(Long.parseLong(serialuid)); - else - serializable = new BISerializable(null); - - - - serializable = - xSuperClass = - xSuperInterface = - - - - xSmartWildcardDefaultBinding = true; - - - - - xSimpleMode = true; - - - - - - - - - - - - - - - - - - - - - - - - - - private Locator loc; - public BISchemaBinding makeResult() { - return new BISchemaBinding(packageName,javadoc,tt,et,at,mt,nt,loc); - } - - - - loc = $runtime.copyLocator(); - - - - - packageName = - - - javadoc = - - - - - - - - - - - tt = - - - et = - - - at = - - - mt = - - - nt = - - - - - - - - - - - - private String prefix=""; - private String suffix=""; - - - - - - prefix = - - - - - suffix = - - - - - - - - - javadoc = - javadoc = $runtime.truncateDocComment(javadoc); - - - - - - private FieldRenderer r = null; - - type = - - if( type.equals("indexed") ) - r = FieldRenderer.ARRAY; - else - try { - r = new UntypedListFieldRenderer( $runtime.codeModel.ref(type) ); - } catch( ClassNotFoundException e ) { - throw new NoClassDefFoundError(e.getMessage()); - } - - - - - - - - private Locator loc; - public BIClass makeResult() { - return new BIClass(loc,name,implClass,javadoc); - } - - - - loc = $runtime.copyLocator(); - - javadoc = - - - - name = - - - - implClass = - - - - - - - - private Locator loc; - private Boolean isConst = null; - private Boolean isSet = null; - private Boolean genElemProp = null; - - public BIProperty makeResult() throws SAXException { - JType baseTypeRef = null; - if(baseType!=null) - baseTypeRef = $runtime.getType(baseType); - - return new BIProperty(loc,name,javadoc,baseTypeRef,conv,ct,isConst,isSet,genElemProp); - } - - - - loc = $runtime.copyLocator(); - - name = - - - baseType = - - - - ct = - - - - - isConstStr = - isConst = $runtime.parseBoolean(isConstStr)?Boolean.TRUE:Boolean.FALSE; - - - - - isSetStr = - isSet = $runtime.parseBoolean(isSetStr)?Boolean.TRUE:Boolean.FALSE; - - - - - genElemPropStr = - genElemProp = $runtime.parseBoolean(genElemPropStr)?Boolean.TRUE:Boolean.FALSE; - - - - - failFast = - - if( $runtime.parseBoolean(failFast) ) { - $runtime.reportUnimplementedFeature("generateFailFastSetterMethod"); - } - - - - - - javadoc = - - - - conv = - - - - - - - - - r = - - - - - - - - import com.sun.tools.internal.xjc.generator.util.WhitespaceNormalizer; - - - - - - parse = - - - print = - - - - - _context = - context = $runtime.parseBoolean(_context); - - - - - - - - - - import java.util.HashMap; - - - private HashMap members = new HashMap(); - private boolean dontBind = false; - private Locator loc,loc2; - - private BIEnum makeResult() { - return new BIEnum(loc,dontBind,name,javadoc,members); - } - - - - loc = $runtime.copyLocator(); - - - false - dontBind = true; - - - - name = - - - javadoc = - - - jname = null; - javadoc = null; - - loc2 = $runtime.copyLocator(); - - jname = - - value = - - javadoc = - - members.put( value, new BIEnumMember(loc2,jname,javadoc) ); - - - - - - - - - - - - - private Locator loc; - private BIEnumMember makeResult() { - return new BIEnumMember(loc,name,javadoc); - } - - - - loc = $runtime.copyLocator(); - name = - - javadoc = - - - - - - - - - private JDefinedClass makeResult() { - try { - JDefinedClass c = $runtime.codeModel._class(name); - c.hide(); - return c; - } catch( JClassAlreadyExistsException e ) { - return e.getExistingClass(); - } - } - - - - name = - - - - - - - private JDefinedClass makeResult() { - try { - JDefinedClass c = $runtime.codeModel._class(name,ClassType.INTERFACE); - c.hide(); - return c; - } catch( JClassAlreadyExistsException e ) { - return e.getExistingClass(); - } - } - - - - name = - - - - - - - private long uid = 1; - private BISerializable makeResult() { - return new BISerializable(uid); - } - - - -// loc = $runtime.copyLocator(); - - - v = - uid = Long.parseLong(v); - - - - - - - - - - complex - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/schemagen/xmlschema/xmlschema-for-jaxb.rng b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/schemagen/xmlschema/xmlschema-for-jaxb.rng deleted file mode 100644 index 88eb2f56610..00000000000 --- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/schemagen/xmlschema/xmlschema-for-jaxb.rng +++ /dev/null @@ -1,1579 +0,0 @@ - - - - - - - RELAX NG schema for XML Schema by Jeni Tennison. Based on - XML - Schema Part I: Structures Recommendation and XML Schema Part - II: Datatypes. - - - - Amended to comply with 10 August 2001 Tutorial. - - Removed key attributes. - Replaced not element with except elements. - - Replaced multiple consecutive optional attributes to use the - zeroOrMore/choice pattern. - - - Removed interleave elements inside list elements (which are no longer - permitted). - - - - - - This allows any number of attributes that are not in the XML Schema - namespace or are in no namespace. This is somewhat more complicated than - the XML Schema anyAttribute equivalent. - - - - - - - - - This allows any number of attributes that are not in the XML Schema - namespace or are in no namespace, an optional id attribute of type ID, - and an optional annotation element. This is used as the basis for many - element content models. - - - - - - - - - - - - - - - This gives the content model of the top level of the schema. - - - - - - - - - - - - This gives the components that can be redefined within the redefine - element. They also occur at the top level of the schema. - - - - - - - - - - - This gives the values for the various form attributes: - elementFormDefault and attributeFormDefault on the schema element, and - the form attributes on the element and attribute elements. - - - qualified - unqualified - - - - - - - This gives the values that can be taken in the lists used to control - derivation by extension or restriction (this is 'reduced' derivation - because some derivation can involve substitution). This RELAX NG schema, - like the XML Schema Recommendation here, allows the keywords 'extension' and - 'restriction' to be repeated any number of times. - - - - - extension - restriction - - - - - - - - This specifies the possible values for attributes that control derivation. - - - #all - - - - - - - This is the beginning point for the schema, and defines the schema - element. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This gives the value type for the maxOccurs attribute, which may be a - non-negative number or the keyword 'unbounded'. - - - - unbounded - - - - - - This specifies the occurs attributes, minOccurs and maxOccurs, as they - are normally used. - - - - - - - - - - - - - - - - This gives the possible content of complex types. - - - - - - - - - - - - This gives the particles that can make up a model group. - - - - - - - - - - - - - This specifies the relationship between fixed and default attributes on - element and attribute elements - if one is present, then the other cannot - be. This is a constraint that cannot be specified using XML Schema. - - - - - - - - - - - This specifies the relationship between the type attribute and the - simpleType element child of attribute elements - if one is present, then - the other cannot be, although it is possible for neither to be allowed. - - - - - - - - - - - - - This describes attribute elements when used in a local context. They - have an optional use attribute, possibly a fixed or default attribute, - and then can either have a ref attribute (referring to a top-level - attribute) or a name attribute with an optional form attribute and - specifying an attribute type. - - - - - - - optional - prohibited - required - - - - - - - - - - - - - - - - - - - - - - - - - - This describes attribute elements when used at the top level of the - schema. They must have a name, may have a fixed or default attribute, - and specify their type through a type attribute or child simpleType - element. The name attribute of each attribute element that appears at - the top level of the schema is unique. - - - - - - - - - - - - - - This gives the model group for specifying the attributes in a complex - type, an extension or restriction. - - - - - - - - - - - - - - - This specifies the anyAttribute wildcard. - - - - - - - - - This specifies the content of a complexType element. As children, it can - have a simpleContent, a complexContent or a model group. Only if it has - one of the latter two, may it have a mixed attribute. This latter - constraint is something that cannot be specified in XML Schema. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This specifies the basic content of a complexType element. - - - - - - - - - - - - - - - - - - - - - - - - - - - This describes a restriction element within a complexContent element - (i.e. one that restricts a complex type). It has a base attribute, may - contain a model group and may contain attribute declarations of various - sorts. - - - - - - - - - - - - - - - - This specifies the basic model for an extension element: adding a - required base attribute to the model used for most components. - - - - - - - - - - This describes an extension element within a complexContent element - (i.e. one that restricts a complex type). It may contain a model group - and may contain attribute declarations of various sorts. - - - - - - - - - - - - - This describes a complexContent element. It may have a mixed attribute, - and either a restriction or extension element as content. - - - - - - - - - - - - - - - - - - This describes a restriction element that appears within a simpleContent - or simpleType element (i.e. one that restricts a simple type). Its - content follows the simple restriction model that is detailed below, and - may include attribute declarations. - - - - - - - - - - - This describes an extension element that appears within a simpleContent - element (i.e. one that extends a simple type). Like other extensions, it - has a base type, but it can only be used to add attributes. - - - - - - - - - - This describes a simpleContent element, whose content can either hold a - restriction or extension element. - - - - - - - - - - - - - This gives the possible values for block attributes on element elements, - which includes substitution amongst the list of possible values. This - RELAX NG schema, like the XML Schema Recommendation, allows each of the - keywords 'extension', 'restriction' and 'substitution' to occur more than - once within the list. - - - #all - - - - extension - restriction - substitution - - - - - - - - - This describes the basic content model of an element element. It is - annotated, may have a fixed or default attribute, and may have nillable - and/or block attributes. Its type may be specified through a type - attribute, a local simple type or a local complex type - the choice - between these methods is something that cannot be indicated with XML - Schema. This content is optionally followed by some identify constraints. - - - - - - - - - - - - - - - - - - - - - - - - - - - This describes an element element that appears at the top level of the - schema. On top of the basic content for an element element, it has to - have a name, which is a unique identifier in the element symbol space. It - may have substitutionGroup, abstract and/or final attributes. - - - - - - - - - - - - - - - - - - - - - - - - - This describes an element element that appears locally, within a - complexType or group element. It may have minOccurs and/or maxOccurs - attributes. If it has a ref attribute, then that's all it can - have. Otherwise, it must have a name and specifies its type in the same - way as the basic element content model described above. It may in this - case also have a form element. These constraints on local elements - cannot be described within XML Schema. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This gives the content of a model group (not a group element) in the - normal run of things. It has occurrence attributes and any number of - particles within it. - - - - - - - - - - - This gives the content of a model group (not a group element) within a - named group - it differs from the above in that it doesn't have any - occurrence attributes. - - - - - - - - - - This describes an all element that appears outside a named group (i.e. as - the content of a complexType element). It has the standard model for an - all element, but adds minOccurs and maxOccurs attributes which can only - take certain values. - - - - - - - - - This describes a choice element that appears outside a named group. - - - - - - - - - This describes a sequence element that appears outside a named group. - - - - - - - - - This describes a wildcard element (i.e. any or anyAttribute). The - namespace attribute can take a list URIs interspersed with the keywords - '##targetNamespace' and/or '##local'. This RELAX NG schema, like the XML - Schema Recommendation, allows the keywords to be specified more than once - each within the list, if they're given. This model also specifies the - processContents attribute. - - - - - - - ##any - ##other - - - - - ##targetNamespace - ##local - - - - - - - - lax - skip - strict - - - - - - - - - This describes an any element as a wildcard. - - - - - - - - - - - - - - - - - - This describes an import element that's used when its parent schema - element specifies a targetNamespace. In these cases, the namespace - attribute on the import element is optional. - - - - - - - - - - - - - - - - - - - - - - - This is designed to describe the content of the appinfo elements in the - schema. At the moment this allows any mixed content without validation. - Note that this is fairly complex compared to the XML Schema equivalent, - which would be a single any element. - - - - - - - - - - - - This describes an appinfo element. It has an optional source attribute - and can currently contain anything at all. - - - - - - - - - - - - - - This is designed to describe the content of the documentation elements in - the schema. At the moment this allows any mixed content without - validation. Note that this is fairly complex compared to the XML Schema - equivalent, which would be a single any element. - - - - - - - This describes a documentation element. It has optional source - and xml:lang attributes and can currently contain anything at all. - - - - - - - - - - - - - - - - - - - This describes an annotation element. It can have any attributes, may - have an id attribute, and contains any number of documentation or appinfo - elements. - - - - - - - - - - - - - - - - - - - - This gives the various types of derivation of simple types. - - - - - - - - - - - This specifies the values of the final attribute for simple types. This - RELAX NG schema for XML Schema, like the XML Schema Recommendation, allows - the keywords 'list', 'union' and 'restriction' to appear more than once - within the list. - - - #all - - - - list - union - restriction - - - - - - - - - - - - - - This gives the basic content of a simple type. - - - - - - - - - - - - - - - - - - - - - - This specifies the types of facets that are valid in restrictions on the - built-in data types. This can only perform rudimentary checking, but - should be enough in most circumstances. Note that for xs:anySimpleType - and xs:string, the whiteSpace facet can take any value, for - xs:normalizedString it can be 'replace' or 'collapse', and for all other - built-in types it has to be 'collapse'. - - - - - - - - - - - - - - - - - - - This describes a list element. It can either specify a local simple type - or have a itemType attribute. This constraint cannot be expressed in XML - Schema. - - - - - - - - - - - - - - - This describes a union element. If the memberTypes attribute is missing - or empty, then it must contain one or more simpleType elements; if - it's present, then it can contain simpleType elements or list simple - types in the memberTypes attribute. This constraint cannot be expressed - in XML Schema. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This is the basic content of a facet. It has an optional fixed attribute. - - - - - - - - - - - - This is the content of a facet that cannot be fixed (enumeration or - pattern). It has a value attribute that can take any kind of value. - - - - - - - - - - This describes an enumeration element. - - - - - - - - - diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/AttachmentPartImpl.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/AttachmentPartImpl.java index bc35f38f8da..ead4533885d 100644 --- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/AttachmentPartImpl.java +++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/AttachmentPartImpl.java @@ -582,7 +582,8 @@ public class AttachmentPartImpl extends AttachmentPart { mailMap.addMailcap("text/xml;;x-java-content-handler=com.sun.xml.internal.messaging.saaj.soap.XmlDataContentHandler"); mailMap.addMailcap("application/xml;;x-java-content-handler=com.sun.xml.internal.messaging.saaj.soap.XmlDataContentHandler"); mailMap.addMailcap("application/fastinfoset;;x-java-content-handler=com.sun.xml.internal.messaging.saaj.soap.FastInfosetDataContentHandler"); - mailMap.addMailcap("multipart/*;;x-java-content-handler=com.sun.xml.internal.messaging.saaj.soap.MultipartDataContentHandler"); + // this handler seems to be not used according VCS history ... + // mailMap.addMailcap("multipart/*;;x-java-content-handler=com.sun.xml.internal.messaging.saaj.soap.MultipartDataContentHandler"); mailMap.addMailcap("image/*;;x-java-content-handler=com.sun.xml.internal.messaging.saaj.soap.ImageDataContentHandler"); mailMap.addMailcap("text/plain;;x-java-content-handler=com.sun.xml.internal.messaging.saaj.soap.StringDataContentHandler"); } diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/rngom/parse/compact/CompactSyntax.jj b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/rngom/parse/compact/CompactSyntax.jj deleted file mode 100644 index c0b8d256cbd..00000000000 --- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/rngom/parse/compact/CompactSyntax.jj +++ /dev/null @@ -1,1963 +0,0 @@ -options { - STATIC = false; - UNICODE_INPUT = true; - JAVA_UNICODE_ESCAPE = true; -} - -PARSER_BEGIN(CompactSyntax) - -package com.sun.xml.internal.rngom.parse.compact; - -import java.io.Reader; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.List; - -import com.sun.xml.internal.rngom.ast.builder.Annotations; -import com.sun.xml.internal.rngom.ast.builder.BuildException; -import com.sun.xml.internal.rngom.ast.builder.CommentList; -import com.sun.xml.internal.rngom.ast.builder.DataPatternBuilder; -import com.sun.xml.internal.rngom.ast.builder.Div; -import com.sun.xml.internal.rngom.ast.builder.ElementAnnotationBuilder; -import com.sun.xml.internal.rngom.ast.builder.Grammar; -import com.sun.xml.internal.rngom.ast.builder.GrammarSection; -import com.sun.xml.internal.rngom.ast.builder.Include; -import com.sun.xml.internal.rngom.ast.builder.IncludedGrammar; -import com.sun.xml.internal.rngom.ast.builder.NameClassBuilder; -import com.sun.xml.internal.rngom.ast.builder.SchemaBuilder; -import com.sun.xml.internal.rngom.ast.builder.Scope; -import com.sun.xml.internal.rngom.ast.om.Location; -import com.sun.xml.internal.rngom.ast.om.ParsedElementAnnotation; -import com.sun.xml.internal.rngom.ast.om.ParsedNameClass; -import com.sun.xml.internal.rngom.ast.om.ParsedPattern; -import com.sun.xml.internal.rngom.parse.Context; -import com.sun.xml.internal.rngom.parse.IllegalSchemaException; -import com.sun.xml.internal.rngom.parse.Parseable; -import org.xml.sax.ErrorHandler; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.helpers.LocatorImpl; - -import com.sun.xml.internal.rngom.util.Localizer; -import com.sun.xml.internal.rngom.xml.util.WellKnownNamespaces; - - -public class CompactSyntax implements Context { - private static final int IN_ELEMENT = 0; - private static final int IN_ATTRIBUTE = 1; - private static final int IN_ANY_NAME = 2; - private static final int IN_NS_NAME = 4; - - private String defaultNamespace; - private String compatibilityPrefix = null; - private SchemaBuilder sb; - private NameClassBuilder ncb; - private String sourceUri; - /** - * This is what we are parsing right now. - */ - private CompactParseable parseable; - private ErrorHandler eh; - private final Hashtable namespaceTable = new Hashtable(); - private final Hashtable datatypesTable = new Hashtable(); - private boolean hadError = false; - private static final Localizer localizer = new Localizer(new Localizer(Parseable.class),CompactSyntax.class); - private final Hashtable attributeNameTable = new Hashtable(); - private boolean annotationsIncludeElements = false; - - /** - * String that represents the inherited namespace. - * - *

- * HACK: we always allocate a new String instance so that - * we can distinguish inherited value from the explicitly - * given value. - */ - private /*final*/ String inheritedNs; // essentially final but JavaCC don't let us declare it as so. - - final class LocatedString { - private final String str; - private final Token tok; - - LocatedString(String str, Token tok) { - this.str = str; - this.tok = tok; - } - - String getString() { - return str; - } - - Location getLocation() { - return makeLocation(tok); - } - - Token getToken() { - return tok; - } - - } - - public CompactSyntax(CompactParseable parseable, Reader r, String sourceUri, SchemaBuilder sb, ErrorHandler eh, String inheritedNs) { - this(r); - this.sourceUri = sourceUri; - this.parseable = parseable; - this.sb = sb; - this.ncb = sb.getNameClassBuilder(); - this.eh = eh; - // this causes the root pattern to have non-null annotations - // which is useful because it gives a context to trang - this.topLevelComments = sb.makeCommentList(); - this.inheritedNs = defaultNamespace = new String(inheritedNs); - } - - ParsedPattern parse(Scope scope) throws IllegalSchemaException { - try { - ParsedPattern p = Input(scope); - if (!hadError) - return p; - } - catch (ParseException e) { - error("syntax_error", e.getMessage(), e.currentToken.next); - } - catch (EscapeSyntaxException e) { - reportEscapeSyntaxException(e); - } - throw new IllegalSchemaException(); - } - - ParsedPattern parseInclude(IncludedGrammar g) throws IllegalSchemaException { - try { - ParsedPattern p = IncludedGrammar(g); - if (!hadError) - return p; - } - catch (ParseException e) { - error("syntax_error", e.getMessage(), e.currentToken.next); - } - catch (EscapeSyntaxException e) { - reportEscapeSyntaxException(e); - } - throw new IllegalSchemaException(); - } - - private void checkNsName(int context, LocatedString ns) { - if ((context & IN_NS_NAME) != 0) - error("ns_name_except_contains_ns_name", ns.getToken()); - } - - private void checkAnyName(int context, Token t) { - if ((context & IN_NS_NAME) != 0) - error("ns_name_except_contains_any_name", t); - if ((context & IN_ANY_NAME) != 0) - error("any_name_except_contains_any_name", t); - } - - private void error(String key, Token tok) { - doError(localizer.message(key), tok); - } - - private void error(String key, String arg, Token tok) { - doError(localizer.message(key, arg), tok); - } - - private void error(String key, String arg1, String arg2, Token tok) { - doError(localizer.message(key, arg1, arg2), tok); - } - - private void doError(String message, Token tok) { - hadError = true; - if (eh != null) { - LocatorImpl loc = new LocatorImpl(); - loc.setLineNumber(tok.beginLine); - loc.setColumnNumber(tok.beginColumn); - loc.setSystemId(sourceUri); - try { - eh.error(new SAXParseException(message, loc)); - } - catch (SAXException se) { - throw new BuildException(se); - } - } - } - - private void reportEscapeSyntaxException(EscapeSyntaxException e) { - if (eh != null) { - LocatorImpl loc = new LocatorImpl(); - loc.setLineNumber(e.getLineNumber()); - loc.setColumnNumber(e.getColumnNumber()); - loc.setSystemId(sourceUri); - try { - eh.error(new SAXParseException(localizer.message(e.getKey()), loc)); - } - catch (SAXException se) { - throw new BuildException(se); - } - } - } - - private static String unquote(String s) { - if (s.length() >= 6 && s.charAt(0) == s.charAt(1)) { - s = s.replace('\u0000', '\n'); - return s.substring(3, s.length() - 3); - } - else - return s.substring(1, s.length() - 1); - } - - Location makeLocation(Token t) { - return sb.makeLocation(sourceUri, t.beginLine, t.beginColumn); - } - - private static ParsedPattern[] addPattern(ParsedPattern[] patterns, int i, ParsedPattern p) { - if (i >= patterns.length) { - ParsedPattern[] oldPatterns = patterns; - patterns = new ParsedPattern[oldPatterns.length*2]; - System.arraycopy(oldPatterns, 0, patterns, 0, oldPatterns.length); - } - patterns[i] = p; - return patterns; - } - - String getCompatibilityPrefix() { - if (compatibilityPrefix == null) { - compatibilityPrefix = "a"; - while (namespaceTable.get(compatibilityPrefix) != null) - compatibilityPrefix = compatibilityPrefix + "a"; - } - return compatibilityPrefix; - } - - public String resolveNamespacePrefix(String prefix) { - String result = (String)namespaceTable.get(prefix); - if (result.length() == 0) - return null; - return result; - } - - public Enumeration prefixes() { - return namespaceTable.keys(); - } - - public String getBaseUri() { - return sourceUri; - } - - public boolean isUnparsedEntity(String entityName) { - return false; - } - - public boolean isNotation(String notationName) { - return false; - } - - public Context copy() { - return this; - } - - private Context getContext() { - return this; - } - - private CommentList getComments() { - return getComments(getTopLevelComments()); - } - - private CommentList topLevelComments; - - private CommentList getTopLevelComments() { - CommentList tem = topLevelComments; - topLevelComments = null; - return tem; - } - - private void noteTopLevelComments() { - topLevelComments = getComments(topLevelComments); - } - - private void topLevelComments(GrammarSection section) { - section.topLevelComment(getComments(null)); - } - - private Token lastCommentSourceToken = null; - - private CommentList getComments(CommentList comments) { - Token nextToken = getToken(1); - if (lastCommentSourceToken != nextToken) { - if (lastCommentSourceToken == null) - lastCommentSourceToken = token; - do { - lastCommentSourceToken = lastCommentSourceToken.next; - Token t = lastCommentSourceToken.specialToken; - if (t != null) { - while (t.specialToken != null) - t = t.specialToken; - if (comments == null) - comments = sb.makeCommentList(); - for (; t != null; t = t.next) { - String s = mungeComment(t.image); - Location loc = makeLocation(t); - if (t.next != null - && t.next.kind == CompactSyntaxConstants.SINGLE_LINE_COMMENT_CONTINUE) { - StringBuffer buf = new StringBuffer(s); - do { - t = t.next; - buf.append('\n'); - buf.append(mungeComment(t.image)); - } while (t.next != null - && t.next.kind == CompactSyntaxConstants.SINGLE_LINE_COMMENT_CONTINUE); - s = buf.toString(); - } - comments.addComment(s, loc); - } - } - } while (lastCommentSourceToken != nextToken); - } - return comments; - } - - private ParsedPattern afterComments(ParsedPattern p) { - CommentList comments = getComments(null); - if (comments == null) - return p; - return sb.commentAfter(p, comments); - } - - private ParsedNameClass afterComments(ParsedNameClass nc) { - CommentList comments = getComments(null); - if (comments == null) - return nc; - return ncb.commentAfter(nc, comments); - } - - private static String mungeComment(String image) { - int i = image.indexOf('#') + 1; - while (i < image.length() && image.charAt(i) == '#') - i++; - if (i < image.length() && image.charAt(i) == ' ') - i++; - return image.substring(i); - } - - private Annotations getCommentsAsAnnotations() { - CommentList comments = getComments(); - if (comments == null) - return null; - return sb.makeAnnotations(comments, getContext()); - } - - private Annotations addCommentsToChildAnnotations(Annotations a) { - CommentList comments = getComments(); - if (comments == null) - return a; - if (a == null) - a = sb.makeAnnotations(null, getContext()); - a.addComment(comments); - return a; - } - - private Annotations addCommentsToLeadingAnnotations(Annotations a) { - CommentList comments = getComments(); - if (comments == null) - return a; - if (a == null) - return sb.makeAnnotations(comments, getContext()); - a.addLeadingComment(comments); - return a; - } - - private Annotations getTopLevelCommentsAsAnnotations() { - CommentList comments = getTopLevelComments(); - if (comments == null) - return null; - return sb.makeAnnotations(comments, getContext()); - } - - private void clearAttributeList() { - attributeNameTable.clear(); - } - - private void addAttribute(Annotations a, String ns, String localName, String prefix, String value, Token tok) { - String key = ns + "#" + localName; - if (attributeNameTable.get(key) != null) - error("duplicate_attribute", ns, localName, tok); - else { - attributeNameTable.put(key, key); - a.addAttribute(ns, localName, prefix, value, makeLocation(tok)); - } - } - - private void checkExcept(Token[] except) { - if (except[0] != null) - error("except_missing_parentheses", except[0]); - } - - private String lookupPrefix(String prefix, Token t) { - String ns = (String)namespaceTable.get(prefix); - if (ns == null) { - error("undeclared_prefix", prefix, t); - return "#error"; - } - return ns; - } - private String lookupDatatype(String prefix, Token t) { - String ns = (String)datatypesTable.get(prefix); - if (ns == null) { - error("undeclared_prefix", prefix, t); - return ""; // XXX - } - return ns; - } - private String resolve(String str) { - try { - return new URL(new URL(sourceUri), str).toString(); - } - catch (MalformedURLException e) { } - return str; - } -} - -PARSER_END(CompactSyntax) - -ParsedPattern Input(Scope scope) : -{ - ParsedPattern p; -} -{ - Preamble() - (LOOKAHEAD(TopLevelLookahead()) p = TopLevelGrammar(scope) - | p = Expr(true, scope, null, null) { p = afterComments(p); } ) - { return p; } -} - -void TopLevelLookahead() : -{} -{ - "[" - | Identifier() ("[" | "=" | "&=" | "|=") - | LookaheadGrammarKeyword() - | LookaheadBody() LookaheadAfterAnnotations() - | LookaheadDocumentation() (LookaheadBody())? LookaheadAfterAnnotations() -} - -void LookaheadAfterAnnotations() : -{} -{ - Identifier() ("=" | "&=" | "|=") - | LookaheadGrammarKeyword() -} - -void LookaheadGrammarKeyword() : -{} -{ - "start" | "div" | "include" -} - -void LookaheadDocumentation() : -{} -{ - (( | ) ()*)+ -} - -void LookaheadBody() : -{} -{ - "[" - ( | UnprefixedName() | "=" | | "~" | LookaheadBody() )* - "]" -} - -ParsedPattern IncludedGrammar(IncludedGrammar g) : -{ - Annotations a; - ParsedPattern p; -} -{ - Preamble() - (LOOKAHEAD(TopLevelLookahead()) a = GrammarBody(g, g, getTopLevelCommentsAsAnnotations()) - | a = Annotations() "grammar" "{" a = GrammarBody(g, g, a) { topLevelComments(g); } "}") - { p = afterComments(g.endIncludedGrammar(sb.makeLocation(sourceUri, 1, 1), a)); } - - { return p; } -} - -ParsedPattern TopLevelGrammar(Scope scope) : -{ - Annotations a = getTopLevelCommentsAsAnnotations(); - Grammar g; - ParsedPattern p; -} -{ - { g = sb.makeGrammar(scope); } - a = GrammarBody(g, g, a) - { p = afterComments(g.endGrammar(sb.makeLocation(sourceUri, 1, 1), a)); } - - { return p; } -} - -void Preamble() : -{} -{ - (NamespaceDecl() | DatatypesDecl())* - { - namespaceTable.put("xml", WellKnownNamespaces.XML); - if (datatypesTable.get("xsd") == null) - datatypesTable.put("xsd", WellKnownNamespaces.XML_SCHEMA_DATATYPES); - } -} - -void NamespaceDecl() : -{ - LocatedString prefix = null; - boolean isDefault = false; - String namespaceName; -} -{ - { noteTopLevelComments(); } - (("namespace" prefix = UnprefixedName()) - | ("default" { isDefault = true; } - "namespace" (prefix = UnprefixedName())?)) - "=" - namespaceName = NamespaceName() - { - if (isDefault) - defaultNamespace = namespaceName; - if (prefix != null) { - if (prefix.getString().equals("xmlns")) - error("xmlns_prefix", prefix.getToken()); - else if (prefix.getString().equals("xml")) { - if (!namespaceName.equals(WellKnownNamespaces.XML)) - error("xml_prefix_bad_uri", prefix.getToken()); - } - else if (namespaceName.equals(WellKnownNamespaces.XML)) - error("xml_uri_bad_prefix", prefix.getToken()); - else { - if (namespaceName.equals(WellKnownNamespaces.RELAX_NG_COMPATIBILITY_ANNOTATIONS)) - compatibilityPrefix = prefix.getString(); - namespaceTable.put(prefix.getString(), namespaceName); - } - } - } -} - -String NamespaceName() : -{ - String r; -} -{ - (r = Literal() | "inherit" { r = this.inheritedNs; }) - { return r; } -} - -void DatatypesDecl() : -{ - LocatedString prefix; - String uri; -} -{ - { noteTopLevelComments(); } - "datatypes" prefix = UnprefixedName() "=" uri = Literal() - { - datatypesTable.put(prefix.getString(), uri); - } -} - -ParsedPattern AnnotatedPrimaryExpr(boolean topLevel, Scope scope, Token[] except) : -{ - Annotations a; - ParsedPattern p; - ParsedElementAnnotation e; - Token t; -} -{ - a = Annotations() - p = PrimaryExpr(topLevel, scope, a, except) - ( t = e = AnnotationElement(false) { - if (topLevel) - error("top_level_follow_annotation", t); - else - p = sb.annotateAfter(p, e); - })* - { return p; } -} - - -ParsedPattern PrimaryExpr(boolean topLevel, Scope scope, Annotations a, Token[] except) : -{ - ParsedPattern p; -} -{ - (p = ElementExpr(scope, a) - | p = AttributeExpr(scope, a) - | p = GrammarExpr(scope, a) - | p = ExternalRefExpr(scope, a) - | p = ListExpr(scope, a) - | p = MixedExpr(scope, a) - | p = ParenExpr(topLevel, scope, a) - | p = IdentifierExpr(scope, a) - | p = ParentExpr(scope, a) - | p = DataExpr(topLevel, scope, a, except) - | p = ValueExpr(topLevel, a) - | p = TextExpr(a) - | p = EmptyExpr(a) - | p = NotAllowedExpr(a)) - { return p; } -} - -ParsedPattern EmptyExpr(Annotations a) : -{ - Token t; -} -{ - t = "empty" - { return sb.makeEmpty(makeLocation(t), a); } -} - -ParsedPattern TextExpr(Annotations a) : -{ - Token t; -} -{ - t = "text" - { return sb.makeText(makeLocation(t), a); } -} - -ParsedPattern NotAllowedExpr(Annotations a) : -{ - Token t; -} -{ - t = "notAllowed" - { return sb.makeNotAllowed(makeLocation(t), a); } -} - -ParsedPattern Expr(boolean topLevel, Scope scope, Token t, Annotations a) : -{ - List patterns = new ArrayList(); - ParsedPattern p; - boolean[] hadOccur = new boolean[1]; - Token[] except = new Token[1]; -} -{ - p = UnaryExpr(topLevel, scope, hadOccur, except) - { patterns.add(p); } - ( - { checkExcept(except); } - (t = "|" p = UnaryExpr(topLevel, scope, null, except) - { patterns.add(p); checkExcept(except); } )+ - { p = sb.makeChoice(patterns, makeLocation(t), a); } - | (t = "&" p = UnaryExpr(topLevel, scope, null, except) - { patterns.add(p); checkExcept(except); } )+ - { p = sb.makeInterleave(patterns, makeLocation(t), a); } - | (t = "," p = UnaryExpr(topLevel, scope, null, except) - { patterns.add(p); checkExcept(except); } )+ - { p = sb.makeGroup(patterns, makeLocation(t), a); } - )? - { - if (patterns.size() == 1 && a != null) { - if (hadOccur[0]) - p = sb.annotate(p, a); - else - p = sb.makeGroup(patterns, makeLocation(t), a); - } - return p; - } -} - -ParsedPattern UnaryExpr(boolean topLevel, Scope scope, boolean[] hadOccur, Token[] except) : -{ - ParsedPattern p; - Token t; - ParsedElementAnnotation e; -} -{ - p = AnnotatedPrimaryExpr(topLevel, scope, except) - ( - { - if (hadOccur != null) hadOccur[0] = true; - p = afterComments(p); - } - (t = "+" { checkExcept(except); p = sb.makeOneOrMore(p, makeLocation(t), null); } - | t = "?" { checkExcept(except); p = sb.makeOptional(p, makeLocation(t), null); } - | t = "*" { checkExcept(except); p = sb.makeZeroOrMore(p, makeLocation(t), null); }) - ( t = e = AnnotationElement(false) { - if (topLevel) - error("top_level_follow_annotation", t); - else - p = sb.annotateAfter(p, e); - } )* - )? - { return p; } -} - -ParsedPattern ElementExpr(Scope scope, Annotations a) : -{ - Token t; - ParsedNameClass nc; - ParsedPattern p; -} -{ - t = "element" - nc = NameClass(IN_ELEMENT, null) - "{" - p = Expr(false, scope, null, null) - { p = afterComments(p); } - "}" - { return sb.makeElement(nc, p, makeLocation(t), a); } -} - -ParsedPattern AttributeExpr(Scope scope, Annotations a) : -{ - Token t; - ParsedNameClass nc; - ParsedPattern p; -} -{ - t = "attribute" - nc = NameClass(IN_ATTRIBUTE, null) - "{" - p = Expr(false, scope, null, null) - { p = afterComments(p); } - "}" - { return sb.makeAttribute(nc, p, makeLocation(t), a); } -} - -ParsedNameClass NameClass(int context, Annotations[] pa) : -{ - Annotations a; - ParsedNameClass nc; -} -{ - a = Annotations() - (nc = PrimaryNameClass(context, a) nc = AnnotateAfter(nc) nc = NameClassAlternatives(context, nc, pa) - | nc = AnyNameExceptClass(context, a, pa) - | nc = NsNameExceptClass(context, a, pa)) - { return nc; } -} - -ParsedNameClass AnnotateAfter(ParsedNameClass nc) : -{ - ParsedElementAnnotation e; -} -{ - ( e = AnnotationElement(false) { nc = ncb.annotateAfter(nc, e); })* - { return nc; } -} - -ParsedNameClass NameClassAlternatives(int context, ParsedNameClass nc, Annotations[] pa) : -{ - Token t; - ParsedNameClass[] nameClasses; - int nNameClasses; -} -{ - ( - { - nameClasses = new ParsedNameClass[2]; - nameClasses[0] = nc; - nNameClasses = 1; - } - (t = "|" nc = BasicNameClass(context) nc = AnnotateAfter(nc) - { - if (nNameClasses >= nameClasses.length) { - ParsedNameClass[] oldNameClasses = nameClasses; - nameClasses = new ParsedNameClass[oldNameClasses.length*2]; - System.arraycopy(oldNameClasses, 0, nameClasses, 0, oldNameClasses.length); - } - nameClasses[nNameClasses++] = nc; - })+ - { - Annotations a; - if (pa == null) - a = null; - else { - a = pa[0]; - pa[0] = null; - } - nc = ncb.makeChoice(Arrays.asList(nameClasses).subList(0,nNameClasses), makeLocation(t), a); - } - )? - { return nc; } -} - -ParsedNameClass BasicNameClass(int context) : -{ - Annotations a; - ParsedNameClass nc; -} -{ - a = Annotations() - (nc = PrimaryNameClass(context, a) - | nc = OpenNameClass(context, a)) - { return nc; } -} - -ParsedNameClass PrimaryNameClass(int context, Annotations a) : -{ - ParsedNameClass nc; -} -{ - (nc = UnprefixedNameClass(context, a) - | nc = PrefixedNameClass(a) - | nc = ParenNameClass(context, a)) - { return nc; } -} - -ParsedNameClass OpenNameClass(int context, Annotations a) : -{ - Token t; - LocatedString ns; -} -{ - ns = NsName() { checkNsName(context, ns); return ncb.makeNsName(ns.getString(), ns.getLocation(), a); } - | t = "*" { checkAnyName(context, t); return ncb.makeAnyName(makeLocation(t), a); } -} - - -ParsedNameClass UnprefixedNameClass(int context, Annotations a) : -{ - LocatedString name; -} -{ - name = UnprefixedName() - { - String ns; - if ((context & (IN_ATTRIBUTE|IN_ELEMENT)) == IN_ATTRIBUTE) - ns = ""; - else - ns = defaultNamespace; - return ncb.makeName(ns, name.getString(), null, name.getLocation(), a); - } -} - -ParsedNameClass PrefixedNameClass(Annotations a) : -{ - Token t; -} -{ - t = - { - String qn = t.image; - int colon = qn.indexOf(':'); - String prefix = qn.substring(0, colon); - return ncb.makeName(lookupPrefix(prefix, t), qn.substring(colon + 1), prefix, makeLocation(t), a); - } -} - -ParsedNameClass NsNameExceptClass(int context, Annotations a, Annotations[] pa) : -{ - LocatedString ns; - ParsedNameClass nc; -} -{ - ns = NsName() - { checkNsName(context, ns); } - (nc = ExceptNameClass(context | IN_NS_NAME) - { nc = ncb.makeNsName(ns.getString(), nc, ns.getLocation(), a); } - nc = AnnotateAfter(nc) - | { nc = ncb.makeNsName(ns.getString(), ns.getLocation(), a); } - nc = AnnotateAfter(nc) - nc = NameClassAlternatives(context, nc, pa)) - { return nc; } -} - -LocatedString NsName() : -{ - Token t; -} -{ - t = - { - String qn = t.image; - String prefix = qn.substring(0, qn.length() - 2); - return new LocatedString(lookupPrefix(prefix, t), t); - } -} - -ParsedNameClass AnyNameExceptClass(int context, Annotations a, Annotations[] pa) : -{ - Token t; - ParsedNameClass nc; -} -{ - t = "*" - { checkAnyName(context, t); } - (nc = ExceptNameClass(context | IN_ANY_NAME) - { nc = ncb.makeAnyName(nc, makeLocation(t), a); } - nc = AnnotateAfter(nc) - | { nc = ncb.makeAnyName(makeLocation(t), a); } - nc = AnnotateAfter(nc) - nc = NameClassAlternatives(context, nc, pa)) - { return nc; } -} - -ParsedNameClass ParenNameClass(int context, Annotations a) : -{ - Token t; - ParsedNameClass nc; - Annotations[] pa = new Annotations[]{ a }; -} -{ - t = "(" nc = NameClass(context, pa) { nc = afterComments(nc); } ")" - { - if (pa[0] != null) - nc = ncb.makeChoice(Collections.singletonList(nc), makeLocation(t), pa[0]); - return nc; - } -} - -ParsedNameClass ExceptNameClass(int context) : -{ - ParsedNameClass nc; -} -{ - "-" nc = BasicNameClass(context) - { return nc; } -} - -ParsedPattern ListExpr(Scope scope, Annotations a) : -{ - Token t; - ParsedPattern p; -} -{ - t = "list" - "{" - p = Expr(false, scope, null, null) - { p = afterComments(p); } - "}" - { return sb.makeList(p, makeLocation(t), a); } -} - -ParsedPattern MixedExpr(Scope scope, Annotations a) : -{ - Token t; - ParsedPattern p; -} -{ - t = "mixed" - "{" - p = Expr(false, scope, null, null) - { p = afterComments(p); } - "}" - { return sb.makeMixed(p, makeLocation(t), a); } -} - -ParsedPattern GrammarExpr(Scope scope, Annotations a) : -{ - Token t; - Grammar g; -} -{ - t = "grammar" { g = sb.makeGrammar(scope); } - "{" a = GrammarBody(g, g, a) { topLevelComments(g); } "}" - { return g.endGrammar(makeLocation(t), a); } -} - -ParsedPattern ParenExpr(boolean topLevel, Scope scope, Annotations a) : -{ - Token t; - ParsedPattern p; -} -{ - t = "(" p = Expr(topLevel, scope, t, a) { p = afterComments(p); } ")" - { return p; } -} - -Annotations GrammarBody(GrammarSection section, Scope scope, Annotations a) : -{ - ParsedElementAnnotation e; -} -{ - (LOOKAHEAD(2) e = AnnotationElementNotKeyword() - { if (a == null) a = sb.makeAnnotations(null, getContext()); a.addElement(e); })* - (GrammarComponent(section, scope))* - { return a; } -} - -void GrammarComponent(GrammarSection section, Scope scope) : -{ - ParsedElementAnnotation e; - Annotations a; -} -{ - (a = Annotations() - (Definition(section, scope, a) - | Include(section, scope, a) - | Div(section, scope, a))) - (LOOKAHEAD(2) e = AnnotationElementNotKeyword() { section.topLevelAnnotation(e); })* -} - -void Definition(GrammarSection section, Scope scope, Annotations a) : -{} -{ - (Define(section, scope, a) | Start(section, scope, a)) -} - -void Start(GrammarSection section, Scope scope, Annotations a) : -{ - Token t; - GrammarSection.Combine combine; - ParsedPattern p; -} -{ - t = "start" combine = AssignOp() p = Expr(false, scope, null, null) - { section.define(GrammarSection.START, combine, p, makeLocation(t), a); } -} - -void Define(GrammarSection section, Scope scope, Annotations a) : -{ - LocatedString name; - GrammarSection.Combine combine; - ParsedPattern p; -} -{ - name = Identifier() combine = AssignOp() p = Expr(false, scope, null, null) - { section.define(name.getString(), combine, p, name.getLocation(), a); } -} - -GrammarSection.Combine AssignOp() : -{} -{ - "=" { return null; } - | "|=" { return GrammarSection.COMBINE_CHOICE; } - | "&=" { return GrammarSection.COMBINE_INTERLEAVE; } -} - -void Include(GrammarSection section, Scope scope, Annotations a) : -{ - Token t; - String href; - String ns; - Include include = section.makeInclude(); -} -{ - t = "include" href = Literal() - ns = Inherit() - ("{" a = IncludeBody(include, scope, a) { topLevelComments(include); } "}")? - { - try { - include.endInclude(parseable, resolve(href), ns, makeLocation(t), a); - } - catch (IllegalSchemaException e) { } - } -} - -Annotations IncludeBody(GrammarSection section, Scope scope, Annotations a) : -{ - ParsedElementAnnotation e; -} -{ - (LOOKAHEAD(2) e = AnnotationElementNotKeyword() - { if (a == null) a = sb.makeAnnotations(null, getContext()); a.addElement(e); })* - (IncludeComponent(section, scope))* - { return a; } -} - - -void IncludeComponent(GrammarSection section, Scope scope) : -{ - ParsedElementAnnotation e; - Annotations a; -} -{ - (a = Annotations() (Definition(section, scope, a) - | IncludeDiv(section, scope, a))) - (LOOKAHEAD(2) e = AnnotationElementNotKeyword() { section.topLevelAnnotation(e); })* -} - -void Div(GrammarSection section, Scope scope, Annotations a) : -{ - Token t; - Div div = section.makeDiv(); -} -{ - t = "div" "{" a = GrammarBody(div, scope, a) { topLevelComments(div); } "}" - { div.endDiv(makeLocation(t), a); } -} - -void IncludeDiv(GrammarSection section, Scope scope, Annotations a) : -{ - Token t; - Div div = section.makeDiv(); -} -{ - t = "div" "{" a = IncludeBody(div, scope, a) { topLevelComments(div); } "}" - { div.endDiv(makeLocation(t), a); } -} - -ParsedPattern ExternalRefExpr(Scope scope, Annotations a) : -{ - Token t; - String href; - String ns; -} -{ - t = "external" href = Literal() - ns = Inherit() - { - try { - return sb.makeExternalRef(parseable, resolve(href), ns, scope, makeLocation(t), a); - } - catch (IllegalSchemaException e) { - return sb.makeErrorPattern(); - } - } -} - -String Inherit() : -{ - String ns = null; -} -{ - ("inherit" "=" ns = Prefix())? - { - if (ns == null) - ns = defaultNamespace; - return ns; - } -} - -ParsedPattern ParentExpr(Scope scope, Annotations a) : -{ - LocatedString name; -} -{ - "parent" { a = addCommentsToChildAnnotations(a); } name = Identifier() - { - if(scope==null) { - error("parent_ref_outside_grammar",name.getToken()); - return sb.makeErrorPattern(); - } else { - return scope.makeParentRef(name.getString(), name.getLocation(), a); - } - } -} - -ParsedPattern IdentifierExpr(Scope scope, Annotations a) : -{ - LocatedString name; -} -{ - name = Identifier() - { - if(scope==null) { - error("ref_outside_grammar",name.getToken()); - return sb.makeErrorPattern(); - } else { - return scope.makeRef(name.getString(), name.getLocation(), a); - } - } -} - -ParsedPattern ValueExpr(boolean topLevel, Annotations a) : -{ - LocatedString s; -} -{ - s = LocatedLiteral() - { - if (topLevel && annotationsIncludeElements) { - error("top_level_follow_annotation", s.getToken()); - a = null; - } - return sb.makeValue("", "token", s.getString(), getContext(), defaultNamespace, s.getLocation(), a); - } -} - -ParsedPattern DataExpr(boolean topLevel, Scope scope, Annotations a, Token[] except) : -{ - Token datatypeToken; - Location loc; - String datatype; - String datatypeUri = null; - String s = null; - ParsedPattern e = null; - DataPatternBuilder dpb; -} -{ - datatypeToken = DatatypeName() - { - datatype = datatypeToken.image; - loc = makeLocation(datatypeToken); - int colon = datatype.indexOf(':'); - if (colon < 0) - datatypeUri = ""; - else { - String prefix = datatype.substring(0, colon); - datatypeUri = lookupDatatype(prefix, datatypeToken); - datatype = datatype.substring(colon + 1); - } - } - ((s = Literal() - { - if (topLevel && annotationsIncludeElements) { - error("top_level_follow_annotation", datatypeToken); - a = null; - } - return sb.makeValue(datatypeUri, datatype, s, getContext(), defaultNamespace, loc, a); - } - ) - | ( { dpb = sb.makeDataPatternBuilder(datatypeUri, datatype, loc); } - ( (Params(dpb) (e = Except(scope, except))?) - | (e = Except(scope, except))?) - { return e == null ? dpb.makePattern(loc, a) : dpb.makePattern(e, loc, a); })) -} - -Token DatatypeName() : -{ - Token t; -} -{ - (t = "string" | t = "token" | t = ) - { return t; } -} - -LocatedString Identifier() : -{ - LocatedString s; - Token t; -} -{ - (t = { s = new LocatedString(t.image, t); } - | t = { s = new LocatedString(t.image.substring(1), t); }) - { return s; } -} - -String Prefix() : -{ - Token t; - String prefix; -} -{ - (t = { prefix = t.image; } - | t = { prefix = t.image.substring(1); } - | t = Keyword() { prefix = t.image; }) - { return lookupPrefix(prefix, t); } -} - -LocatedString UnprefixedName() : -{ - LocatedString s; - Token t; -} -{ - (s = Identifier() - | t = Keyword() { s = new LocatedString(t.image, t); }) - { return s; } -} - -void Params(DataPatternBuilder dpb) : -{} -{ - "{" (Param(dpb))* "}" -} - -void Param(DataPatternBuilder dpb) : -{ - LocatedString name; - Annotations a; - String value; -} -{ - a = Annotations() name = UnprefixedName() "=" { a = addCommentsToLeadingAnnotations(a); } value = Literal() - { dpb.addParam(name.getString(), value, getContext(), defaultNamespace, name.getLocation(), a); } -} - -ParsedPattern Except(Scope scope, Token[] except) : -{ - Annotations a; - ParsedPattern p; - Token t; - Token[] innerExcept = new Token[1]; -} -{ - t = "-" a = Annotations() p = PrimaryExpr(false, scope, a, innerExcept) - { - checkExcept(innerExcept); - except[0] = t; - return p; - } -} - -ParsedElementAnnotation Documentation() : -{ - CommentList comments = getComments(); - ElementAnnotationBuilder eab; - Token t; -} -{ - (t = | t = ) - { - eab = sb.makeElementAnnotationBuilder(WellKnownNamespaces.RELAX_NG_COMPATIBILITY_ANNOTATIONS, - "documentation", - getCompatibilityPrefix(), - makeLocation(t), - comments, - getContext()); - eab.addText(mungeComment(t.image), makeLocation(t), null); - } - (t = { eab.addText("\n" + mungeComment(t.image), makeLocation(t), null); })* - { return eab.makeElementAnnotation(); } -} - -Annotations Annotations() : -{ - CommentList comments = getComments(); - Annotations a = null; - ParsedElementAnnotation e; -} -{ - ( { a = sb.makeAnnotations(comments, getContext()); } - (e = Documentation() { a.addElement(e); })+ - { - comments = getComments(); - if (comments != null) - a.addLeadingComment(comments); - } - )? - ("[" { if (a == null) a = sb.makeAnnotations(comments, getContext()); clearAttributeList(); annotationsIncludeElements = false; } - (LOOKAHEAD(2) PrefixedAnnotationAttribute(a, false) )* - ( e = AnnotationElement(false) { a.addElement(e); annotationsIncludeElements = true; } )* - { a.addComment(getComments()); } - "]")? - { - if (a == null && comments != null) - a = sb.makeAnnotations(comments, getContext()); - return a; - } -} - -void AnnotationAttribute(Annotations a) : -{} -{ - PrefixedAnnotationAttribute(a, true) | UnprefixedAnnotationAttribute(a) -} - -void PrefixedAnnotationAttribute(Annotations a, boolean nested) : -{ - Token t; - String value; -} -{ - t = "=" value = Literal() - { - String qn = t.image; - int colon = qn.indexOf(':'); - String prefix = qn.substring(0, colon); - String ns = lookupPrefix(prefix, t); - if (ns == this.inheritedNs) - error("inherited_annotation_namespace", t); - else if (ns.length() == 0 && !nested) - error("unqualified_annotation_attribute", t); - else if (ns.equals(WellKnownNamespaces.RELAX_NG) && !nested) - error("relax_ng_namespace", t); - /*else if (ns.length() == 0 - && qn.length() - colon - 1 == 5 - && qn.regionMatches(colon + 1, "xmlns", 0, 5)) - error("xmlns_annotation_attribute", t);*/ - else if (ns.equals(WellKnownNamespaces.XMLNS)) - error("xmlns_annotation_attribute_uri", t); - else { - if (ns.length() == 0) - prefix = null; - addAttribute(a, ns, qn.substring(colon + 1), prefix, value, t); - } - } -} - -void UnprefixedAnnotationAttribute(Annotations a) : -{ - LocatedString name; - String value; -} -{ - name = UnprefixedName() "=" value = Literal() - { - if (name.getString().equals("xmlns")) - error("xmlns_annotation_attribute", name.getToken()); - else - addAttribute(a, "", name.getString(), null, value, name.getToken()); - } -} - -ParsedElementAnnotation AnnotationElement(boolean nested) : -{ - ParsedElementAnnotation a; -} -{ - (a = PrefixedAnnotationElement(nested) - | a = UnprefixedAnnotationElement()) - { return a; } -} - -ParsedElementAnnotation AnnotationElementNotKeyword() : -{ - ParsedElementAnnotation a; -} -{ - (a = PrefixedAnnotationElement(false) - | a = IdentifierAnnotationElement()) - { return a; } -} - -ParsedElementAnnotation PrefixedAnnotationElement(boolean nested) : -{ - CommentList comments = getComments(); - Token t; - ElementAnnotationBuilder eab; -} -{ - t = - { - String qn = t.image; - int colon = qn.indexOf(':'); - String prefix = qn.substring(0, colon); - String ns = lookupPrefix(prefix, t); - if (ns == this.inheritedNs) { - error("inherited_annotation_namespace", t); - ns = ""; - } - else if (!nested && ns.equals(WellKnownNamespaces.RELAX_NG)) { - error("relax_ng_namespace", t); - ns = ""; - } - else { - if (ns.length() == 0) - prefix = null; - } - eab = sb.makeElementAnnotationBuilder(ns, qn.substring(colon + 1), prefix, - makeLocation(t), comments, getContext()); - } - AnnotationElementContent(eab) - { return eab.makeElementAnnotation(); } -} - -ParsedElementAnnotation UnprefixedAnnotationElement() : -{ - CommentList comments = getComments(); - LocatedString name; - ElementAnnotationBuilder eab; -} -{ - name = UnprefixedName() - { - eab = sb.makeElementAnnotationBuilder("", name.getString(), null, - name.getLocation(), comments, getContext()); - } - AnnotationElementContent(eab) - { return eab.makeElementAnnotation(); } -} - -ParsedElementAnnotation IdentifierAnnotationElement() : -{ - CommentList comments = getComments(); - LocatedString name; - ElementAnnotationBuilder eab; -} -{ - name = Identifier() - { - eab = sb.makeElementAnnotationBuilder("", name.getString(), null, - name.getLocation(), comments, getContext()); - } - AnnotationElementContent(eab) - { return eab.makeElementAnnotation(); } -} - -void AnnotationElementContent(ElementAnnotationBuilder eab) : -{ - ParsedElementAnnotation e; -} -{ - "[" { clearAttributeList(); } - (LOOKAHEAD(2) AnnotationAttribute(eab))* - ((AnnotationElementLiteral(eab) - ("~" AnnotationElementLiteral(eab))*) - | e = AnnotationElement(true) { eab.addElement(e); })* - { eab.addComment(getComments()); } - "]" -} - -void AnnotationElementLiteral(ElementAnnotationBuilder eab) : -{ - Token t; - CommentList comments = getComments(); -} -{ - t = { eab.addText(unquote(t.image), makeLocation(t), comments); } -} - -String Literal() : -{ - Token t; - String s; - StringBuffer buf; -} -{ - t = - { - s = unquote(t.image); - } - ( - { buf = new StringBuffer(s); } - ("~" t = { buf.append(unquote(t.image)); })+ - { s = buf.toString(); } - )? - { return s; } -} - -LocatedString LocatedLiteral() : -{ - Token t; - Token t2; - String s; - StringBuffer buf; -} -{ - t = - { - s = unquote(t.image); - } - ( - { buf = new StringBuffer(s); } - ("~" t2 = { buf.append(unquote(t2.image)); })+ - { s = buf.toString(); } - )? - { return new LocatedString(s, t); } -} - -Token Keyword() : -{ - Token t; -} -{ - (t = "element" - | t = "attribute" - | t = "namespace" - | t = "list" - | t = "mixed" - | t = "grammar" - | t = "empty" - | t = "text" - | t = "parent" - | t = "external" - | t = "notAllowed" - | t = "start" - | t = "include" - | t = "default" - | t = "inherit" - | t = "string" - | t = "token" - | t = "datatypes" - | t = "div") - { return t; } -} - -<*> -SKIP: { - < #NEWLINE : [ "\u0000", "\n" ] > - | < #NOT_NEWLINE : ~[ "\u0000", "\n" ] > - | < WS: ([ "\u0000", " ", "\n", "\t" ])+ > : DEFAULT -} - -TOKEN : -{ - < DOCUMENTATION: "##" ()* > : AFTER_DOCUMENTATION -} - - -TOKEN : -{ - < DOCUMENTATION_CONTINUE: ([" ", "\t"])* > -} - -SPECIAL_TOKEN: -{ - < SINGLE_LINE_COMMENT: "#" ()* > : AFTER_SINGLE_LINE_COMMENT -} - - -TOKEN : -{ - < DOCUMENTATION_AFTER_SINGLE_LINE_COMMENT: ([" ", "\t"])* > : AFTER_DOCUMENTATION -} - - -SPECIAL_TOKEN : -{ - < SINGLE_LINE_COMMENT_CONTINUE: ([" ", "\t"])* > -} - -TOKEN : -{ - < #BASE_CHAR : [ - "\u0041" - "\u005a", - "\u0061" - "\u007a", - "\u00c0" - "\u00d6", - "\u00d8" - "\u00f6", - "\u00f8" - "\u00ff", - "\u0100" - "\u0131", - "\u0134" - "\u013e", - "\u0141" - "\u0148", - "\u014a" - "\u017e", - "\u0180" - "\u01c3", - "\u01cd" - "\u01f0", - "\u01f4" - "\u01f5", - "\u01fa" - "\u0217", - "\u0250" - "\u02a8", - "\u02bb" - "\u02c1", - "\u0386", - "\u0388" - "\u038a", - "\u038c", - "\u038e" - "\u03a1", - "\u03a3" - "\u03ce", - "\u03d0" - "\u03d6", - "\u03da", - "\u03dc", - "\u03de", - "\u03e0", - "\u03e2" - "\u03f3", - "\u0401" - "\u040c", - "\u040e" - "\u044f", - "\u0451" - "\u045c", - "\u045e" - "\u0481", - "\u0490" - "\u04c4", - "\u04c7" - "\u04c8", - "\u04cb" - "\u04cc", - "\u04d0" - "\u04eb", - "\u04ee" - "\u04f5", - "\u04f8" - "\u04f9", - "\u0531" - "\u0556", - "\u0559", - "\u0561" - "\u0586", - "\u05d0" - "\u05ea", - "\u05f0" - "\u05f2", - "\u0621" - "\u063a", - "\u0641" - "\u064a", - "\u0671" - "\u06b7", - "\u06ba" - "\u06be", - "\u06c0" - "\u06ce", - "\u06d0" - "\u06d3", - "\u06d5", - "\u06e5" - "\u06e6", - "\u0905" - "\u0939", - "\u093d", - "\u0958" - "\u0961", - "\u0985" - "\u098c", - "\u098f" - "\u0990", - "\u0993" - "\u09a8", - "\u09aa" - "\u09b0", - "\u09b2", - "\u09b6" - "\u09b9", - "\u09dc" - "\u09dd", - "\u09df" - "\u09e1", - "\u09f0" - "\u09f1", - "\u0a05" - "\u0a0a", - "\u0a0f" - "\u0a10", - "\u0a13" - "\u0a28", - "\u0a2a" - "\u0a30", - "\u0a32" - "\u0a33", - "\u0a35" - "\u0a36", - "\u0a38" - "\u0a39", - "\u0a59" - "\u0a5c", - "\u0a5e", - "\u0a72" - "\u0a74", - "\u0a85" - "\u0a8b", - "\u0a8d", - "\u0a8f" - "\u0a91", - "\u0a93" - "\u0aa8", - "\u0aaa" - "\u0ab0", - "\u0ab2" - "\u0ab3", - "\u0ab5" - "\u0ab9", - "\u0abd", - "\u0ae0", - "\u0b05" - "\u0b0c", - "\u0b0f" - "\u0b10", - "\u0b13" - "\u0b28", - "\u0b2a" - "\u0b30", - "\u0b32" - "\u0b33", - "\u0b36" - "\u0b39", - "\u0b3d", - "\u0b5c" - "\u0b5d", - "\u0b5f" - "\u0b61", - "\u0b85" - "\u0b8a", - "\u0b8e" - "\u0b90", - "\u0b92" - "\u0b95", - "\u0b99" - "\u0b9a", - "\u0b9c", - "\u0b9e" - "\u0b9f", - "\u0ba3" - "\u0ba4", - "\u0ba8" - "\u0baa", - "\u0bae" - "\u0bb5", - "\u0bb7" - "\u0bb9", - "\u0c05" - "\u0c0c", - "\u0c0e" - "\u0c10", - "\u0c12" - "\u0c28", - "\u0c2a" - "\u0c33", - "\u0c35" - "\u0c39", - "\u0c60" - "\u0c61", - "\u0c85" - "\u0c8c", - "\u0c8e" - "\u0c90", - "\u0c92" - "\u0ca8", - "\u0caa" - "\u0cb3", - "\u0cb5" - "\u0cb9", - "\u0cde", - "\u0ce0" - "\u0ce1", - "\u0d05" - "\u0d0c", - "\u0d0e" - "\u0d10", - "\u0d12" - "\u0d28", - "\u0d2a" - "\u0d39", - "\u0d60" - "\u0d61", - "\u0e01" - "\u0e2e", - "\u0e30", - "\u0e32" - "\u0e33", - "\u0e40" - "\u0e45", - "\u0e81" - "\u0e82", - "\u0e84", - "\u0e87" - "\u0e88", - "\u0e8a", - "\u0e8d", - "\u0e94" - "\u0e97", - "\u0e99" - "\u0e9f", - "\u0ea1" - "\u0ea3", - "\u0ea5", - "\u0ea7", - "\u0eaa" - "\u0eab", - "\u0ead" - "\u0eae", - "\u0eb0", - "\u0eb2" - "\u0eb3", - "\u0ebd", - "\u0ec0" - "\u0ec4", - "\u0f40" - "\u0f47", - "\u0f49" - "\u0f69", - "\u10a0" - "\u10c5", - "\u10d0" - "\u10f6", - "\u1100", - "\u1102" - "\u1103", - "\u1105" - "\u1107", - "\u1109", - "\u110b" - "\u110c", - "\u110e" - "\u1112", - "\u113c", - "\u113e", - "\u1140", - "\u114c", - "\u114e", - "\u1150", - "\u1154" - "\u1155", - "\u1159", - "\u115f" - "\u1161", - "\u1163", - "\u1165", - "\u1167", - "\u1169", - "\u116d" - "\u116e", - "\u1172" - "\u1173", - "\u1175", - "\u119e", - "\u11a8", - "\u11ab", - "\u11ae" - "\u11af", - "\u11b7" - "\u11b8", - "\u11ba", - "\u11bc" - "\u11c2", - "\u11eb", - "\u11f0", - "\u11f9", - "\u1e00" - "\u1e9b", - "\u1ea0" - "\u1ef9", - "\u1f00" - "\u1f15", - "\u1f18" - "\u1f1d", - "\u1f20" - "\u1f45", - "\u1f48" - "\u1f4d", - "\u1f50" - "\u1f57", - "\u1f59", - "\u1f5b", - "\u1f5d", - "\u1f5f" - "\u1f7d", - "\u1f80" - "\u1fb4", - "\u1fb6" - "\u1fbc", - "\u1fbe", - "\u1fc2" - "\u1fc4", - "\u1fc6" - "\u1fcc", - "\u1fd0" - "\u1fd3", - "\u1fd6" - "\u1fdb", - "\u1fe0" - "\u1fec", - "\u1ff2" - "\u1ff4", - "\u1ff6" - "\u1ffc", - "\u2126", - "\u212a" - "\u212b", - "\u212e", - "\u2180" - "\u2182", - "\u3041" - "\u3094", - "\u30a1" - "\u30fa", - "\u3105" - "\u312c", - "\uac00" - "\ud7a3" - ] > - | < #IDEOGRAPHIC : [ - "\u4e00" - "\u9fa5", - "\u3007", - "\u3021" - "\u3029" - ] > - | < #LETTER : ( | ) > - | < #COMBINING_CHAR : [ - "\u0300" - "\u0345", - "\u0360" - "\u0361", - "\u0483" - "\u0486", - "\u0591" - "\u05a1", - "\u05a3" - "\u05b9", - "\u05bb" - "\u05bd", - "\u05bf", - "\u05c1" - "\u05c2", - "\u05c4", - "\u064b" - "\u0652", - "\u0670", - "\u06d6" - "\u06dc", - "\u06dd" - "\u06df", - "\u06e0" - "\u06e4", - "\u06e7" - "\u06e8", - "\u06ea" - "\u06ed", - "\u0901" - "\u0903", - "\u093c", - "\u093e" - "\u094c", - "\u094d", - "\u0951" - "\u0954", - "\u0962" - "\u0963", - "\u0981" - "\u0983", - "\u09bc", - "\u09be", - "\u09bf", - "\u09c0" - "\u09c4", - "\u09c7" - "\u09c8", - "\u09cb" - "\u09cd", - "\u09d7", - "\u09e2" - "\u09e3", - "\u0a02", - "\u0a3c", - "\u0a3e", - "\u0a3f", - "\u0a40" - "\u0a42", - "\u0a47" - "\u0a48", - "\u0a4b" - "\u0a4d", - "\u0a70" - "\u0a71", - "\u0a81" - "\u0a83", - "\u0abc", - "\u0abe" - "\u0ac5", - "\u0ac7" - "\u0ac9", - "\u0acb" - "\u0acd", - "\u0b01" - "\u0b03", - "\u0b3c", - "\u0b3e" - "\u0b43", - "\u0b47" - "\u0b48", - "\u0b4b" - "\u0b4d", - "\u0b56" - "\u0b57", - "\u0b82" - "\u0b83", - "\u0bbe" - "\u0bc2", - "\u0bc6" - "\u0bc8", - "\u0bca" - "\u0bcd", - "\u0bd7", - "\u0c01" - "\u0c03", - "\u0c3e" - "\u0c44", - "\u0c46" - "\u0c48", - "\u0c4a" - "\u0c4d", - "\u0c55" - "\u0c56", - "\u0c82" - "\u0c83", - "\u0cbe" - "\u0cc4", - "\u0cc6" - "\u0cc8", - "\u0cca" - "\u0ccd", - "\u0cd5" - "\u0cd6", - "\u0d02" - "\u0d03", - "\u0d3e" - "\u0d43", - "\u0d46" - "\u0d48", - "\u0d4a" - "\u0d4d", - "\u0d57", - "\u0e31", - "\u0e34" - "\u0e3a", - "\u0e47" - "\u0e4e", - "\u0eb1", - "\u0eb4" - "\u0eb9", - "\u0ebb" - "\u0ebc", - "\u0ec8" - "\u0ecd", - "\u0f18" - "\u0f19", - "\u0f35", - "\u0f37", - "\u0f39", - "\u0f3e", - "\u0f3f", - "\u0f71" - "\u0f84", - "\u0f86" - "\u0f8b", - "\u0f90" - "\u0f95", - "\u0f97", - "\u0f99" - "\u0fad", - "\u0fb1" - "\u0fb7", - "\u0fb9", - "\u20d0" - "\u20dc", - "\u20e1", - "\u302a" - "\u302f", - "\u3099", - "\u309a" - ] > - | < #DIGIT : [ - "\u0030" - "\u0039", - "\u0660" - "\u0669", - "\u06f0" - "\u06f9", - "\u0966" - "\u096f", - "\u09e6" - "\u09ef", - "\u0a66" - "\u0a6f", - "\u0ae6" - "\u0aef", - "\u0b66" - "\u0b6f", - "\u0be7" - "\u0bef", - "\u0c66" - "\u0c6f", - "\u0ce6" - "\u0cef", - "\u0d66" - "\u0d6f", - "\u0e50" - "\u0e59", - "\u0ed0" - "\u0ed9", - "\u0f20" - "\u0f29" - ] > - | < #EXTENDER : [ - "\u00b7", - "\u02d0", - "\u02d1", - "\u0387", - "\u0640", - "\u0e46", - "\u0ec6", - "\u3005", - "\u3031" - "\u3035", - "\u309d" - "\u309e", - "\u30fc" - "\u30fe" - ] > - | < #NMSTART : ( | "_") > - | < #NMCHAR : ( | | | | "." | "-" | "_") > - | < #NCNAME: ()* > -} - -TOKEN : -{ - < IDENTIFIER: > - | < ESCAPED_IDENTIFIER: "\\" > - | < PREFIX_STAR: ":*" > - | < PREFIXED_NAME: ":" > - | < LITERAL : ("\"" (~["\u0000", "\""])* "\"") - | ("'" (~["\u0000", "'"])* "'") - | ("\"\"\"" (~["\""] - | ("\"" ~["\""]) - | ("\"\"" ~["\""]))* "\"\"\"") - | ("'''" (~["'"] - | ("'" ~["'"]) - | ("''" ~["'"]))* "'''") > - | < FANNOTATE : ">>" > -} - -/* This avoids lexical errors from JavaCC. */ -<*> -TOKEN : -{ - < ILLEGAL_CHAR : [ "\u0000" - "\u0008", "\u000b" - "\uffff" ] > -} diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/client/sei/pacakge-info.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/client/sei/package-info.java similarity index 95% rename from jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/client/sei/pacakge-info.java rename to jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/client/sei/package-info.java index c64df853e20..e3fff6d0645 100644 --- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/client/sei/pacakge-info.java +++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/client/sei/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/server/DefaultResourceInjector.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/server/DefaultResourceInjector.java index 73cd2c46cd5..8600d0184a7 100644 --- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/server/DefaultResourceInjector.java +++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/server/DefaultResourceInjector.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -40,7 +40,7 @@ import javax.xml.ws.WebServiceContext; */ public final class DefaultResourceInjector extends ResourceInjector { public void inject(@NotNull WSWebServiceContext context, @NotNull Object instance) { - InjectionPlan.buildInjectionPlan( + InjectionPlan.buildInjectionPlan( instance.getClass(),WebServiceContext.class,false).inject(instance,context); } diff --git a/jdk/.hgtags b/jdk/.hgtags index 7a9bbb24e71..0316b38ce62 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -256,3 +256,5 @@ ab06ba2894313a47e4969ca37792ff119c49e711 jdk9-b10 47feccd164b7187a0147693a922ee47c6629643c jdk9-b11 83d9bc20973de232cae45b139fdff8a4549c130f jdk9-b12 c7c8002d02721e02131d104549ebeb8b379fb8d2 jdk9-b13 +5c7a17a81afd0906b53ee31d95a3211c96ff6b25 jdk9-b14 +4537360f09fe23ab339ee588747b657feb12d0c8 jdk9-b15 diff --git a/jdk/make/CompileJavaClasses.gmk b/jdk/make/CompileJavaClasses.gmk index f0ea1835967..6d2acb6708f 100644 --- a/jdk/make/CompileJavaClasses.gmk +++ b/jdk/make/CompileJavaClasses.gmk @@ -38,7 +38,7 @@ EXCLUDES := ########################################################################################## -EXCLUDES += com/sun/pept \ +EXCLUDES += \ com/sun/tools/example/trace \ com/sun/tools/example/debug/bdi \ com/sun/tools/example/debug/event \ diff --git a/jdk/make/CopyIntoClasses.gmk b/jdk/make/CopyIntoClasses.gmk index 36b0919fa2f..fdf2a173aca 100644 --- a/jdk/make/CopyIntoClasses.gmk +++ b/jdk/make/CopyIntoClasses.gmk @@ -30,7 +30,6 @@ COPY_PATTERNS := .icu _dict .dat _options .js aliasmap .spp .wav .css \ # These directories should not be copied at all EXCLUDES += \ - com/sun/org/apache/xml/internal/security/resource/schema \ java/awt/doc-files \ java/lang/doc-files \ javax/swing/doc-files \ @@ -111,20 +110,8 @@ else ALL_META-INF_DIRS := $(ALL_META-INF_DIRS_share) endif -ifndef OPENJDK - ALL_META-INF_DIRS += $(JDK_TOPDIR)/src/closed/share/classes/sun/java2d/cmm/kcms/META-INF -endif - SRC_SERVICES_FILES := $(wildcard $(addsuffix /services/*, $(ALL_META-INF_DIRS))) -ifdef OPENJDK - SRC_SERVICES_FILES := $(filter-out %sun/dc/META-INF/services/sun.java2d.pipe.RenderingEngine, $(SRC_SERVICES_FILES)) - SRC_SERVICES_FILES := $(filter-out %sun/java2d/cmm/kcms/META-INF/services/sun.java2d.cmm.CMMServiceProvider, $(SRC_SERVICES_FILES)) -else - SRC_SERVICES_FILES := $(filter-out %sun/java2d/pisces/META-INF/services/sun.java2d.pipe.RenderingEngine, $(SRC_SERVICES_FILES)) - SRC_SERVICES_FILES := $(filter-out %sun/java2d/cmm/lcms/META-INF/services/sun.java2d.cmm.CMMServiceProvider, $(SRC_SERVICES_FILES)) -endif - # The number of services files are relatively few. If the increase in numbers, then # we have to use ListPathsSafelyNow here. # Change $(JDK_TOPDIR)/src/.../META-INF/services/yyyy into $(JDK_OUTPUTDIR)/classes/META-INF/services/yyyy diff --git a/jdk/make/lib/Awt2dLibraries.gmk b/jdk/make/lib/Awt2dLibraries.gmk index fd2e516be70..06a5672d00a 100644 --- a/jdk/make/lib/Awt2dLibraries.gmk +++ b/jdk/make/lib/Awt2dLibraries.gmk @@ -318,7 +318,7 @@ ifeq ($(OPENJDK_TARGET_OS), aix) endif ifeq ($(OPENJDK_TARGET_OS), macosx) - LIBAWT_FILES += awt_LoadLibrary.c img_colors.c + LIBAWT_FILES += awt_LoadLibrary.c LIBAWT_CFLAGS += -F/System/Library/Frameworks/JavaVM.framework/Frameworks endif @@ -606,7 +606,6 @@ ifeq ($(findstring $(OPENJDK_TARGET_OS),windows macosx),) debug_mem.c \ debug_trace.c \ debug_util.c \ - awt_Plugin.c \ gnome_interface.c \ gtk2_interface.c \ swing_GTKEngine.c \ @@ -657,17 +656,34 @@ endif ########################################################################################## +LIBLCMS_DIR := $(JDK_TOPDIR)/src/share/native/sun/java2d/cmm/lcms + +ifeq ($(USE_EXTERNAL_LCMS), true) + # If we're using an external library, we'll just need the wrapper part. + # By including it explicitely, all other files will be excluded. + BUILD_LIBLCMS_INCLUDE_FILES := LCMS.c + BUILD_LIBLCMS_HEADERS := +else + BUILD_LIBLCMS_INCLUDE_FILES := + # If we're using the bundled library, we'll need to include it in the + # include path explicitly. Otherwise the system headers will be used. + BUILD_LIBLCMS_HEADERS := -I$(LIBLCMS_DIR) +endif + # TODO: Update awt lib path when awt is converted $(eval $(call SetupNativeCompilation,BUILD_LIBLCMS, \ LIBRARY := lcms, \ OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \ - SRC := $(JDK_TOPDIR)/src/share/native/sun/java2d/cmm/lcms, \ + SRC := $(LIBLCMS_DIR), \ + INCLUDE_FILES := $(BUILD_LIBLCMS_INCLUDE_FILES), \ LANG := C, \ OPTIMIZATION := HIGHEST, \ CFLAGS := $(filter-out -xc99=%none, $(CFLAGS_JDKLIB)) \ $(SHARED_LIBRARY_FLAGS) \ -I$(JDK_TOPDIR)/src/share/native/sun/java2d \ - -I$(JDK_TOPDIR)/src/share/native/sun/awt/debug, \ + -I$(JDK_TOPDIR)/src/share/native/sun/awt/debug \ + $(BUILD_LIBLCMS_HEADERS) \ + $(LCMS_CFLAGS), \ CFLAGS_solaris := -xc99=no_lib, \ CFLAGS_windows := -DCMS_IS_WINDOWS_, \ MAPFILE := $(JDK_TOPDIR)/make/mapfiles/liblcms/mapfile-vers, \ @@ -675,10 +691,10 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBLCMS, \ $(call SET_SHARED_LIBRARY_ORIGIN), \ LDFLAGS_solaris := /usr/lib$(OPENJDK_TARGET_CPU_ISADIR)/libm.so.2, \ LDFLAGS_windows := $(WIN_AWT_LIB) $(WIN_JAVA_LIB), \ - LDFLAGS_SUFFIX_solaris := -lawt -ljava -ljvm -lc, \ - LDFLAGS_SUFFIX_macosx := $(LIBM) -lawt -ljava -ljvm, \ - LDFLAGS_SUFFIX_linux := -lm -lawt -ljava -ljvm, \ - LDFLAGS_SUFFIX_aix := -lm -lawt -ljava -ljvm,\ + LDFLAGS_SUFFIX_solaris := -lawt -ljava -ljvm -lc $(LCMS_LIBS), \ + LDFLAGS_SUFFIX_macosx := $(LIBM) -lawt -ljava -ljvm $(LCMS_LIBS), \ + LDFLAGS_SUFFIX_linux := -lm -lawt -ljava -ljvm $(LCMS_LIBS), \ + LDFLAGS_SUFFIX_aix := -lm -lawt -ljava -ljvm $(LCMS_LIBS),\ VERSIONINFO_RESOURCE := $(JDK_TOPDIR)/src/windows/resource/version.rc, \ RC_FLAGS := $(RC_FLAGS) \ -D "JDK_FNAME=lcms.dll" \ diff --git a/jdk/make/mapfiles/libawt/mapfile-mawt-vers b/jdk/make/mapfiles/libawt/mapfile-mawt-vers index a50c13a62e5..b8ea1636c88 100644 --- a/jdk/make/mapfiles/libawt/mapfile-mawt-vers +++ b/jdk/make/mapfiles/libawt/mapfile-mawt-vers @@ -1,5 +1,5 @@ # -# Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2001, 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 @@ -249,11 +249,6 @@ SUNWprivate_1.1 { Java_sun_awt_motif_XsessionWMcommand; Java_sun_awt_motif_XsessionWMcommand_New; - # Java Plugin - getAwtLockFunctions; - getAwtData; - getAwtDisplay; - # libfontmanager entry points AWTIsHeadless; AWTCountFonts; diff --git a/jdk/make/mapfiles/libawt/mapfile-vers b/jdk/make/mapfiles/libawt/mapfile-vers index 05ca7d538dd..b1c6a39ec1e 100644 --- a/jdk/make/mapfiles/libawt/mapfile-vers +++ b/jdk/make/mapfiles/libawt/mapfile-vers @@ -1,5 +1,5 @@ # -# Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1997, 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 @@ -173,13 +173,6 @@ SUNWprivate_1.1 { Java_sun_awt_motif_XsessionWMcommand; Java_sun_awt_motif_XsessionWMcommand_New; - # Java Plugin - # This is in awt_LoadLibrary.c and falls through to libmawt. - # Evidently plugin needs this for backward compatability. - getAwtLockFunctions; - getAwtData; - getAwtDisplay; - # libfontmanager entry points AWTIsHeadless; GrPrim_Sg2dGetCompInfo; diff --git a/jdk/make/mapfiles/libawt/mapfile-vers-linux b/jdk/make/mapfiles/libawt/mapfile-vers-linux index f8967e09462..922b015c68c 100644 --- a/jdk/make/mapfiles/libawt/mapfile-vers-linux +++ b/jdk/make/mapfiles/libawt/mapfile-vers-linux @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 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 @@ -152,13 +152,6 @@ SUNWprivate_1.1 { # Evidently CDE needs this for backward compatability. Java_sun_awt_motif_XsessionWMcommand; - # Java Plugin - # This is in awt_LoadLibrary.c and falls through to libmawt. - # Evidently plugin needs this for backward compatability. - getAwtLockFunctions; - getAwtData; - getAwtDisplay; - # libfontmanager entry points AWTIsHeadless; GrPrim_Sg2dGetCompInfo; @@ -283,11 +276,6 @@ SUNWprivate_1.1 { # CDE private entry point Java_sun_awt_motif_XsessionWMcommand; - # Java Plugin - getAwtLockFunctions; - getAwtData; - getAwtDisplay; - # libfontmanager entry points AWTIsHeadless; AWTCountFonts; diff --git a/jdk/make/mapfiles/libawt_xawt/mapfile-vers b/jdk/make/mapfiles/libawt_xawt/mapfile-vers index 15089a114ca..3ae8af3ddbf 100644 --- a/jdk/make/mapfiles/libawt_xawt/mapfile-vers +++ b/jdk/make/mapfiles/libawt_xawt/mapfile-vers @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 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 @@ -449,12 +449,6 @@ SUNWprivate_1.1 { awt_Lock; awt_GetComponent; - # Java Plugin - # This is in awt_LoadLibrary.c and falls through to libmawt. - # Evidently plugin needs this for backward compatability. - getAwtLockFunctions; - getAwtData; - getAwtDisplay; #XAWT entry point for CDE Java_sun_awt_motif_XsessionWMcommand; Java_sun_awt_motif_XsessionWMcommand_New; diff --git a/jdk/make/mapfiles/libjava/mapfile-vers b/jdk/make/mapfiles/libjava/mapfile-vers index aeb1588e70d..ca99cc5c03b 100644 --- a/jdk/make/mapfiles/libjava/mapfile-vers +++ b/jdk/make/mapfiles/libjava/mapfile-vers @@ -270,7 +270,10 @@ SUNWprivate_1.1 { Java_sun_misc_Version_getJvmVersionInfo; Java_sun_misc_Version_getJvmSpecialVersion; Java_sun_misc_VM_latestUserDefinedLoader; - Java_sun_misc_VM_isSetUID; + Java_sun_misc_VM_getuid; + Java_sun_misc_VM_geteuid; + Java_sun_misc_VM_getgid; + Java_sun_misc_VM_getegid; Java_sun_misc_VM_initialize; Java_sun_misc_VMSupport_initAgentProperties; Java_sun_misc_VMSupport_getVMTemporaryDirectory; diff --git a/jdk/make/mapfiles/libjpeg/mapfile-vers-closed b/jdk/make/mapfiles/libjpeg/mapfile-vers-closed index 9b3724c4994..6f84d2da352 100644 --- a/jdk/make/mapfiles/libjpeg/mapfile-vers-closed +++ b/jdk/make/mapfiles/libjpeg/mapfile-vers-closed @@ -31,10 +31,6 @@ SUNWprivate_1.1 { Java_sun_awt_image_JPEGImageDecoder_initIDs; Java_sun_awt_image_JPEGImageDecoder_readImage; - Java_sun_awt_image_codec_JPEGImageDecoderImpl_initDecoder; - Java_sun_awt_image_codec_JPEGImageDecoderImpl_readJPEGStream; - Java_sun_awt_image_codec_JPEGImageEncoderImpl_initEncoder; - Java_sun_awt_image_codec_JPEGImageEncoderImpl_writeJPEGStream; Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_initReaderIDs; Java_com_sun_imageio_plugins_jpeg_JPEGImageReader_initJPEGImageReader; diff --git a/jdk/make/profile-rtjar-includes.txt b/jdk/make/profile-rtjar-includes.txt index 95b3357f183..b20031a017e 100644 --- a/jdk/make/profile-rtjar-includes.txt +++ b/jdk/make/profile-rtjar-includes.txt @@ -239,6 +239,4 @@ FULL_JRE_INCLUDE_METAINF_SERVICES := \ META-INF/services/javax.sound.sampled.spi.AudioFileReader \ META-INF/services/javax.sound.sampled.spi.AudioFileWriter \ META-INF/services/javax.sound.sampled.spi.FormatConversionProvider \ - META-INF/services/javax.sound.sampled.spi.MixerProvider \ - META-INF/services/sun.java2d.cmm.PCMM \ - META-INF/services/sun.java2d.pipe.RenderingEngine + META-INF/services/javax.sound.sampled.spi.MixerProvider diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxPopup.java b/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxPopup.java index dde9b1be337..9fbf67283cd 100644 --- a/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxPopup.java +++ b/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxPopup.java @@ -121,6 +121,10 @@ class AquaComboBoxPopup extends BasicComboPopup { public void show() { final int startItemCount = comboBox.getItemCount(); + if (startItemCount == 0) { + return; + } + final Rectangle popupBounds = adjustPopupAndGetBounds(); if (popupBounds == null) return; // null means don't show diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaImageFactory.java b/jdk/src/macosx/classes/com/apple/laf/AquaImageFactory.java index be6a787a45b..4838ba48879 100644 --- a/jdk/src/macosx/classes/com/apple/laf/AquaImageFactory.java +++ b/jdk/src/macosx/classes/com/apple/laf/AquaImageFactory.java @@ -46,10 +46,8 @@ import com.apple.laf.AquaIcon.JRSUIControlSpec; import com.apple.laf.AquaIcon.SystemIcon; import com.apple.laf.AquaUtils.RecyclableObject; import com.apple.laf.AquaUtils.RecyclableSingleton; -import java.util.Arrays; -import java.util.List; -import sun.awt.image.MultiResolutionBufferedImage; import sun.awt.image.MultiResolutionImage; +import sun.awt.image.MultiResolutionCachedImage; public class AquaImageFactory { public static IconUIResource getConfirmImageIcon() { @@ -57,7 +55,7 @@ public class AquaImageFactory { return new IconUIResource(new AquaIcon.CachingScalingIcon(kAlertIconSize, kAlertIconSize) { Image createImage() { - return getThisApplicationsIcon(kAlertIconSize, kAlertIconSize); + return getGenericJavaIcon(); } }); } @@ -83,24 +81,6 @@ public class AquaImageFactory { return getAppIconCompositedOn(lockIcon); } - static Image getThisApplicationsIcon(final int width, final int height) { - final String path = getPathToThisApplication(); - - if (path == null) { - return getGenericJavaIcon(); - } - - if (path.endsWith("/Home/bin")) { - return getGenericJavaIcon(); - } - - if (path.startsWith("/usr/bin")) { - return getGenericJavaIcon(); - } - - return AquaUtils.getCImageCreator().createImageOfFile(path, height, width); - } - static Image getGenericJavaIcon() { return java.security.AccessController.doPrivileged(new PrivilegedAction() { public Image run() { @@ -125,9 +105,9 @@ public class AquaImageFactory { private static final int kAlertIconSize = 64; static IconUIResource getAppIconCompositedOn(final Image background) { - if (background instanceof MultiResolutionBufferedImage) { + if (background instanceof MultiResolutionCachedImage) { int width = background.getWidth(null); - Image mrIconImage = ((MultiResolutionBufferedImage) background).map( + Image mrIconImage = ((MultiResolutionCachedImage) background).map( rv -> getAppIconImageCompositedOn(rv, rv.getWidth(null) / width)); return new IconUIResource(new ImageIcon(mrIconImage)); } @@ -144,7 +124,7 @@ public class AquaImageFactory { final Icon smallAppIconScaled = new AquaIcon.CachingScalingIcon( kAlertSubIconSize, kAlertSubIconSize) { Image createImage() { - return getThisApplicationsIcon(kAlertSubIconSize, kAlertSubIconSize); + return getGenericJavaIcon(); } }; @@ -306,21 +286,7 @@ public class AquaImageFactory { private static Image getNSIcon(String imageName) { Image icon = Toolkit.getDefaultToolkit() .getImage("NSImage://" + imageName); - - if (icon instanceof MultiResolutionImage) { - return icon; - } - - int w = icon.getWidth(null); - int h = icon.getHeight(null); - - Dimension[] sizes = new Dimension[]{ - new Dimension(w, h), new Dimension(2 * w, 2 * h) - }; - - return new MultiResolutionBufferedImage(icon, sizes, (width, height) -> - AquaUtils.getCImageCreator().createImageFromName( - imageName, width, height)); + return icon; } public static class NineSliceMetrics { @@ -530,4 +496,4 @@ public class AquaImageFactory { public static Color getSelectionInactiveForegroundColorUIResource() { return new SystemColorProxy(LWCToolkit.getAppleColor(LWCToolkit.INACTIVE_SELECTION_FOREGROUND_COLOR)); } -} \ No newline at end of file +} diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaPainter.java b/jdk/src/macosx/classes/com/apple/laf/AquaPainter.java index ee4fcba1a4d..a2ebaf1c920 100644 --- a/jdk/src/macosx/classes/com/apple/laf/AquaPainter.java +++ b/jdk/src/macosx/classes/com/apple/laf/AquaPainter.java @@ -174,11 +174,7 @@ abstract class AquaPainter { bounds, controlState); Image img = cache.getImage(key); if (img == null) { - - Image baseImage = createImage(imgX, imgY, imgW, imgH, bounds, - control, controlState); - - img = new MultiResolutionBufferedImage(baseImage, + img = new MultiResolutionCachedImage(imgW, imgH, (rvWidth, rvHeight) -> createImage(imgX, imgY, rvWidth, rvHeight, bounds, control, controlState)); diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaUtils.java b/jdk/src/macosx/classes/com/apple/laf/AquaUtils.java index a20897f7b31..078435b161b 100644 --- a/jdk/src/macosx/classes/com/apple/laf/AquaUtils.java +++ b/jdk/src/macosx/classes/com/apple/laf/AquaUtils.java @@ -48,7 +48,7 @@ import sun.security.action.GetPropertyAction; import sun.swing.SwingUtilities2; import com.apple.laf.AquaImageFactory.SlicedImageControl; -import sun.awt.image.MultiResolutionBufferedImage; +import sun.awt.image.MultiResolutionCachedImage; final class AquaUtils { @@ -124,8 +124,8 @@ final class AquaUtils { static Image generateLightenedImage(final Image image, final int percent) { final GrayFilter filter = new GrayFilter(true, percent); - return (image instanceof MultiResolutionBufferedImage) - ? ((MultiResolutionBufferedImage) image).map( + return (image instanceof MultiResolutionCachedImage) + ? ((MultiResolutionCachedImage) image).map( rv -> generateLightenedImage(rv, filter)) : generateLightenedImage(image, filter); } diff --git a/jdk/src/macosx/classes/sun/font/CFontManager.java b/jdk/src/macosx/classes/sun/font/CFontManager.java index ad2bfab62ba..8e1cead53c2 100644 --- a/jdk/src/macosx/classes/sun/font/CFontManager.java +++ b/jdk/src/macosx/classes/sun/font/CFontManager.java @@ -40,7 +40,7 @@ import javax.swing.plaf.FontUIResource; import sun.awt.FontConfiguration; import sun.awt.HeadlessToolkit; -import sun.misc.ThreadGroupUtils; +import sun.awt.util.ThreadGroupUtils; import sun.lwawt.macosx.*; public class CFontManager extends SunFontManager { diff --git a/jdk/src/macosx/classes/sun/lwawt/LWChoicePeer.java b/jdk/src/macosx/classes/sun/lwawt/LWChoicePeer.java index bb360d6d677..27d43b1bfce 100644 --- a/jdk/src/macosx/classes/sun/lwawt/LWChoicePeer.java +++ b/jdk/src/macosx/classes/sun/lwawt/LWChoicePeer.java @@ -171,7 +171,9 @@ final class LWChoicePeer extends LWComponentPeer> SwingUtilities.invokeLater(() -> { JPopupMenu popupMenu = getPopupMenu(); // Need to override the invoker for proper grab handling - if (popupMenu != null && popupMenu.getInvoker() != getTarget()) { + if (popupMenu != null + && popupMenu.isShowing() + && popupMenu.getInvoker() != getTarget()) { // The popup is now visible with correct location // Save it and restore after toggling visibility and changing invoker Point loc = popupMenu.getLocationOnScreen(); diff --git a/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java b/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java index 5880d06be4d..354f2538012 100644 --- a/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java +++ b/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java @@ -63,8 +63,6 @@ import javax.swing.JComponent; import javax.swing.SwingUtilities; import javax.swing.RepaintManager; -import sun.lwawt.macosx.CDropTarget; - import com.sun.java.swing.SwingUtilities3; public abstract class LWComponentPeer @@ -137,7 +135,7 @@ public abstract class LWComponentPeer private final Object dropTargetLock = new Object(); private int fNumDropTargets = 0; - private CDropTarget fDropTarget = null; + private PlatformDropTarget fDropTarget = null; private final PlatformComponent platformComponent; @@ -1063,11 +1061,11 @@ public abstract class LWComponentPeer // if it's the first (or last) one for the component. Otherwise this call is a no-op. if (++fNumDropTargets == 1) { // Having a non-null drop target would be an error but let's check just in case: - if (fDropTarget != null) - System.err.println("CComponent.addDropTarget(): current drop target is non-null."); - + if (fDropTarget != null) { + throw new IllegalStateException("Current drop target is not null"); + } // Create a new drop target: - fDropTarget = CDropTarget.createDropTarget(dt, target, this); + fDropTarget = LWToolkit.getLWToolkit().createDropTarget(dt, target, this); } } } diff --git a/jdk/src/macosx/classes/sun/lwawt/LWToolkit.java b/jdk/src/macosx/classes/sun/lwawt/LWToolkit.java index 8dd9467eed6..315a19a7ff3 100644 --- a/jdk/src/macosx/classes/sun/lwawt/LWToolkit.java +++ b/jdk/src/macosx/classes/sun/lwawt/LWToolkit.java @@ -28,6 +28,7 @@ package sun.lwawt; import java.awt.*; import java.awt.List; import java.awt.datatransfer.*; +import java.awt.dnd.DropTarget; import java.awt.image.*; import java.awt.peer.*; import java.security.*; @@ -35,7 +36,7 @@ import java.util.*; import sun.awt.*; import sun.print.*; -import sun.misc.ThreadGroupUtils; +import sun.awt.util.ThreadGroupUtils; import static sun.lwawt.LWWindowPeer.PeerType; @@ -440,6 +441,10 @@ public abstract class LWToolkit extends SunToolkit implements Runnable { protected abstract FileDialogPeer createFileDialogPeer(FileDialog target); + protected abstract PlatformDropTarget createDropTarget(DropTarget dropTarget, + Component component, + LWComponentPeer peer); + // ---- UTILITY METHODS ---- // /* diff --git a/jdk/src/share/classes/com/sun/pept/ept/Acceptor.java b/jdk/src/macosx/classes/sun/lwawt/PlatformDropTarget.java similarity index 64% rename from jdk/src/share/classes/com/sun/pept/ept/Acceptor.java rename to jdk/src/macosx/classes/sun/lwawt/PlatformDropTarget.java index 82b59c1198b..e2a9a70e70f 100644 --- a/jdk/src/share/classes/com/sun/pept/ept/Acceptor.java +++ b/jdk/src/macosx/classes/sun/lwawt/PlatformDropTarget.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -23,32 +23,12 @@ * questions. */ -/** Java interface "Acceptor.java" generated from Poseidon for UML. - * Poseidon for UML is developed by Gentleware. - * Generated with velocity template engine. - */ -package com.sun.pept.ept; +package sun.lwawt; -import java.util.*; +public interface PlatformDropTarget { -/** - *

- * - * @author Dr. Harold Carr - *

- */ -public interface Acceptor extends EPTFactory { - - /////////////////////////////////////// - // operations - -/** - *

- * Does ... - *

- * - *

- */ - public void accept(); - -} // end Acceptor + /** + * Release native dragging destination, if any + */ + void dispose(); +} diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java index 26d2347ff15..c07356057ee 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java @@ -31,6 +31,7 @@ import sun.awt.image.ImageRepresentation; import java.io.*; import java.net.URL; +import java.nio.charset.Charset; import java.text.Normalizer; import java.text.Normalizer.Form; import java.util.*; @@ -126,7 +127,7 @@ public class CDataTransferer extends DataTransferer { if (format == CF_URL && URL.class.equals(flavor.getRepresentationClass())) { - String charset = getDefaultTextCharset(); + String charset = Charset.defaultCharset().name(); if (transferable != null && transferable.isDataFlavorSupported(javaTextEncodingFlavor)) { try { charset = new String((byte[])transferable.getTransferData(javaTextEncodingFlavor), "UTF-8"); diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java index 910e1407a36..d4f4353d9ec 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTarget.java @@ -25,54 +25,37 @@ package sun.lwawt.macosx; -import java.awt.Component; -import java.awt.peer.ComponentPeer; +import sun.lwawt.LWComponentPeer; +import sun.lwawt.PlatformDropTarget; + +import java.awt.*; import java.awt.dnd.DropTarget; -import sun.lwawt.LWComponentPeer; -import sun.lwawt.PlatformWindow; +final class CDropTarget implements PlatformDropTarget { + private long fNativeDropTarget; -public final class CDropTarget { - - Component fComponent; - ComponentPeer fPeer; - DropTarget fDropTarget; - private long fNativeDropTarget; - - public static CDropTarget createDropTarget(DropTarget dropTarget, Component component, ComponentPeer peer) { - return new CDropTarget(dropTarget, component, peer); - } - - private CDropTarget(DropTarget dropTarget, Component component, ComponentPeer peer) { - super(); - - fDropTarget = dropTarget; - fComponent = component; - fPeer = peer; - - long nativePeer = CPlatformWindow.getNativeViewPtr(((LWComponentPeer) peer).getPlatformWindow()); + CDropTarget(DropTarget dropTarget, Component component, LWComponentPeer peer) { + long nativePeer = CPlatformWindow.getNativeViewPtr(peer.getPlatformWindow()); if (nativePeer == 0L) return; // Unsupported for a window without a native view (plugin) // Create native dragging destination: - fNativeDropTarget = this.createNativeDropTarget(dropTarget, component, peer, nativePeer); + fNativeDropTarget = createNativeDropTarget(dropTarget, component, nativePeer); if (fNativeDropTarget == 0) { throw new IllegalStateException("CDropTarget.createNativeDropTarget() failed."); } } - public DropTarget getDropTarget() { - return fDropTarget; - } - + @Override public void dispose() { - // Release native dragging destination, if any: if (fNativeDropTarget != 0) { - this.releaseNativeDropTarget(fNativeDropTarget); + releaseNativeDropTarget(fNativeDropTarget); fNativeDropTarget = 0; } } - protected native long createNativeDropTarget(DropTarget dropTarget, Component component, ComponentPeer peer, long nativePeer); + protected native long createNativeDropTarget(DropTarget dropTarget, + Component component, + long nativePeer); protected native void releaseNativeDropTarget(long nativeDropTarget); } diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CImage.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CImage.java index 17815d4882e..69bdab05734 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CImage.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CImage.java @@ -32,7 +32,7 @@ import java.awt.image.*; import java.util.Arrays; import java.util.List; import sun.awt.image.MultiResolutionImage; -import sun.awt.image.MultiResolutionBufferedImage; +import sun.awt.image.MultiResolutionCachedImage; import sun.awt.image.SunWritableRaster; @@ -62,41 +62,41 @@ public class CImage extends CFRetainedResource { // This is used to create a CImage with an NSImage pointer. It MUST be a CFRetained // NSImage, and the CImage takes ownership of the non-GC retain. If callers need the // NSImage themselves, they MUST call retain on the NSImage themselves. - public BufferedImage createImageUsingNativeSize(final long image) { + public Image createImageUsingNativeSize(final long image) { if (image == 0) return null; final Dimension2D size = nativeGetNSImageSize(image); - return createBufferedImage(image, size.getWidth(), size.getHeight()); + return createImage(image, size.getWidth(), size.getHeight()); } // the width and height passed in as a parameter could differ than the width and the height of the NSImage (image), in that case, the image will be scaled - BufferedImage createBufferedImage(long image, double width, double height) { + Image createImage(long image, double width, double height) { if (image == 0) throw new Error("Unable to instantiate CImage with null native image reference."); return createImageWithSize(image, width, height); } - public BufferedImage createImageWithSize(final long image, final double width, final double height) { + public Image createImageWithSize(final long image, final double width, final double height) { final CImage img = new CImage(image); img.resize(width, height); return img.toImage(); } // This is used to create a CImage that represents the icon of the given file. - public BufferedImage createImageOfFile(final String file, final int width, final int height) { - return createBufferedImage(nativeCreateNSImageOfFileFromLaunchServices(file), width, height); + public Image createImageOfFile(final String file, final int width, final int height) { + return createImage(nativeCreateNSImageOfFileFromLaunchServices(file), width, height); } - public BufferedImage createImageFromFile(final String file, final double width, final double height) { + public Image createImageFromFile(final String file, final double width, final double height) { final long image = nativeCreateNSImageFromFileContents(file); nativeSetNSImageSize(image, width, height); - return createBufferedImage(image, width, height); + return createImage(image, width, height); } - public BufferedImage createSystemImageFromSelector(final String iconSelector, final int width, final int height) { - return createBufferedImage(nativeCreateNSImageFromIconSelector(getSelectorAsInt(iconSelector)), width, height); + public Image createSystemImageFromSelector(final String iconSelector, final int width, final int height) { + return createImage(nativeCreateNSImageFromIconSelector(getSelectorAsInt(iconSelector)), width, height); } public Image createImageFromName(final String name, final int width, final int height) { - return createBufferedImage(nativeCreateNSImageFromImageName(name), width, height); + return createImage(nativeCreateNSImageFromImageName(name), width, height); } public Image createImageFromName(final String name) { @@ -232,7 +232,7 @@ public class CImage extends CFRetainedResource { } /** @return A MultiResolution image created from nsImagePtr, or null. */ - private BufferedImage toImage() { + private Image toImage() { if (ptr == 0) return null; final Dimension2D size = nativeGetNSImageSize(ptr); @@ -243,11 +243,11 @@ public class CImage extends CFRetainedResource { = nativeGetNSImageRepresentationSizes(ptr, size.getWidth(), size.getHeight()); - BufferedImage baseImage = toImage(w, h, w, h); - - return sizes == null || sizes.length < 2 ? baseImage - : new MultiResolutionBufferedImage(baseImage, sizes, - (width, height) -> toImage(w, h, width, height)); + return sizes == null || sizes.length < 2 ? + new MultiResolutionCachedImage(w, h, (width, height) + -> toImage(w, h, width, height)) + : new MultiResolutionCachedImage(w, h, sizes, (width, height) + -> toImage(w, h, width, height)); } private BufferedImage toImage(int srcWidth, int srcHeight, int dstWidth, int dstHeight) { diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java index fc72ef79474..0acc67feed6 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java @@ -309,6 +309,10 @@ public final class CWarningWindow extends CPlatformWindow @Override public void dispose() { cancelTasks(); + SurfaceData surfaceData = contentView.getSurfaceData(); + if (surfaceData != null) { + surfaceData.invalidate(); + } super.dispose(); } diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java b/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java index 4a153fc94d4..2bb5d4ac508 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java @@ -611,19 +611,20 @@ public final class LWCToolkit extends LWToolkit { } /** - * Kicks an event over to the appropriate eventqueue and waits for it to + * Kicks an event over to the appropriate event queue and waits for it to * finish To avoid deadlocking, we manually run the NSRunLoop while waiting * Any selector invoked using ThreadUtilities performOnMainThread will be * processed in doAWTRunLoop The InvocationEvent will call * LWCToolkit.stopAWTRunLoop() when finished, which will stop our manual - * runloop Does not dispatch native events while in the loop + * run loop. Does not dispatch native events while in the loop */ public static void invokeAndWait(Runnable runnable, Component component) throws InvocationTargetException { - final long mediator = createAWTRunLoopMediator(); + Objects.requireNonNull(component, "Null component provided to invokeAndWait"); + long mediator = createAWTRunLoopMediator(); InvocationEvent invocationEvent = - new InvocationEvent(component != null ? component : Toolkit.getDefaultToolkit(), + new InvocationEvent(component, runnable, () -> { if (mediator != 0) { @@ -632,49 +633,42 @@ public final class LWCToolkit extends LWToolkit { }, true); - if (component != null) { - AppContext appContext = SunToolkit.targetToAppContext(component); - SunToolkit.postEvent(appContext, invocationEvent); - - // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock - SunToolkit.flushPendingEvents(appContext); - } else { - // This should be the equivalent to EventQueue.invokeAndWait - ((LWCToolkit)Toolkit.getDefaultToolkit()).getSystemEventQueueForInvokeAndWait().postEvent(invocationEvent); - } - + AppContext appContext = SunToolkit.targetToAppContext(component); + SunToolkit.postEvent(appContext, invocationEvent); + // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock + SunToolkit.flushPendingEvents(appContext); doAWTRunLoop(mediator, false); - Throwable eventException = invocationEvent.getException(); - if (eventException != null) { - if (eventException instanceof UndeclaredThrowableException) { - eventException = ((UndeclaredThrowableException)eventException).getUndeclaredThrowable(); - } - throw new InvocationTargetException(eventException); - } + checkException(invocationEvent); } public static void invokeLater(Runnable event, Component component) throws InvocationTargetException { - final InvocationEvent invocationEvent = - new InvocationEvent(component != null ? component : Toolkit.getDefaultToolkit(), event); + Objects.requireNonNull(component, "Null component provided to invokeLater"); - if (component != null) { - final AppContext appContext = SunToolkit.targetToAppContext(component); - SunToolkit.postEvent(appContext, invocationEvent); + InvocationEvent invocationEvent = new InvocationEvent(component, event); - // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock - SunToolkit.flushPendingEvents(appContext); - } else { - // This should be the equivalent to EventQueue.invokeAndWait - ((LWCToolkit)Toolkit.getDefaultToolkit()).getSystemEventQueueForInvokeAndWait().postEvent(invocationEvent); - } + AppContext appContext = SunToolkit.targetToAppContext(component); + SunToolkit.postEvent(SunToolkit.targetToAppContext(component), invocationEvent); + // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock + SunToolkit.flushPendingEvents(appContext); - final Throwable eventException = invocationEvent.getException(); + checkException(invocationEvent); + } + + /** + * Checks if exception occurred while {@code InvocationEvent} was processed and rethrows it as + * an {@code InvocationTargetException} + * + * @param event the event to check for an exception + * @throws InvocationTargetException if exception occurred when event was processed + */ + private static void checkException(InvocationEvent event) throws InvocationTargetException { + Throwable eventException = event.getException(); if (eventException == null) return; if (eventException instanceof UndeclaredThrowableException) { - throw new InvocationTargetException(((UndeclaredThrowableException)eventException).getUndeclaredThrowable()); + eventException = ((UndeclaredThrowableException)eventException).getUndeclaredThrowable(); } throw new InvocationTargetException(eventException); } @@ -686,11 +680,6 @@ public final class LWCToolkit extends LWToolkit { */ native static void performOnMainThreadAfterDelay(Runnable r, long delay); - // This exists purely to get around permissions issues with getSystemEventQueueImpl - EventQueue getSystemEventQueueForInvokeAndWait() { - return getSystemEventQueueImpl(); - } - // DnD support @Override @@ -712,7 +701,14 @@ public final class LWCToolkit extends LWToolkit { return (T)dgr; } -// InputMethodSupport Method + @Override + protected PlatformDropTarget createDropTarget(DropTarget dropTarget, + Component component, + LWComponentPeer peer) { + return new CDropTarget(dropTarget, component, peer); + } + + // InputMethodSupport Method /** * Returns the default keyboard locale of the underlying operating system */ diff --git a/jdk/src/macosx/native/sun/awt/AWTView.m b/jdk/src/macosx/native/sun/awt/AWTView.m index bcc832190f4..830fb77e82b 100644 --- a/jdk/src/macosx/native/sun/awt/AWTView.m +++ b/jdk/src/macosx/native/sun/awt/AWTView.m @@ -27,6 +27,7 @@ #import #import +#import "jni_util.h" #import "ThreadUtilities.h" #import "AWTView.h" @@ -391,14 +392,12 @@ AWT_ASSERT_APPKIT_THREAD; (jint)absP.x, (jint)absP.y, [event deltaY], [event deltaX]); - if (jEvent == nil) { - // Unable to create event by some reason. - return; - } + CHECK_NULL(jEvent); static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView"); static JNF_MEMBER_CACHE(jm_deliverMouseEvent, jc_PlatformView, "deliverMouseEvent", "(Lsun/lwawt/macosx/NSEvent;)V"); JNFCallVoidMethod(env, m_cPlatformView, jm_deliverMouseEvent, jEvent); + (*env)->DeleteLocalRef(env, jEvent); } - (void) resetTrackingArea { @@ -447,20 +446,22 @@ AWT_ASSERT_APPKIT_THREAD; static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent"); static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IISLjava/lang/String;)V"); - jobject jevent = JNFNewObject(env, jctor_NSEvent, + jobject jEvent = JNFNewObject(env, jctor_NSEvent, [event type], [event modifierFlags], [event keyCode], characters); + CHECK_NULL(jEvent); static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView"); static JNF_MEMBER_CACHE(jm_deliverKeyEvent, jc_PlatformView, "deliverKeyEvent", "(Lsun/lwawt/macosx/NSEvent;)V"); - JNFCallVoidMethod(env, m_cPlatformView, jm_deliverKeyEvent, jevent); + JNFCallVoidMethod(env, m_cPlatformView, jm_deliverKeyEvent, jEvent); if (characters != NULL) { (*env)->DeleteLocalRef(env, characters); } + (*env)->DeleteLocalRef(env, jEvent); } -(void) deliverResize: (NSRect) rect { diff --git a/jdk/src/macosx/native/sun/awt/AWTWindow.m b/jdk/src/macosx/native/sun/awt/AWTWindow.m index c2577584886..6a9c1166e84 100644 --- a/jdk/src/macosx/native/sun/awt/AWTWindow.m +++ b/jdk/src/macosx/native/sun/awt/AWTWindow.m @@ -261,7 +261,8 @@ AWT_ASSERT_APPKIT_THREAD; // returns id for the topmost window under mouse + (NSInteger) getTopmostWindowUnderMouseID { - + NSInteger result = -1; + NSRect screenRect = [[NSScreen mainScreen] frame]; NSPoint nsMouseLocation = [NSEvent mouseLocation]; CGPoint cgMouseLocation = CGPointMake(nsMouseLocation.x, screenRect.size.height - nsMouseLocation.y); @@ -274,11 +275,13 @@ AWT_ASSERT_APPKIT_THREAD; CGRect rect; CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)[window objectForKey:(id)kCGWindowBounds], &rect); if (CGRectContainsPoint(rect, cgMouseLocation)) { - return [[window objectForKey:(id)kCGWindowNumber] integerValue]; + result = [[window objectForKey:(id)kCGWindowNumber] integerValue]; + break; } } } - return -1; + [windows release]; + return result; } // checks that this window is under the mouse cursor and this point is not overlapped by others windows diff --git a/jdk/src/macosx/native/sun/awt/CDropTarget.h b/jdk/src/macosx/native/sun/awt/CDropTarget.h index b6cd156562b..3b87485add7 100644 --- a/jdk/src/macosx/native/sun/awt/CDropTarget.h +++ b/jdk/src/macosx/native/sun/awt/CDropTarget.h @@ -48,7 +48,7 @@ + (CDropTarget *) currentDropTarget; // Common methods: -- (id)init:(jobject)dropTarget component:(jobject)jcomponent peer:(jobject)jpeer control:(id)control; +- (id)init:(jobject)dropTarget component:(jobject)jcomponent control:(id)control; - (void)controlModelControlValid; - (void)removeFromView:(JNIEnv *)env; diff --git a/jdk/src/macosx/native/sun/awt/CDropTarget.m b/jdk/src/macosx/native/sun/awt/CDropTarget.m index 41b0a192c61..7e038ab7715 100644 --- a/jdk/src/macosx/native/sun/awt/CDropTarget.m +++ b/jdk/src/macosx/native/sun/awt/CDropTarget.m @@ -65,7 +65,7 @@ extern JNFClassInfo jc_CDropTargetContextPeer; return sCurrentDropTarget; } -- (id)init:(jobject)jdropTarget component:(jobject)jcomponent peer:(jobject)jpeer control:(id)control +- (id)init:(jobject)jdropTarget component:(jobject)jcomponent control:(id)control { self = [super init]; DLog2(@"[CDropTarget init]: %@\n", self); @@ -714,13 +714,13 @@ extern JNFClassInfo jc_CDropTargetContextPeer; * Signature: (Ljava/awt/dnd/DropTarget;Ljava/awt/Component;Ljava/awt/peer/ComponentPeer;J)J */ JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_CDropTarget_createNativeDropTarget - (JNIEnv *env, jobject jthis, jobject jdroptarget, jobject jcomponent, jobject jpeer, jlong jnativepeer) + (JNIEnv *env, jobject jthis, jobject jdroptarget, jobject jcomponent, jlong jnativepeer) { CDropTarget* dropTarget = nil; JNF_COCOA_ENTER(env); id controlObj = (id) jlong_to_ptr(jnativepeer); - dropTarget = [[CDropTarget alloc] init:jdroptarget component:jcomponent peer:jpeer control:controlObj]; + dropTarget = [[CDropTarget alloc] init:jdroptarget component:jcomponent control:controlObj]; JNF_COCOA_EXIT(env); return ptr_to_jlong(dropTarget); diff --git a/jdk/src/macosx/native/sun/awt/CGraphicsDevice.m b/jdk/src/macosx/native/sun/awt/CGraphicsDevice.m index 9b94b82abbc..a1813b6154d 100644 --- a/jdk/src/macosx/native/sun/awt/CGraphicsDevice.m +++ b/jdk/src/macosx/native/sun/awt/CGraphicsDevice.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -66,7 +66,8 @@ static CFMutableArrayRef getAllValidDisplayModes(jint displayID){ CFArrayAppendValue(validModes, cRef); } } - + CFRelease(allModes); + CGDisplayModeRef currentMode = CGDisplayCopyDisplayMode(displayID); BOOL containsCurrentMode = NO; @@ -81,6 +82,7 @@ static CFMutableArrayRef getAllValidDisplayModes(jint displayID){ if (!containsCurrentMode) { CFArrayAppendValue(validModes, currentMode); } + CGDisplayModeRelease(currentMode); return validModes; } @@ -154,14 +156,12 @@ JNIEXPORT jdouble JNICALL Java_sun_awt_CGraphicsDevice_nativeGetXResolution (JNIEnv *env, jclass class, jint displayID) { - // TODO: this is the physically correct answer, but we probably want - // to use NSScreen API instead... + // CGDisplayScreenSize can return 0 if displayID is invalid CGSize size = CGDisplayScreenSize(displayID); CGRect rect = CGDisplayBounds(displayID); // 1 inch == 25.4 mm jfloat inches = size.width / 25.4f; - jfloat dpi = rect.size.width / inches; - return dpi; + return inches > 0 ? rect.size.width / inches : 72; } /* @@ -173,14 +173,12 @@ JNIEXPORT jdouble JNICALL Java_sun_awt_CGraphicsDevice_nativeGetYResolution (JNIEnv *env, jclass class, jint displayID) { - // TODO: this is the physically correct answer, but we probably want - // to use NSScreen API instead... + // CGDisplayScreenSize can return 0 if displayID is invalid CGSize size = CGDisplayScreenSize(displayID); CGRect rect = CGDisplayBounds(displayID); // 1 inch == 25.4 mm jfloat inches = size.height / 25.4f; - jfloat dpi = rect.size.height / inches; - return dpi; + return inches > 0 ? rect.size.height / inches : 72; } /* @@ -235,17 +233,19 @@ Java_sun_awt_CGraphicsDevice_nativeSetDisplayMode { JNF_COCOA_ENTER(env); CFArrayRef allModes = getAllValidDisplayModes(displayID); - CGDisplayModeRef closestMatch = getBestModeForParameters(allModes, (int)w, (int)h, (int)bpp, (int)refrate); + __block CGError retCode = kCGErrorSuccess; if (closestMatch != NULL) { - [JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){ + CGDisplayModeRetain(closestMatch); + [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ CGDisplayConfigRef config; retCode = CGBeginDisplayConfiguration(&config); if (retCode == kCGErrorSuccess) { CGConfigureDisplayWithDisplayMode(config, displayID, closestMatch, NULL); retCode = CGCompleteDisplayConfiguration(config, kCGConfigureForAppOnly); } + CGDisplayModeRelease(closestMatch); }]; } else { [JNFException raise:env as:kIllegalArgumentException reason:"Invalid display mode"]; @@ -253,8 +253,7 @@ Java_sun_awt_CGraphicsDevice_nativeSetDisplayMode if (retCode != kCGErrorSuccess){ [JNFException raise:env as:kIllegalArgumentException reason:"Unable to set display mode!"]; - } - + } CFRelease(allModes); JNF_COCOA_EXIT(env); } diff --git a/jdk/src/macosx/native/sun/awt/CImage.m b/jdk/src/macosx/native/sun/awt/CImage.m index b6db3458047..e4ef6306031 100644 --- a/jdk/src/macosx/native/sun/awt/CImage.m +++ b/jdk/src/macosx/native/sun/awt/CImage.m @@ -76,17 +76,17 @@ static void CImage_CopyNSImageIntoArray static NSBitmapImageRep* CImage_CreateImageRep(JNIEnv *env, jintArray buffer, jint width, jint height) { - NSBitmapImageRep* imageRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL - pixelsWide:width - pixelsHigh:height - bitsPerSample:8 - samplesPerPixel:4 - hasAlpha:YES - isPlanar:NO - colorSpaceName:NSDeviceRGBColorSpace - bitmapFormat:NSAlphaFirstBitmapFormat - bytesPerRow:width*4 // TODO: use explicit scanStride - bitsPerPixel:32]; + NSBitmapImageRep* imageRep = [[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL + pixelsWide:width + pixelsHigh:height + bitsPerSample:8 + samplesPerPixel:4 + hasAlpha:YES + isPlanar:NO + colorSpaceName:NSDeviceRGBColorSpace + bitmapFormat:NSAlphaFirstBitmapFormat + bytesPerRow:width*4 // TODO: use explicit scanStride + bitsPerPixel:32] autorelease]; jint *imgData = (jint *)[imageRep bitmapData]; if (imgData == NULL) return 0L; @@ -115,9 +115,8 @@ JNF_COCOA_ENTER(env); NSBitmapImageRep* imageRep = CImage_CreateImageRep(env, buffer, width, height); if (imageRep) { - NSImage *nsImage = [[[NSImage alloc] initWithSize:NSMakeSize(width, height)] retain]; + NSImage *nsImage = [[NSImage alloc] initWithSize:NSMakeSize(width, height)]; [nsImage addRepresentation:imageRep]; - [imageRep release]; result = ptr_to_jlong(nsImage); } @@ -160,7 +159,7 @@ JNF_COCOA_ENTER(env); (*env)->ReleaseIntArrayElements(env, widths, ws, JNI_ABORT); } if ([reps count]) { - NSImage *nsImage = [[[NSImage alloc] initWithSize:NSMakeSize(0, 0)] retain]; + NSImage *nsImage = [[NSImage alloc] initWithSize:NSMakeSize(0, 0)]; [nsImage addRepresentations: reps]; result = ptr_to_jlong(nsImage); } @@ -184,7 +183,7 @@ JNF_COCOA_ENTER(env); IconRef iconRef; if (noErr == GetIconRef(kOnSystemDisk, kSystemIconsCreator, selector, &iconRef)) { - image = [[[NSImage alloc] initWithIconRef:iconRef] retain]; + image = [[NSImage alloc] initWithIconRef:iconRef]; ReleaseIconRef(iconRef); } @@ -206,7 +205,7 @@ JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_CImage_nativeCreateNSImageFromFile JNF_COCOA_ENTER(env); NSString *path = JNFNormalizedNSStringForPath(env, file); - image = [[[NSImage alloc] initByReferencingFile:path] retain]; + image = [[NSImage alloc] initByReferencingFile:path]; JNF_COCOA_EXIT(env); @@ -435,7 +434,7 @@ JNIEXPORT jbyteArray JNICALL Java_sun_lwawt_macosx_CImage_nativeGetPlatformImage JNF_COCOA_ENTER(env); - NSBitmapImageRep* imageRep = [CImage_CreateImageRep(env, buffer, width, height) autorelease]; + NSBitmapImageRep* imageRep = CImage_CreateImageRep(env, buffer, width, height); if (imageRep) { NSData *tiffImage = [imageRep TIFFRepresentation]; jsize tiffSize = (jsize)[tiffImage length]; diff --git a/jdk/src/macosx/native/sun/awt/CTrayIcon.m b/jdk/src/macosx/native/sun/awt/CTrayIcon.m index 79ae024f76f..35adf3b866d 100644 --- a/jdk/src/macosx/native/sun/awt/CTrayIcon.m +++ b/jdk/src/macosx/native/sun/awt/CTrayIcon.m @@ -25,6 +25,7 @@ #import #import +#import "jni_util.h" #import "CTrayIcon.h" #import "ThreadUtilities.h" @@ -146,14 +147,12 @@ static NSSize ScaledImageSizeForStatusBar(NSSize imageSize) { (jint)absP.x, (jint)absP.y, [event deltaY], [event deltaX]); - if (jEvent == nil) { - // Unable to create event by some reason. - return; - } + CHECK_NULL(jEvent); static JNF_CLASS_CACHE(jc_TrayIcon, "sun/lwawt/macosx/CTrayIcon"); static JNF_MEMBER_CACHE(jm_handleMouseEvent, jc_TrayIcon, "handleMouseEvent", "(Lsun/lwawt/macosx/NSEvent;)V"); JNFCallVoidMethod(env, peer, jm_handleMouseEvent, jEvent); + (*env)->DeleteLocalRef(env, jEvent); } @end //AWTTrayIcon diff --git a/jdk/src/macosx/native/sun/awt/LWCToolkit.m b/jdk/src/macosx/native/sun/awt/LWCToolkit.m index c78834547c3..7347ecdd251 100644 --- a/jdk/src/macosx/native/sun/awt/LWCToolkit.m +++ b/jdk/src/macosx/native/sun/awt/LWCToolkit.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 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 @@ -157,61 +157,6 @@ JNF_COCOA_ENTER(env); JNF_COCOA_EXIT(env); } -static JNF_CLASS_CACHE(jc_Component, "java/awt/Component"); -static JNF_MEMBER_CACHE(jf_Component_appContext, jc_Component, "appContext", "Lsun/awt/AppContext;"); -static JNF_CLASS_CACHE(jc_MenuComponent, "java/awt/MenuComponent"); -static JNF_MEMBER_CACHE(jf_MenuComponent_appContext, jc_MenuComponent, "appContext", "Lsun/awt/AppContext;"); - -/* - * Class: sun_awt_SunToolkit - * Method: getAppContext - * Signature: (Ljava/awt/Object;)Lsun/awt/AppContext; - */ -JNIEXPORT jobject JNICALL -Java_sun_awt_SunToolkit_getAppContext -(JNIEnv *env, jclass cls, jobject obj) -{ - jobject appContext = NULL; - -JNF_COCOA_ENTER(env); - - if (JNFIsInstanceOf(env, obj, &jc_Component)) { - appContext = JNFGetObjectField(env, obj, jf_Component_appContext); - } else if (JNFIsInstanceOf(env, obj, &jc_MenuComponent)) { - appContext = JNFGetObjectField(env, obj, jf_MenuComponent_appContext); - } - -JNF_COCOA_EXIT(env); - - return appContext; -} - -/* - * Class: sun_awt_SunToolkit - * Method: setAppContext - * Signature: (Ljava/lang/Object;Lsun/awt/AppContext;)Z - */ -JNIEXPORT jboolean JNICALL -Java_sun_awt_SunToolkit_setAppContext -(JNIEnv *env, jclass cls, jobject obj, jobject appContext) -{ - jboolean isComponent; - -JNF_COCOA_ENTER(env); - - if (JNFIsInstanceOf(env, obj, &jc_Component)) { - JNFSetObjectField(env, obj, jf_Component_appContext, appContext); - isComponent = JNI_TRUE; - } else if (JNFIsInstanceOf(env, obj, &jc_MenuComponent)) { - JNFSetObjectField(env, obj, jf_MenuComponent_appContext, appContext); - isComponent = JNI_FALSE; - } - -JNF_COCOA_EXIT(env); - - return isComponent; -} - /* * Class: sun_lwawt_macosx_LWCToolkit * Method: beep diff --git a/jdk/src/macosx/native/sun/awt/awt.m b/jdk/src/macosx/native/sun/awt/awt.m index 0f553d0e69f..f5fe3ea9eba 100644 --- a/jdk/src/macosx/native/sun/awt/awt.m +++ b/jdk/src/macosx/native/sun/awt/awt.m @@ -435,7 +435,7 @@ JNF_COCOA_ENTER(env); forceEmbeddedMode = YES; } JNIEnv* env = [ThreadUtilities getJNIEnvUncached]; - jclass jc_ThreadGroupUtils = (*env)->FindClass(env, "sun/misc/ThreadGroupUtils"); + jclass jc_ThreadGroupUtils = (*env)->FindClass(env, "sun/awt/util/ThreadGroupUtils"); jmethodID sjm_getRootThreadGroup = (*env)->GetStaticMethodID(env, jc_ThreadGroupUtils, "getRootThreadGroup", "()Ljava/lang/ThreadGroup;"); jobject rootThreadGroup = (*env)->CallStaticObjectMethod(env, jc_ThreadGroupUtils, sjm_getRootThreadGroup); [ThreadUtilities setAppkitThreadGroup:(*env)->NewGlobalRef(env, rootThreadGroup)]; diff --git a/jdk/src/macosx/native/sun/osxapp/AWT_debug.h b/jdk/src/macosx/native/sun/osxapp/AWT_debug.h index 1d02a824f3a..46f57cc6d73 100644 --- a/jdk/src/macosx/native/sun/osxapp/AWT_debug.h +++ b/jdk/src/macosx/native/sun/osxapp/AWT_debug.h @@ -32,9 +32,10 @@ #define kInternalError "java/lang/InternalError" #define AWT_DEBUG_LOG(str) \ - NSLog(@"Cocoa AWT: %@ %@", str, [NSThread callStackSymbols]) + NSLog(@"\tCocoa AWT: %@ %@", str, [NSThread callStackSymbols]) #define AWT_DEBUG_BUG_REPORT_MESSAGE \ - NSLog(@"\tPlease file a bug report at http://java.net/jira/browse/MACOSX_PORT with this message and a reproducible test case.") + NSLog(@"\tPlease file a bug report at http://bugreport.java.com/bugreport \ +with this message and a reproducible test case.") #endif diff --git a/jdk/src/share/bin/java.c b/jdk/src/share/bin/java.c index 79912d52d0a..1db708c90d8 100644 --- a/jdk/src/share/bin/java.c +++ b/jdk/src/share/bin/java.c @@ -739,6 +739,9 @@ SetClassPath(const char *s) if (s == NULL) return; s = JLI_WildcardExpandClasspath(s); + if (sizeof(format) - 2 + JLI_StrLen(s) < JLI_StrLen(s)) + // s is became corrupted after expanding wildcards + return; def = JLI_MemAlloc(sizeof(format) - 2 /* strlen("%s") */ + JLI_StrLen(s)); @@ -1358,9 +1361,11 @@ AddApplicationOptions(int cpathc, const char **cpathv) if (s) { s = (char *) JLI_WildcardExpandClasspath(s); /* 40 for -Denv.class.path= */ - envcp = (char *)JLI_MemAlloc(JLI_StrLen(s) + 40); - sprintf(envcp, "-Denv.class.path=%s", s); - AddOption(envcp, NULL); + if (JLI_StrLen(s) + 40 > JLI_StrLen(s)) { // Safeguard from overflow + envcp = (char *)JLI_MemAlloc(JLI_StrLen(s) + 40); + sprintf(envcp, "-Denv.class.path=%s", s); + AddOption(envcp, NULL); + } } } diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DHParameters.java b/jdk/src/share/classes/com/sun/crypto/provider/DHParameters.java index 57b0e7c3a0c..f8de6b43ff5 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/DHParameters.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/DHParameters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -131,14 +131,14 @@ public final class DHParameters extends AlgorithmParametersSpi { protected String engineToString() { String LINE_SEP = System.getProperty("line.separator"); - StringBuffer strbuf - = new StringBuffer("SunJCE Diffie-Hellman Parameters:" + StringBuilder sb + = new StringBuilder("SunJCE Diffie-Hellman Parameters:" + LINE_SEP + "p:" + LINE_SEP + Debug.toHexString(this.p) + LINE_SEP + "g:" + LINE_SEP + Debug.toHexString(this.g)); if (this.l != 0) - strbuf.append(LINE_SEP + "l:" + LINE_SEP + " " + this.l); - return strbuf.toString(); + sb.append(LINE_SEP + "l:" + LINE_SEP + " " + this.l); + return sb.toString(); } } diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DHPublicKey.java b/jdk/src/share/classes/com/sun/crypto/provider/DHPublicKey.java index 7293c945768..037589c8d53 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/DHPublicKey.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/DHPublicKey.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -260,8 +260,8 @@ javax.crypto.interfaces.DHPublicKey, Serializable { public String toString() { String LINE_SEP = System.getProperty("line.separator"); - StringBuffer strbuf - = new StringBuffer("SunJCE Diffie-Hellman Public Key:" + StringBuilder sb + = new StringBuilder("SunJCE Diffie-Hellman Public Key:" + LINE_SEP + "y:" + LINE_SEP + Debug.toHexString(this.y) + LINE_SEP + "p:" + LINE_SEP @@ -269,8 +269,8 @@ javax.crypto.interfaces.DHPublicKey, Serializable { + LINE_SEP + "g:" + LINE_SEP + Debug.toHexString(this.g)); if (this.l != 0) - strbuf.append(LINE_SEP + "l:" + LINE_SEP + " " + this.l); - return strbuf.toString(); + sb.append(LINE_SEP + "l:" + LINE_SEP + " " + this.l); + return sb.toString(); } private void parseKeyBits() throws InvalidKeyException { diff --git a/jdk/src/share/classes/com/sun/crypto/provider/OAEPParameters.java b/jdk/src/share/classes/com/sun/crypto/provider/OAEPParameters.java index 74b3cc408d9..1ea16cc62e1 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/OAEPParameters.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/OAEPParameters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -238,7 +238,7 @@ public final class OAEPParameters extends AlgorithmParametersSpi { } protected String engineToString() { - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); sb.append("MD: " + mdName + "\n"); sb.append("MGF: MGF1" + mgfSpec.getDigestAlgorithm() + "\n"); sb.append("PSource: PSpecified " + diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java b/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java index 13f2d9349d0..3b2a081d860 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java @@ -664,6 +664,12 @@ public class PNGImageReader extends ImageReader { try { while (true) { int chunkLength = stream.readInt(); + + // verify the chunk length first + if (chunkLength < 0 || chunkLength + 4 < 0) { + throw new IIOException("Invalid chunk length " + chunkLength); + } + int chunkType = stream.readInt(); if (chunkType == IDAT_TYPE) { @@ -692,7 +698,7 @@ public class PNGImageReader extends ImageReader { // verify the chunk length if (chunkLength < 0) { - throw new IIOException("Invalid chunk lenght " + chunkLength); + throw new IIOException("Invalid chunk length " + chunkLength); }; try { diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java index d86b4ec92ac..b35e60d7ec6 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java @@ -1683,6 +1683,7 @@ public class GTKLookAndFeel extends SynthLookAndFeel { * adjustments that windows/metal do. This is because gtk doesn't * provide margins/insets for checkbox/radiobuttons. */ + @SuppressWarnings("fallthrough") private static class GnomeLayoutStyle extends DefaultLayoutStyle { private static GnomeLayoutStyle INSTANCE = new GnomeLayoutStyle(); diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java index 00530fa19ea..a6c1c895757 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java @@ -2409,6 +2409,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel // Windows LayoutStyle. From: // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwue/html/ch14e.asp + @SuppressWarnings("fallthrough") private class WindowsLayoutStyle extends DefaultLayoutStyle { @Override public int getPreferredGap(JComponent component1, diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsScrollBarUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsScrollBarUI.java index 279bdb72b79..418f326165f 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsScrollBarUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsScrollBarUI.java @@ -51,6 +51,8 @@ import static com.sun.java.swing.plaf.windows.XPStyle.Skin; public class WindowsScrollBarUI extends BasicScrollBarUI { private Grid thumbGrid; private Grid highlightGrid; + private Dimension horizontalThumbSize; + private Dimension verticalThumbSize; /** * Creates a UI for a JScrollBar. @@ -65,11 +67,32 @@ public class WindowsScrollBarUI extends BasicScrollBarUI { protected void installDefaults() { super.installDefaults(); - if (XPStyle.getXP() != null) { + XPStyle xp = XPStyle.getXP(); + if (xp != null) { scrollbar.setBorder(null); + horizontalThumbSize = getSize(scrollbar, xp, Part.SBP_THUMBBTNHORZ); + verticalThumbSize = getSize(scrollbar, xp, Part.SBP_THUMBBTNVERT); + } else { + horizontalThumbSize = null; + verticalThumbSize = null; } } + private static Dimension getSize(Component component, XPStyle xp, Part part) { + Skin skin = xp.getSkin(component, part); + return new Dimension(skin.getWidth(), skin.getHeight()); + } + + @Override + protected Dimension getMinimumThumbSize() { + if ((horizontalThumbSize == null) || (verticalThumbSize == null)) { + return super.getMinimumThumbSize(); + } + return JScrollBar.HORIZONTAL == scrollbar.getOrientation() + ? horizontalThumbSize + : verticalThumbSize; + } + public void uninstallUI(JComponent c) { super.uninstallUI(c); thumbGrid = highlightGrid = null; diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java index c5101177f40..117e9d7b7b1 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsTableHeaderUI.java @@ -182,7 +182,6 @@ public class WindowsTableHeaderUI extends BasicTableHeaderUI { if (sortOrder != null) { switch(sortOrder) { case ASCENDING: - /* falls through */ case DESCENDING: switch (state) { case NORMAL: @@ -197,6 +196,7 @@ public class WindowsTableHeaderUI extends BasicTableHeaderUI { default: /* do nothing */ } + break; default : /* do nothing */ } diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java b/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java index 65a675ffdf5..d41c94480e9 100644 --- a/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java +++ b/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -459,10 +459,10 @@ public final class Connection implements Runnable { // will be woken up before readTimeout only if reply is // available ldr.wait(readTimeout); - waited = true; } else { ldr.wait(15 * 1000); // 15 second timeout } + waited = true; } else { break; } @@ -474,7 +474,7 @@ public final class Connection implements Runnable { } if ((rber == null) && waited) { - removeRequest(ldr); + abandonRequest(ldr, null); throw new NamingException("LDAP response read timed out, timeout used:" + readTimeout + "ms." ); diff --git a/jdk/src/share/classes/com/sun/media/sound/AbstractLine.java b/jdk/src/share/classes/com/sun/media/sound/AbstractLine.java index e6a7ba2d9cb..1d0393d35eb 100644 --- a/jdk/src/share/classes/com/sun/media/sound/AbstractLine.java +++ b/jdk/src/share/classes/com/sun/media/sound/AbstractLine.java @@ -48,7 +48,7 @@ abstract class AbstractLine implements Line { protected Control[] controls; AbstractMixer mixer; private boolean open = false; - private final Vector listeners = new Vector(); + private final Vector listeners = new Vector<>(); /** * Contains event dispatcher per thread group. diff --git a/jdk/src/share/classes/com/sun/media/sound/AbstractMidiDevice.java b/jdk/src/share/classes/com/sun/media/sound/AbstractMidiDevice.java index 4323970cafa..93c3926aaed 100644 --- a/jdk/src/share/classes/com/sun/media/sound/AbstractMidiDevice.java +++ b/jdk/src/share/classes/com/sun/media/sound/AbstractMidiDevice.java @@ -70,7 +70,7 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice /** List of Receivers and Transmitters that opened the device implicitely. */ - private List openKeepingObjects; + private List openKeepingObjects; /** * This is the device handle returned from native code @@ -284,6 +284,7 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice } + @SuppressWarnings("unchecked") // Cast of result of clone public final List getReceivers() { List recs; synchronized (traRecLock) { @@ -313,6 +314,7 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice } + @SuppressWarnings("unchecked") // Cast of result of clone public final List getTransmitters() { List tras; synchronized (traRecLock) { @@ -372,9 +374,9 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice /** Return the list of objects that have opened the device implicitely. */ - private synchronized List getOpenKeepingObjects() { + private synchronized List getOpenKeepingObjects() { if (openKeepingObjects == null) { - openKeepingObjects = new ArrayList(); + openKeepingObjects = new ArrayList<>(); } return openKeepingObjects; } diff --git a/jdk/src/share/classes/com/sun/media/sound/AbstractMixer.java b/jdk/src/share/classes/com/sun/media/sound/AbstractMixer.java index 1055fc6859e..83378615b77 100644 --- a/jdk/src/share/classes/com/sun/media/sound/AbstractMixer.java +++ b/jdk/src/share/classes/com/sun/media/sound/AbstractMixer.java @@ -90,13 +90,13 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { /** * Source lines (ports) currently open */ - private final Vector sourceLines = new Vector(); + private final Vector sourceLines = new Vector<>(); /** * Target lines currently open. */ - private final Vector targetLines = new Vector(); + private final Vector targetLines = new Vector<>(); /** @@ -151,7 +151,7 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { public final Line.Info[] getSourceLineInfo(Line.Info info) { int i; - Vector vec = new Vector(); + Vector vec = new Vector<>(); for (i = 0; i < sourceLineInfo.length; i++) { @@ -162,7 +162,7 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { Line.Info[] returnedArray = new Line.Info[vec.size()]; for (i = 0; i < returnedArray.length; i++) { - returnedArray[i] = (Line.Info)vec.elementAt(i); + returnedArray[i] = vec.elementAt(i); } return returnedArray; @@ -172,7 +172,7 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { public final Line.Info[] getTargetLineInfo(Line.Info info) { int i; - Vector vec = new Vector(); + Vector vec = new Vector<>(); for (i = 0; i < targetLineInfo.length; i++) { @@ -183,7 +183,7 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { Line.Info[] returnedArray = new Line.Info[vec.size()]; for (i = 0; i < returnedArray.length; i++) { - returnedArray[i] = (Line.Info)vec.elementAt(i); + returnedArray[i] = vec.elementAt(i); } return returnedArray; @@ -231,7 +231,7 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { localLines = new Line[sourceLines.size()]; for (int i = 0; i < localLines.length; i++) { - localLines[i] = (Line)sourceLines.elementAt(i); + localLines[i] = sourceLines.elementAt(i); } } @@ -248,7 +248,7 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { localLines = new Line[targetLines.size()]; for (int i = 0; i < localLines.length; i++) { - localLines[i] = (Line)targetLines.elementAt(i); + localLines[i] = targetLines.elementAt(i); } } @@ -453,7 +453,8 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { return; } - Vector localSourceLines = (Vector)sourceLines.clone(); + @SuppressWarnings("unchecked") + Vector localSourceLines = (Vector)sourceLines.clone(); for (int i = 0; i < localSourceLines.size(); i++) { // if any other open line is running, return @@ -468,7 +469,8 @@ abstract class AbstractMixer extends AbstractLine implements Mixer { } } - Vector localTargetLines = (Vector)targetLines.clone(); + @SuppressWarnings("unchecked") + Vector localTargetLines = (Vector)targetLines.clone(); for (int i = 0; i < localTargetLines.size(); i++) { // if any other open line is running, return diff --git a/jdk/src/share/classes/com/sun/media/sound/AlawCodec.java b/jdk/src/share/classes/com/sun/media/sound/AlawCodec.java index 367f318b06a..fbe63f6ff16 100644 --- a/jdk/src/share/classes/com/sun/media/sound/AlawCodec.java +++ b/jdk/src/share/classes/com/sun/media/sound/AlawCodec.java @@ -213,7 +213,7 @@ public final class AlawCodec extends SunCodec { private AudioFormat[] getOutputFormats(AudioFormat inputFormat) { - Vector formats = new Vector(); + Vector formats = new Vector<>(); AudioFormat format; if ( AudioFormat.Encoding.PCM_SIGNED.equals(inputFormat.getEncoding())) { @@ -248,7 +248,7 @@ public final class AlawCodec extends SunCodec { AudioFormat[] formatArray = new AudioFormat[formats.size()]; for (int i = 0; i < formatArray.length; i++) { - formatArray[i] = (AudioFormat)(formats.elementAt(i)); + formatArray[i] = formats.elementAt(i); } return formatArray; } diff --git a/jdk/src/share/classes/com/sun/media/sound/AudioSynthesizerPropertyInfo.java b/jdk/src/share/classes/com/sun/media/sound/AudioSynthesizerPropertyInfo.java index d4305523526..16bfaa20790 100644 --- a/jdk/src/share/classes/com/sun/media/sound/AudioSynthesizerPropertyInfo.java +++ b/jdk/src/share/classes/com/sun/media/sound/AudioSynthesizerPropertyInfo.java @@ -68,7 +68,7 @@ public final class AudioSynthesizerPropertyInfo { * The valueClass field specifies class * used in value field. */ - public Class valueClass = null; + public Class valueClass = null; /** * An array of possible values if the value for the field * AudioSynthesizerPropertyInfo.value may be selected diff --git a/jdk/src/share/classes/com/sun/media/sound/DirectAudioDevice.java b/jdk/src/share/classes/com/sun/media/sound/DirectAudioDevice.java index 7c938bbb1c4..becf4981ba7 100644 --- a/jdk/src/share/classes/com/sun/media/sound/DirectAudioDevice.java +++ b/jdk/src/share/classes/com/sun/media/sound/DirectAudioDevice.java @@ -94,7 +94,7 @@ final class DirectAudioDevice extends AbstractMixer { } private DirectDLI createDataLineInfo(boolean isSource) { - Vector formats = new Vector(); + Vector formats = new Vector<>(); AudioFormat[] hardwareFormatArray = null; AudioFormat[] formatArray = null; @@ -107,7 +107,7 @@ final class DirectAudioDevice extends AbstractMixer { int formatArraySize = size; hardwareFormatArray = new AudioFormat[size]; for (int i = 0; i < size; i++) { - AudioFormat format = (AudioFormat)formats.elementAt(i); + AudioFormat format = formats.elementAt(i); hardwareFormatArray[i] = format; int bits = format.getSampleSizeInBits(); boolean isSigned = format.getEncoding().equals(AudioFormat.Encoding.PCM_SIGNED); @@ -265,7 +265,7 @@ final class DirectAudioDevice extends AbstractMixer { return ((DirectAudioDeviceProvider.DirectAudioDeviceInfo) getMixerInfo()).getMaxSimulLines(); } - private static void addFormat(Vector v, int bits, int frameSizeInBytes, int channels, float sampleRate, + private static void addFormat(Vector v, int bits, int frameSizeInBytes, int channels, float sampleRate, int encoding, boolean signed, boolean bigEndian) { AudioFormat.Encoding enc = null; switch (encoding) { @@ -338,7 +338,7 @@ final class DirectAudioDevice extends AbstractMixer { private static final class DirectDLI extends DataLine.Info { final AudioFormat[] hardwareFormats; - private DirectDLI(Class clazz, AudioFormat[] formatArray, + private DirectDLI(Class clazz, AudioFormat[] formatArray, AudioFormat[] hardwareFormatArray, int minBuffer, int maxBuffer) { super(clazz, formatArray, minBuffer, maxBuffer); @@ -1457,7 +1457,7 @@ final class DirectAudioDevice extends AbstractMixer { } // class DirectBAOS - + @SuppressWarnings("rawtypes") private static native void nGetFormats(int mixerIndex, int deviceID, boolean isSource, Vector formats); diff --git a/jdk/src/share/classes/com/sun/media/sound/EventDispatcher.java b/jdk/src/share/classes/com/sun/media/sound/EventDispatcher.java index 54b948af168..49709891bd0 100644 --- a/jdk/src/share/classes/com/sun/media/sound/EventDispatcher.java +++ b/jdk/src/share/classes/com/sun/media/sound/EventDispatcher.java @@ -57,7 +57,7 @@ final class EventDispatcher implements Runnable { /** * List of events */ - private final ArrayList eventQueue = new ArrayList(); + private final ArrayList eventQueue = new ArrayList<>(); /** @@ -186,7 +186,7 @@ final class EventDispatcher implements Runnable { } if (eventQueue.size() > 0) { // Remove the event from the queue and dispatch it to the listeners. - eventInfo = (EventInfo) eventQueue.remove(0); + eventInfo = eventQueue.remove(0); } } // end of synchronized @@ -230,7 +230,7 @@ final class EventDispatcher implements Runnable { /** * Send audio and MIDI events. */ - void sendAudioEvents(Object event, List listeners) { + void sendAudioEvents(Object event, List listeners) { if ((listeners == null) || (listeners.size() == 0)) { // nothing to do @@ -392,7 +392,7 @@ final class EventDispatcher implements Runnable { * @param event the event to be dispatched * @param listeners listener list; will be copied */ - EventInfo(Object event, List listeners) { + EventInfo(Object event, List listeners) { this.event = event; this.listeners = listeners.toArray(); } diff --git a/jdk/src/share/classes/com/sun/media/sound/JDK13Services.java b/jdk/src/share/classes/com/sun/media/sound/JDK13Services.java index 9f19a8734e3..9c93d06dc23 100644 --- a/jdk/src/share/classes/com/sun/media/sound/JDK13Services.java +++ b/jdk/src/share/classes/com/sun/media/sound/JDK13Services.java @@ -118,7 +118,7 @@ public final class JDK13Services { (the part before the hash sign), if available. If the property is not set or the value has no provider class name part, null is returned. */ - public static synchronized String getDefaultProviderClassName(Class typeClass) { + public static synchronized String getDefaultProviderClassName(Class typeClass) { String value = null; String defaultProviderSpec = getDefaultProvider(typeClass); if (defaultProviderSpec != null) { @@ -144,7 +144,7 @@ public final class JDK13Services { part after the hash sign), if available. If the property is not set or the value has no instance name part, null is returned. */ - public static synchronized String getDefaultInstanceName(Class typeClass) { + public static synchronized String getDefaultInstanceName(Class typeClass) { String value = null; String defaultProviderSpec = getDefaultProvider(typeClass); if (defaultProviderSpec != null) { @@ -165,7 +165,7 @@ public final class JDK13Services { @return The complete value of the property, if available. If the property is not set, null is returned. */ - private static synchronized String getDefaultProvider(Class typeClass) { + private static synchronized String getDefaultProvider(Class typeClass) { if (!SourceDataLine.class.equals(typeClass) && !TargetDataLine.class.equals(typeClass) && !Clip.class.equals(typeClass) diff --git a/jdk/src/share/classes/com/sun/media/sound/MidiInDeviceProvider.java b/jdk/src/share/classes/com/sun/media/sound/MidiInDeviceProvider.java index 1f397724e3f..5044dfeaa17 100644 --- a/jdk/src/share/classes/com/sun/media/sound/MidiInDeviceProvider.java +++ b/jdk/src/share/classes/com/sun/media/sound/MidiInDeviceProvider.java @@ -106,9 +106,9 @@ public final class MidiInDeviceProvider extends AbstractMidiDeviceProvider { * the new instance will not reflect that state... */ static final class MidiInDeviceInfo extends AbstractMidiDeviceProvider.Info { - private final Class providerClass; + private final Class providerClass; - private MidiInDeviceInfo(int index, Class providerClass) { + private MidiInDeviceInfo(int index, Class providerClass) { super(nGetName(index), nGetVendor(index), nGetDescription(index), nGetVersion(index), index); this.providerClass = providerClass; } diff --git a/jdk/src/share/classes/com/sun/media/sound/MidiOutDeviceProvider.java b/jdk/src/share/classes/com/sun/media/sound/MidiOutDeviceProvider.java index 75583ab1e65..eaacf0991be 100644 --- a/jdk/src/share/classes/com/sun/media/sound/MidiOutDeviceProvider.java +++ b/jdk/src/share/classes/com/sun/media/sound/MidiOutDeviceProvider.java @@ -104,9 +104,9 @@ public final class MidiOutDeviceProvider extends AbstractMidiDeviceProvider { * the new instance will not reflect that state... */ static final class MidiOutDeviceInfo extends AbstractMidiDeviceProvider.Info { - private final Class providerClass; + private final Class providerClass; - private MidiOutDeviceInfo(int index, Class providerClass) { + private MidiOutDeviceInfo(int index, Class providerClass) { super(nGetName(index), nGetVendor(index), nGetDescription(index), nGetVersion(index), index); this.providerClass = providerClass; } diff --git a/jdk/src/share/classes/com/sun/media/sound/MidiUtils.java b/jdk/src/share/classes/com/sun/media/sound/MidiUtils.java index a3f62efd29e..eecd33fe0b5 100644 --- a/jdk/src/share/classes/com/sun/media/sound/MidiUtils.java +++ b/jdk/src/share/classes/com/sun/media/sound/MidiUtils.java @@ -295,7 +295,7 @@ public final class MidiUtils { public synchronized void refresh(Sequence seq) { - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList<>(); Track[] tracks = seq.getTracks(); if (tracks.length > 0) { // tempo events only occur in track 0 @@ -313,7 +313,7 @@ public final class MidiUtils { int size = list.size() + 1; firstTempoIsFake = true; if ((size > 1) - && (((MidiEvent) list.get(0)).getTick() == 0)) { + && (list.get(0).getTick() == 0)) { // do not need to add an initial tempo event at the beginning size--; firstTempoIsFake = false; @@ -328,7 +328,7 @@ public final class MidiUtils { e++; } for (int i = 0; i < list.size(); i++, e++) { - MidiEvent evt = (MidiEvent) list.get(i); + MidiEvent evt = list.get(i); ticks[e] = evt.getTick(); tempos[e] = getTempoMPQ(evt.getMessage()); } diff --git a/jdk/src/share/classes/com/sun/media/sound/PCMtoPCMCodec.java b/jdk/src/share/classes/com/sun/media/sound/PCMtoPCMCodec.java index 9a4f1a874b3..dbed920e6fa 100644 --- a/jdk/src/share/classes/com/sun/media/sound/PCMtoPCMCodec.java +++ b/jdk/src/share/classes/com/sun/media/sound/PCMtoPCMCodec.java @@ -91,7 +91,7 @@ public final class PCMtoPCMCodec extends SunCodec { // filter out targetEncoding from the old getOutputFormats( sourceFormat ) method AudioFormat[] formats = getOutputFormats( sourceFormat ); - Vector newFormats = new Vector(); + Vector newFormats = new Vector<>(); for(int i=0; i formats = new Vector<>(); AudioFormat format; int sampleSize = inputFormat.getSampleSizeInBits(); @@ -335,7 +335,7 @@ public final class PCMtoPCMCodec extends SunCodec { for (int i = 0; i < formatArray.length; i++) { - formatArray[i] = (AudioFormat)(formats.elementAt(i)); + formatArray[i] = formats.elementAt(i); } } diff --git a/jdk/src/share/classes/com/sun/media/sound/PortMixer.java b/jdk/src/share/classes/com/sun/media/sound/PortMixer.java index 705648004ff..ee0fbd064ae 100644 --- a/jdk/src/share/classes/com/sun/media/sound/PortMixer.java +++ b/jdk/src/share/classes/com/sun/media/sound/PortMixer.java @@ -253,12 +253,12 @@ final class PortMixer extends AbstractMixer { long newID = ((PortMixer) mixer).getID(); if ((id == 0) || (newID != id) || (controls.length == 0)) { id = newID; - Vector vector = new Vector(); + Vector vector = new Vector<>(); synchronized (vector) { nGetControls(id, portIndex, vector); controls = new Control[vector.size()]; for (int i = 0; i < controls.length; i++) { - controls[i] = (Control) vector.elementAt(i); + controls[i] = vector.elementAt(i); } } } else { @@ -494,6 +494,7 @@ final class PortMixer extends AbstractMixer { private static native String nGetPortName(long id, int portIndex); // fills the vector with the controls for this port + @SuppressWarnings("rawtypes") private static native void nGetControls(long id, int portIndex, Vector vector); // getters/setters for controls diff --git a/jdk/src/share/classes/com/sun/media/sound/RealTimeSequencer.java b/jdk/src/share/classes/com/sun/media/sound/RealTimeSequencer.java index 6ea2ec4b3c6..7252723e776 100644 --- a/jdk/src/share/classes/com/sun/media/sound/RealTimeSequencer.java +++ b/jdk/src/share/classes/com/sun/media/sound/RealTimeSequencer.java @@ -122,7 +122,7 @@ final class RealTimeSequencer extends AbstractMidiDevice /** * List of tracks to which we're recording */ - private final List recordingTracks = new ArrayList(); + private final List recordingTracks = new ArrayList<>(); private long loopStart = 0; @@ -133,13 +133,13 @@ final class RealTimeSequencer extends AbstractMidiDevice /** * Meta event listeners */ - private final ArrayList metaEventListeners = new ArrayList(); + private final ArrayList metaEventListeners = new ArrayList<>(); /** * Control change listeners */ - private final ArrayList controllerEventListeners = new ArrayList(); + private final ArrayList controllerEventListeners = new ArrayList<>(); /** automatic connection support */ @@ -645,7 +645,7 @@ final class RealTimeSequencer extends AbstractMidiDevice boolean flag = false; for(int i=0; i < controllerEventListeners.size(); i++) { - cve = (ControllerListElement) controllerEventListeners.get(i); + cve = controllerEventListeners.get(i); if (cve.listener.equals(listener)) { cve.addControllers(controllers); @@ -669,7 +669,7 @@ final class RealTimeSequencer extends AbstractMidiDevice ControllerListElement cve = null; boolean flag = false; for (int i=0; i < controllerEventListeners.size(); i++) { - cve = (ControllerListElement) controllerEventListeners.get(i); + cve = controllerEventListeners.get(i); if (cve.listener.equals(listener)) { cve.removeControllers(controllers); flag = true; @@ -940,9 +940,9 @@ final class RealTimeSequencer extends AbstractMidiDevice } ShortMessage msg = (ShortMessage) message; int controller = msg.getData1(); - List sendToListeners = new ArrayList(); + List sendToListeners = new ArrayList<>(); for (int i = 0; i < size; i++) { - ControllerListElement cve = (ControllerListElement) controllerEventListeners.get(i); + ControllerListElement cve = controllerEventListeners.get(i); for(int j = 0; j < cve.controllers.length; j++) { if (cve.controllers[j] == controller) { sendToListeners.add(cve.listener); @@ -1213,13 +1213,13 @@ final class RealTimeSequencer extends AbstractMidiDevice this.channel = channel; } - static RecordingTrack get(List recordingTracks, Track track) { + static RecordingTrack get(List recordingTracks, Track track) { synchronized(recordingTracks) { int size = recordingTracks.size(); for (int i = 0; i < size; i++) { - RecordingTrack current = (RecordingTrack)recordingTracks.get(i); + RecordingTrack current = recordingTracks.get(i); if (current.track == track) { return current; } @@ -1228,12 +1228,12 @@ final class RealTimeSequencer extends AbstractMidiDevice return null; } - static Track get(List recordingTracks, int channel) { + static Track get(List recordingTracks, int channel) { synchronized(recordingTracks) { int size = recordingTracks.size(); for (int i = 0; i < size; i++) { - RecordingTrack current = (RecordingTrack)recordingTracks.get(i); + RecordingTrack current = recordingTracks.get(i); if ((current.channel == channel) || (current.channel == -1)) { return current.track; } diff --git a/jdk/src/share/classes/com/sun/media/sound/SoftSynthesizer.java b/jdk/src/share/classes/com/sun/media/sound/SoftSynthesizer.java index 01a64c2dddf..2c6dff99fea 100644 --- a/jdk/src/share/classes/com/sun/media/sound/SoftSynthesizer.java +++ b/jdk/src/share/classes/com/sun/media/sound/SoftSynthesizer.java @@ -949,7 +949,7 @@ public final class SoftSynthesizer implements AudioSynthesizer, Object v = (info == null) ? null : info.get(item2.name); v = (v != null) ? v : storedProperties.getProperty(item2.name); if (v != null) { - Class c = (item2.valueClass); + Class c = (item2.valueClass); if (c.isInstance(v)) item2.value = v; else if (v instanceof String) { diff --git a/jdk/src/share/classes/com/sun/media/sound/UlawCodec.java b/jdk/src/share/classes/com/sun/media/sound/UlawCodec.java index 7dda283a0da..337fe199788 100644 --- a/jdk/src/share/classes/com/sun/media/sound/UlawCodec.java +++ b/jdk/src/share/classes/com/sun/media/sound/UlawCodec.java @@ -198,7 +198,7 @@ public final class UlawCodec extends SunCodec { /* public AudioFormat[] getOutputFormats(AudioFormat inputFormat) { */ private AudioFormat[] getOutputFormats(AudioFormat inputFormat) { - Vector formats = new Vector(); + Vector formats = new Vector<>(); AudioFormat format; if ((inputFormat.getSampleSizeInBits() == 16) @@ -235,7 +235,7 @@ public final class UlawCodec extends SunCodec { AudioFormat[] formatArray = new AudioFormat[formats.size()]; for (int i = 0; i < formatArray.length; i++) { - formatArray[i] = (AudioFormat)(formats.elementAt(i)); + formatArray[i] = formats.elementAt(i); } return formatArray; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/etsi.xsd b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/etsi.xsd deleted file mode 100644 index d69852ff842..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/etsi.xsd +++ /dev/null @@ -1,347 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xenc-schema.rng b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xenc-schema.rng deleted file mode 100644 index 895e033a626..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xenc-schema.rng +++ /dev/null @@ -1,219 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xenc-schema.xsd b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xenc-schema.xsd deleted file mode 100644 index 85af68b5518..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xenc-schema.xsd +++ /dev/null @@ -1,146 +0,0 @@ - - - - - - ]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.dtd b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.dtd deleted file mode 100644 index b2cc19f63a1..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.dtd +++ /dev/null @@ -1,171 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.rng b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.rng deleted file mode 100644 index 03330fb1fee..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.rng +++ /dev/null @@ -1,339 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.xsd b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.xsd deleted file mode 100644 index e8288a526c3..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/schema/xmldsig-core-schema.xsd +++ /dev/null @@ -1,318 +0,0 @@ - - - - - - ]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jdk/src/share/classes/com/sun/pept/Delegate.java b/jdk/src/share/classes/com/sun/pept/Delegate.java deleted file mode 100644 index 7d29ce00c6b..00000000000 --- a/jdk/src/share/classes/com/sun/pept/Delegate.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 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. - */ - -/** Java interface "Delegate.java" generated from Poseidon for UML. - * Poseidon for UML is developed by Gentleware. - * Generated with velocity template engine. - */ -package com.sun.pept; - -import com.sun.pept.presentation.MessageStruct; -import java.util.*; - -/** - *

- * - * @author Dr. Harold Carr - *

- */ -public interface Delegate { - - /////////////////////////////////////// - // operations - -/** - *

- * Does ... - *

- * - * @return a MessageStruct with ... - *

- */ - public MessageStruct getMessageStruct(); -/** - *

- * Does ... - *

- * - *

- * - * @param message ... - *

- */ - public void send(MessageStruct message); - -} // end Delegate diff --git a/jdk/src/share/classes/com/sun/pept/encoding/Decoder.java b/jdk/src/share/classes/com/sun/pept/encoding/Decoder.java deleted file mode 100644 index 3af6e03bc84..00000000000 --- a/jdk/src/share/classes/com/sun/pept/encoding/Decoder.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 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. - */ - -/** Java interface "Decoder.java" generated from Poseidon for UML. - * Poseidon for UML is developed by Gentleware. - * Generated with velocity template engine. - */ -package com.sun.pept.encoding; - -import com.sun.pept.ept.MessageInfo; -import java.util.*; - -/** - *

- * - * @author Dr. Harold Carr - *

- */ -public interface Decoder { - - /////////////////////////////////////// - // operations - -/** - *

- * Does ... - *

- * - *

- * - * @param messageInfo ... - *

- */ - public void decode(MessageInfo messageInfo); -/** - *

- * Does ... - *

- * - *

- * - * @param messageInfo ... - *

- */ - public void receiveAndDecode(MessageInfo messageInfo); - -} // end Decoder diff --git a/jdk/src/share/classes/com/sun/pept/encoding/Encoder.java b/jdk/src/share/classes/com/sun/pept/encoding/Encoder.java deleted file mode 100644 index 66a6d642931..00000000000 --- a/jdk/src/share/classes/com/sun/pept/encoding/Encoder.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 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. - */ - -/** Java interface "Encoder.java" generated from Poseidon for UML. - * Poseidon for UML is developed by Gentleware. - * Generated with velocity template engine. - */ -package com.sun.pept.encoding; - -import com.sun.pept.ept.MessageInfo; -import java.nio.ByteBuffer; -import java.util.*; - -/** - *

- * - * @author Arun Gupta - *

- */ -public interface Encoder { - - /////////////////////////////////////// - // operations - -/** - *

- * Does ... - *

- * - *

- * - * @param messageInfo ... - *

- */ - public void encodeAndSend(MessageInfo messageInfo); -/** - *

- * Does ... - *

- * - * @return a ByteBuffer with ... - *

- * @param messageInfo ... - *

- */ - public ByteBuffer encode(MessageInfo messageInfo); - -} // end Encoder diff --git a/jdk/src/share/classes/com/sun/pept/ept/ContactInfo.java b/jdk/src/share/classes/com/sun/pept/ept/ContactInfo.java deleted file mode 100644 index 2981a5128b3..00000000000 --- a/jdk/src/share/classes/com/sun/pept/ept/ContactInfo.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 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. - */ - -/** Java interface "ContactInfo.java" generated from Poseidon for UML. - * Poseidon for UML is developed by Gentleware. - * Generated with velocity template engine. - */ -package com.sun.pept.ept; - -import com.sun.pept.transport.Connection; -import java.util.*; - -/** - *

- * - * @author Dr. Harold Carr - *

- */ -public interface ContactInfo extends EPTFactory { - - /////////////////////////////////////// - // operations - -/** - *

- * Does ... - *

- * - * @return a Connection with ... - *

- * @param messageInfo ... - *

- */ - public Connection getConnection(MessageInfo messageInfo); - -} // end ContactInfo diff --git a/jdk/src/share/classes/com/sun/pept/ept/ContactInfoListIterator.java b/jdk/src/share/classes/com/sun/pept/ept/ContactInfoListIterator.java deleted file mode 100644 index 16143ddcb6b..00000000000 --- a/jdk/src/share/classes/com/sun/pept/ept/ContactInfoListIterator.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 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. - */ - -/** Java interface "ContactInfoListIterator.java" generated from Poseidon for UML. - * Poseidon for UML is developed by Gentleware. - * Generated with velocity template engine. - */ -package com.sun.pept.ept; - -import java.util.*; - -/** - *

- * - * @author Dr. Harold Carr - *

- */ -public interface ContactInfoListIterator { - - /////////////////////////////////////// - // operations - -/** - *

- * Does ... - *

- * - * @return a boolean with ... - *

- */ - public boolean hasNext(); -/** - *

- * Does ... - *

- * - * @return a ContactInfo with ... - *

- */ - public ContactInfo next(); - -} // end ContactInfoListIterator diff --git a/jdk/src/share/classes/com/sun/pept/ept/EPTFactory.java b/jdk/src/share/classes/com/sun/pept/ept/EPTFactory.java deleted file mode 100644 index 05595f09282..00000000000 --- a/jdk/src/share/classes/com/sun/pept/ept/EPTFactory.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 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. - */ - -/** Java interface "EPTFactory.java" generated from Poseidon for UML. - * Poseidon for UML is developed by Gentleware. - * Generated with velocity template engine. - */ -package com.sun.pept.ept; - -import com.sun.pept.encoding.Decoder; -import com.sun.pept.encoding.Encoder; -import com.sun.pept.presentation.TargetFinder; -import com.sun.pept.protocol.Interceptors; -import com.sun.pept.protocol.MessageDispatcher; -import java.util.*; - -/** - *

- * - * @author Dr. Harold Carr - *

- */ -public interface EPTFactory { - - /////////////////////////////////////// - // operations - -/** - *

- * Does ... - *

- * - * @return a MessageDispatcher with ... - *

- * @param messageInfo ... - *

- */ - public MessageDispatcher getMessageDispatcher(MessageInfo messageInfo); -/** - *

- * Does ... - *

- * - * @return a Encoder with ... - *

- * @param messageInfo ... - *

- */ - public Encoder getEncoder(MessageInfo messageInfo); -/** - *

- * Does ... - *

- * - * @return a Decoder with ... - *

- * @param messageInfo ... - *

- */ - public Decoder getDecoder(MessageInfo messageInfo); -/** - *

- * Does ... - *

- * - * @return a Interceptors with ... - *

- * @param x ... - *

- */ - public Interceptors getInterceptors(MessageInfo x); -/** - *

- * Does ... - *

- * - * @return a TargetFinder with ... - *

- * @param x ... - *

- */ - public TargetFinder getTargetFinder(MessageInfo x); - -} // end EPTFactory diff --git a/jdk/src/share/classes/com/sun/pept/ept/MessageInfo.java b/jdk/src/share/classes/com/sun/pept/ept/MessageInfo.java deleted file mode 100644 index 9a4cd159a55..00000000000 --- a/jdk/src/share/classes/com/sun/pept/ept/MessageInfo.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) 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. - */ - -/** Java interface "MessageInfo.java" generated from Poseidon for UML. - * Poseidon for UML is developed by Gentleware. - * Generated with velocity template engine. - */ -package com.sun.pept.ept; - -import com.sun.pept.encoding.Decoder; -import com.sun.pept.encoding.Encoder; -import com.sun.pept.presentation.MessageStruct; -import com.sun.pept.protocol.MessageDispatcher; -import com.sun.pept.transport.Connection; -import java.util.*; - -/** - *

- * - * @author Dr. Harold Carr - *

- */ -public interface MessageInfo extends MessageStruct { - - /////////////////////////////////////// - // operations - -/** - *

- * Does ... - *

- * - * @return a EPTFactory with ... - *

- */ - public EPTFactory getEPTFactory(); -/** - *

- * Does ... - *

- * - * @return a MessageDispatcher with ... - *

- */ - public MessageDispatcher getMessageDispatcher(); -/** - *

- * Does ... - *

- * - * @return a Encoder with ... - *

- */ - public Encoder getEncoder(); -/** - *

- * Does ... - *

- * - * @return a Decoder with ... - *

- */ - public Decoder getDecoder(); -/** - *

- * Does ... - *

- * - * @return a Connection with ... - *

- */ - public Connection getConnection(); -/** - *

- * Does ... - *

- * - *

- * - * @param eptFactory ... - *

- */ - public void setEPTFactory(EPTFactory eptFactory); -/** - *

- * Does ... - *

- * - *

- * - * @param messageDispatcher ... - *

- */ - public void setMessageDispatcher(MessageDispatcher messageDispatcher); -/** - *

- * Does ... - *

- * - *

- * - * @param encoder ... - *

- */ - public void setEncoder(Encoder encoder); -/** - *

- * Does ... - *

- * - *

- * - * @param decoder ... - *

- */ - public void setDecoder(Decoder decoder); -/** - *

- * Does ... - *

- * - *

- * - * @param connection ... - *

- */ - public void setConnection(Connection connection); - -} // end MessageInfo diff --git a/jdk/src/share/classes/com/sun/pept/presentation/MessageStruct.java b/jdk/src/share/classes/com/sun/pept/presentation/MessageStruct.java deleted file mode 100644 index 85f4fc7f889..00000000000 --- a/jdk/src/share/classes/com/sun/pept/presentation/MessageStruct.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) 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. - */ - -/** Java interface "MessageStruct.java" generated from Poseidon for UML. - * Poseidon for UML is developed by Gentleware. - * Generated with velocity template engine. - */ -package com.sun.pept.presentation; - -import java.util.*; -import java.lang.reflect.Method; -/** - *

- * - * @author Dr. Harold Carr - *

- */ -public interface MessageStruct { - - /////////////////////////////////////// - //attributes - - -/** - *

- * Represents ... - *

- */ - public static final int NORMAL_RESPONSE = 0; - -/** - *

- * Represents ... - *

- */ - public static final int CHECKED_EXCEPTION_RESPONSE = 1; - -/** - *

- * Represents ... - *

- */ - public static final int UNCHECKED_EXCEPTION_RESPONSE = 2; - -/** - *

- * Represents ... - *

- */ - public static final int REQUEST_RESPONSE_MEP = 1; - -/** - *

- * Represents ... - *

- */ - public static final int ONE_WAY_MEP = 2; - -/** - *

- * Represents ... - *

- */ - public static final int ASYNC_POLL_MEP = 3; - -/** - *

- * Represents ... - *

- */ - public static final int ASYNC_CALLBACK_MEP = 4; - - /////////////////////////////////////// - // operations - -/** - *

- * Does ... - *

- * - * @param data ... - *

- * - *

- */ - public void setData(Object[] data); -/** - *

- * Does ... - *

- * - * @return a Object[] with ... - *

- */ - public Object[] getData(); -/** - *

- * Does ... - *

- * - *

- * - * @param name ... - *

- * @param value ... - *

- */ - public void setMetaData(Object name, Object value); -/** - *

- * Does ... - *

- * - * @return a Object with ... - *

- * @param name ... - *

- */ - public Object getMetaData(Object name); -/** - *

- * Does ... - *

- * - *

- * - * @param messageExchangePattern ... - *

- */ - public void setMEP(int messageExchangePattern); -/** - *

- * Does ... - *

- * - * @return a int with ... - *

- */ - public int getMEP(); -/** - *

- * Does ... - *

- * - * @return a int with ... - *

- */ - public int getResponseType(); -/** - *

- * Does ... - *

- * - *

- * - * @param responseType ... - *

- */ - public void setResponseType(int responseType); -/** - *

- * Does ... - *

- * - * @return a Object with ... - *

- */ - public Object getResponse(); -/** - *

- * Does ... - *

- * - *

- * - * @param response ... - *

- */ - public void setResponse(Object response); -/** - *

- * Does ... - *

- * - *

- * - * @param method ... - *

- */ - public void setMethod(Method method); -/** - *

- * Does ... - *

- * - * @return a Method with ... - *

- */ - public Method getMethod(); - -} // end MessageStruct diff --git a/jdk/src/share/classes/com/sun/pept/presentation/Stub.java b/jdk/src/share/classes/com/sun/pept/presentation/Stub.java deleted file mode 100644 index 4b44dd4e276..00000000000 --- a/jdk/src/share/classes/com/sun/pept/presentation/Stub.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 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. - */ - -/** Java interface "Stub.java" generated from Poseidon for UML. - * Poseidon for UML is developed by Gentleware. - * Generated with velocity template engine. - */ -package com.sun.pept.presentation; - -import com.sun.pept.Delegate; -import java.util.*; - -/** - *

- * - * @author Dr. Harold Carr - *

- */ -public interface Stub { - - /////////////////////////////////////// - // operations - -/** - *

- * Does ... - *

- * - *

- * - * @param delegate ... - *

- */ - public void _setDelegate(Delegate delegate); -/** - *

- * Does ... - *

- * - * @return a Delegate with ... - *

- */ - public Delegate _getDelegate(); - -} // end Stub diff --git a/jdk/src/share/classes/com/sun/pept/presentation/Tie.java b/jdk/src/share/classes/com/sun/pept/presentation/Tie.java deleted file mode 100644 index ed4dae25c33..00000000000 --- a/jdk/src/share/classes/com/sun/pept/presentation/Tie.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 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. - */ - -/** Java interface "Tie.java" generated from Poseidon for UML. - * Poseidon for UML is developed by Gentleware. - * Generated with velocity template engine. - */ -package com.sun.pept.presentation; - -import com.sun.pept.ept.MessageInfo; -import java.util.*; - -/** - *

- * - * @author Dr. Harold Carr - *

- */ -public interface Tie { - - /////////////////////////////////////// - // operations - -/** - *

- * Does ... - *

- * - *

- * - * @param servant ... - *

- */ - public void _setServant(Object servant); -/** - *

- * Does ... - *

- * - * @return a Object with ... - *

- */ - public Object _getServant(); -/** - *

- * Does ... - *

- * - *

- * - * @param messageInfo ... - *

- */ - public void _invoke(MessageInfo messageInfo); - -} // end Tie diff --git a/jdk/src/share/classes/com/sun/pept/protocol/Interceptors.java b/jdk/src/share/classes/com/sun/pept/protocol/Interceptors.java deleted file mode 100644 index acfe1b927dd..00000000000 --- a/jdk/src/share/classes/com/sun/pept/protocol/Interceptors.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 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. - */ - -/** - * $Id: Interceptors.java,v 1.1 2005/05/23 22:09:18 bbissett Exp $ - */ - -/** Java interface "Interceptors.java" generated from Poseidon for UML. - * Poseidon for UML is developed by Gentleware. - * Generated with velocity template engine. - */ -package com.sun.pept.protocol; - -import com.sun.pept.ept.MessageInfo; -import java.util.*; - -/** - *

- * - * @author Dr. Harold Carr - *

- */ -public interface Interceptors { - - /////////////////////////////////////// - // operations - -/** - *

- * Does ... - *

- * - *

- * - * @param messageInfo ... - *

- */ - public void interceptMessage(MessageInfo messageInfo); - -} // end Interceptors diff --git a/jdk/src/share/classes/com/sun/pept/protocol/MessageDispatcher.java b/jdk/src/share/classes/com/sun/pept/protocol/MessageDispatcher.java deleted file mode 100644 index 83b81f27236..00000000000 --- a/jdk/src/share/classes/com/sun/pept/protocol/MessageDispatcher.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 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. - */ - -/** - * $Id: MessageDispatcher.java,v 1.1 2005/05/23 22:09:18 bbissett Exp $ - */ - -/** Java interface "MessageDispatcher.java" generated from Poseidon for UML. - * Poseidon for UML is developed by Gentleware. - * Generated with velocity template engine. - */ -package com.sun.pept.protocol; - -import com.sun.pept.ept.MessageInfo; -import java.util.*; - -/** - *

- * - * @author Dr. Harold Carr - *

- */ -public interface MessageDispatcher { - - /////////////////////////////////////// - // operations - -/** - *

- * Does ... - *

- * - *

- * - * @param messageInfo ... - *

- */ - public void send(MessageInfo messageInfo); -/** - *

- * Does ... - *

- * - *

- * - * @param messageInfo ... - *

- */ - public void receive(MessageInfo messageInfo); - -} // end MessageDispatcher diff --git a/jdk/src/share/classes/com/sun/pept/transport/Connection.java b/jdk/src/share/classes/com/sun/pept/transport/Connection.java deleted file mode 100644 index 489827fbc59..00000000000 --- a/jdk/src/share/classes/com/sun/pept/transport/Connection.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 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. - */ - -/** - * $Id: Connection.java,v 1.2 2005/07/23 04:09:58 kohlert Exp $ - */ - -/** Java interface "Connection.java" generated from Poseidon for UML. - * Poseidon for UML is developed by Gentleware. - * Generated with velocity template engine. - */ -package com.sun.pept.transport; - -import com.sun.pept.ept.EPTFactory; -import java.nio.ByteBuffer; -import java.util.*; - -/** - *

- * - * @author Dr. Harold Carr - *

- */ -public interface Connection { - - /////////////////////////////////////// - // operations - -/** - *

- * Does ... - *

- * - *

- * - * @param byteBuffer ... - *

- */ - public void write(ByteBuffer byteBuffer); -/** - *

- * Does ... - *

- * - * @return a EPTFactory with ... - *

- */ - public EPTFactory getEPTFactory(); -/** - *

- * Does ... - *

- * - * @return a int with ... - *

- * @param byteBuffer ... - *

- */ - public int read(ByteBuffer byteBuffer); -/** - *

- * Does ... - *

- * - *

- */ - public ByteBuffer readUntilEnd(); - -} // end Connection diff --git a/jdk/src/share/classes/com/sun/tools/hat/MANIFEST.mf b/jdk/src/share/classes/com/sun/tools/hat/MANIFEST.mf deleted file mode 100644 index 35334c8e34c..00000000000 --- a/jdk/src/share/classes/com/sun/tools/hat/MANIFEST.mf +++ /dev/null @@ -1,2 +0,0 @@ -Manifest-Version: 1.0 -Main-Class: com.sun.tools.hat.Main diff --git a/jdk/src/share/classes/com/sun/tools/hat/README.txt b/jdk/src/share/classes/com/sun/tools/hat/README.txt deleted file mode 100644 index 9bc0b9a3351..00000000000 --- a/jdk/src/share/classes/com/sun/tools/hat/README.txt +++ /dev/null @@ -1,20 +0,0 @@ --------------- -This HAT source originally came from the http://hat.dev.java.net site. - -The utility has been named 'jhat' in the JDK, it is basically the same tool. - -Q: Where do I make changes? In the JDK or hat.dev.java.net? - -A: It depends on whether the change is intended for the JDK jhat version only, - or expected to be given back to the java.net project. - In general, we should putback changes to the java.net project and - bringover those changes to the JDK. - -Q: I want to build just jhat.jar instead of building entire JDK. What should I do? - -A: Use ant makefile (build.xml) in the current directory. This builds just the -jhat sources and creates jhat.jar under ./build directory. - -To run the built jhat.jar, you can use the command: - - java -jar build/jhat.jar heap_dump diff --git a/jdk/src/share/classes/com/sun/tools/hat/build.xml b/jdk/src/share/classes/com/sun/tools/hat/build.xml deleted file mode 100644 index 2d7bdc800fd..00000000000 --- a/jdk/src/share/classes/com/sun/tools/hat/build.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jdk/src/share/classes/com/sun/tools/jdi/SocketAttachingConnector.java b/jdk/src/share/classes/com/sun/tools/jdi/SocketAttachingConnector.java index a8c2bed6549..2fe565bcc01 100644 --- a/jdk/src/share/classes/com/sun/tools/jdi/SocketAttachingConnector.java +++ b/jdk/src/share/classes/com/sun/tools/jdi/SocketAttachingConnector.java @@ -44,12 +44,7 @@ public class SocketAttachingConnector extends GenericAttachingConnector { public SocketAttachingConnector() { super(new SocketTransportService()); - String defaultHostName; - try { - defaultHostName = InetAddress.getLocalHost().getHostName(); - } catch (UnknownHostException e) { - defaultHostName = ""; - } + String defaultHostName = "localhost"; addStringArgument( ARG_HOST, diff --git a/jdk/src/share/classes/com/sun/tools/jdi/SocketTransportService.java b/jdk/src/share/classes/com/sun/tools/jdi/SocketTransportService.java index 5585a003110..e1c0e5a0256 100644 --- a/jdk/src/share/classes/com/sun/tools/jdi/SocketTransportService.java +++ b/jdk/src/share/classes/com/sun/tools/jdi/SocketTransportService.java @@ -198,13 +198,17 @@ public class SocketTransportService extends TransportService { String host; String portStr; if (splitIndex < 0) { - host = InetAddress.getLocalHost().getHostName(); + host = "localhost"; portStr = address; } else { host = address.substring(0, splitIndex); portStr = address.substring(splitIndex+1); } + if (host.equals("*")) { + host = InetAddress.getLocalHost().getHostName(); + } + int port; try { port = Integer.decode(portStr).intValue(); @@ -215,7 +219,6 @@ public class SocketTransportService extends TransportService { // open TCP connection to VM - InetSocketAddress sa = new InetSocketAddress(host, port); Socket s = new Socket(); try { diff --git a/jdk/src/share/classes/java/awt/AWTKeyStroke.java b/jdk/src/share/classes/java/awt/AWTKeyStroke.java index c4e07b45530..4be729b8c89 100644 --- a/jdk/src/share/classes/java/awt/AWTKeyStroke.java +++ b/jdk/src/share/classes/java/awt/AWTKeyStroke.java @@ -86,7 +86,8 @@ public class AWTKeyStroke implements Serializable { * Must be called under locked AWTKeyStro */ private static Class getAWTKeyStrokeClass() { - Class clazz = (Class)AppContext.getAppContext().get(AWTKeyStroke.class); + @SuppressWarnings("unchecked") + Class clazz = (Class)AppContext.getAppContext().get(AWTKeyStroke.class); if (clazz == null) { clazz = AWTKeyStroke.class; AppContext.getAppContext().put(AWTKeyStroke.class, AWTKeyStroke.class); @@ -182,6 +183,7 @@ public class AWTKeyStroke implements Serializable { throw new IllegalArgumentException("subclass cannot be null"); } synchronized (AWTKeyStroke.class) { + @SuppressWarnings("unchecked") Class keyStrokeClass = (Class)AppContext.getAppContext().get(AWTKeyStroke.class); if (keyStrokeClass != null && keyStrokeClass.equals(subclass)){ // Already registered @@ -192,7 +194,7 @@ public class AWTKeyStroke implements Serializable { throw new ClassCastException("subclass is not derived from AWTKeyStroke"); } - Constructor ctor = getCtor(subclass); + Constructor ctor = getCtor(subclass); String couldNotInstantiate = "subclass could not be instantiated"; @@ -227,12 +229,12 @@ public class AWTKeyStroke implements Serializable { threat as accessible flag is set only for this Constructor object, not for Class constructor. */ - private static Constructor getCtor(final Class clazz) + private static Constructor getCtor(final Class clazz) { - Constructor ctor = AccessController.doPrivileged(new PrivilegedAction() { - public Constructor run() { + Constructor ctor = AccessController.doPrivileged(new PrivilegedAction>() { + public Constructor run() { try { - Constructor ctor = clazz.getDeclaredConstructor((Class[]) null); + Constructor ctor = clazz.getDeclaredConstructor((Class[]) null); if (ctor != null) { ctor.setAccessible(true); } @@ -249,6 +251,7 @@ public class AWTKeyStroke implements Serializable { private static synchronized AWTKeyStroke getCachedStroke (char keyChar, int keyCode, int modifiers, boolean onKeyRelease) { + @SuppressWarnings("unchecked") Map cache = (Map)AppContext.getAppContext().get(APP_CONTEXT_CACHE_KEY); AWTKeyStroke cacheKey = (AWTKeyStroke)AppContext.getAppContext().get(APP_CONTEXT_KEYSTROKE_KEY); diff --git a/jdk/src/share/classes/java/awt/CardLayout.java b/jdk/src/share/classes/java/awt/CardLayout.java index 3ffb19fbee7..5e813fffbe9 100644 --- a/jdk/src/share/classes/java/awt/CardLayout.java +++ b/jdk/src/share/classes/java/awt/CardLayout.java @@ -560,6 +560,7 @@ public class CardLayout implements LayoutManager2, /** * Reads serializable fields from stream. */ + @SuppressWarnings("unchecked") private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { diff --git a/jdk/src/share/classes/java/awt/Component.java b/jdk/src/share/classes/java/awt/Component.java index a7573c09a3c..cd6ae69de1d 100644 --- a/jdk/src/share/classes/java/awt/Component.java +++ b/jdk/src/share/classes/java/awt/Component.java @@ -6184,7 +6184,7 @@ public abstract class Component implements ImageObserver, MenuContainer, /** * Parameter types of coalesceEvents(AWTEvent,AWTEVent). */ - private static final Class[] coalesceEventsParams = { + private static final Class[] coalesceEventsParams = { AWTEvent.class, AWTEvent.class }; diff --git a/jdk/src/share/classes/java/awt/GraphicsEnvironment.java b/jdk/src/share/classes/java/awt/GraphicsEnvironment.java index 66ab39a45b1..e9e9080dba6 100644 --- a/jdk/src/share/classes/java/awt/GraphicsEnvironment.java +++ b/jdk/src/share/classes/java/awt/GraphicsEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -95,18 +95,18 @@ public abstract class GraphicsEnvironment { String nm = AccessController.doPrivileged(new GetPropertyAction("java.awt.graphicsenv", null)); try { // long t0 = System.currentTimeMillis(); - Class geCls; + Class geCls; try { // First we try if the bootclassloader finds the requested // class. This way we can avoid to run in a privileged block. - geCls = (Class)Class.forName(nm); + geCls = Class.forName(nm); } catch (ClassNotFoundException ex) { // If the bootclassloader fails, we try again with the // application classloader. ClassLoader cl = ClassLoader.getSystemClassLoader(); - geCls = (Class)Class.forName(nm, true, cl); + geCls = Class.forName(nm, true, cl); } - ge = geCls.newInstance(); + ge = (GraphicsEnvironment)geCls.newInstance(); // long t1 = System.currentTimeMillis(); // System.out.println("GE creation took " + (t1-t0)+ "ms."); if (isHeadless()) { diff --git a/jdk/src/share/classes/java/awt/KeyboardFocusManager.java b/jdk/src/share/classes/java/awt/KeyboardFocusManager.java index b02bb5b0dba..8758a2b50e3 100644 --- a/jdk/src/share/classes/java/awt/KeyboardFocusManager.java +++ b/jdk/src/share/classes/java/awt/KeyboardFocusManager.java @@ -348,6 +348,7 @@ public abstract class KeyboardFocusManager * Component of those Windows that has no such array of its own explicitly * set. */ + @SuppressWarnings({"unchecked", "rawtypes"}) private Set[] defaultFocusTraversalKeys = new Set[4]; /** @@ -422,7 +423,7 @@ public abstract class KeyboardFocusManager targetSet.add(AWTKeyStroke.getAWTKeyStroke(tokens.nextToken())); } return (targetSet.isEmpty()) - ? Collections.EMPTY_SET + ? Collections.emptySet() : Collections.unmodifiableSet(targetSet); } @@ -436,7 +437,7 @@ public abstract class KeyboardFocusManager work_set.add(defaultFocusTraversalKeyStrokes[i][j]); } defaultFocusTraversalKeys[i] = (work_set.isEmpty()) - ? Collections.EMPTY_SET + ? Collections.emptySet() : Collections.unmodifiableSet(work_set); } initPeer(); @@ -1750,11 +1751,12 @@ public abstract class KeyboardFocusManager * @see #addKeyEventDispatcher * @see #removeKeyEventDispatcher */ + @SuppressWarnings("unchecked") // Cast of result of clone protected synchronized java.util.List getKeyEventDispatchers() { return (keyEventDispatchers != null) - ? (java.util.List)keyEventDispatchers.clone() + ? (java.util.List)keyEventDispatchers.clone() : null; } @@ -1841,11 +1843,12 @@ public abstract class KeyboardFocusManager * @see #addKeyEventPostProcessor * @see #removeKeyEventPostProcessor */ + @SuppressWarnings("unchecked") // Cast of result of clone protected java.util.List getKeyEventPostProcessors() { return (keyEventPostProcessors != null) - ? (java.util.List)keyEventPostProcessors.clone() + ? (java.util.List)keyEventPostProcessors.clone() : null; } @@ -1907,8 +1910,7 @@ public abstract class KeyboardFocusManager * javax.swing.JComponent.runInputVerifier() using reflection. */ static synchronized Component getMostRecentFocusOwner(Window window) { - WeakReference weakValue = - (WeakReference)mostRecentFocusOwners.get(window); + WeakReference weakValue = mostRecentFocusOwners.get(window); return weakValue == null ? null : weakValue.get(); } diff --git a/jdk/src/share/classes/java/awt/Menu.java b/jdk/src/share/classes/java/awt/Menu.java index 629371868d1..ae8e50ea7e1 100644 --- a/jdk/src/share/classes/java/awt/Menu.java +++ b/jdk/src/share/classes/java/awt/Menu.java @@ -66,7 +66,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { AWTAccessor.setMenuAccessor( new AWTAccessor.MenuAccessor() { - public Vector getItems(Menu menu) { + public Vector getItems(Menu menu) { return menu.items; } }); @@ -78,7 +78,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { * @serial * @see #countItems() */ - Vector items = new Vector<>(); + Vector items = new Vector<>(); /** * This field indicates whether the menu has the @@ -252,7 +252,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { * be called on the toolkit thread. */ final MenuItem getItemImpl(int index) { - return (MenuItem)items.elementAt(index); + return items.elementAt(index); } /** @@ -544,7 +544,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { // HeadlessException will be thrown from MenuComponent's readObject s.defaultReadObject(); for(int i = 0; i < items.size(); i++) { - MenuItem item = (MenuItem)items.elementAt(i); + MenuItem item = items.elementAt(i); item.parent = this; } } diff --git a/jdk/src/share/classes/java/awt/SystemTray.java b/jdk/src/share/classes/java/awt/SystemTray.java index 7f3a5c31893..e542dfc1712 100644 --- a/jdk/src/share/classes/java/awt/SystemTray.java +++ b/jdk/src/share/classes/java/awt/SystemTray.java @@ -259,7 +259,9 @@ public class SystemTray { Vector icons = null; synchronized (this) { oldArray = systemTray.getTrayIcons(); - icons = (Vector)AppContext.getAppContext().get(TrayIcon.class); + @SuppressWarnings("unchecked") + Vector tmp = (Vector)AppContext.getAppContext().get(TrayIcon.class); + icons = tmp; if (icons == null) { icons = new Vector(3); AppContext.getAppContext().put(TrayIcon.class, icons); @@ -304,6 +306,7 @@ public class SystemTray { TrayIcon[] oldArray = null, newArray = null; synchronized (this) { oldArray = systemTray.getTrayIcons(); + @SuppressWarnings("unchecked") Vector icons = (Vector)AppContext.getAppContext().get(TrayIcon.class); // TrayIcon with no peer is not contained in the array. if (icons == null || !icons.remove(trayIcon)) { @@ -335,6 +338,7 @@ public class SystemTray { * @see TrayIcon */ public TrayIcon[] getTrayIcons() { + @SuppressWarnings("unchecked") Vector icons = (Vector)AppContext.getAppContext().get(TrayIcon.class); if (icons != null) { return icons.toArray(new TrayIcon[icons.size()]); diff --git a/jdk/src/share/classes/java/awt/datatransfer/MimeTypeParameterList.java b/jdk/src/share/classes/java/awt/datatransfer/MimeTypeParameterList.java index f4816b65d87..3a79886c2b4 100644 --- a/jdk/src/share/classes/java/awt/datatransfer/MimeTypeParameterList.java +++ b/jdk/src/share/classes/java/awt/datatransfer/MimeTypeParameterList.java @@ -296,14 +296,14 @@ class MimeTypeParameterList implements Cloneable { /** * @return a clone of this object */ - + @SuppressWarnings("unchecked") // Cast from clone public Object clone() { MimeTypeParameterList newObj = null; try { newObj = (MimeTypeParameterList)super.clone(); } catch (CloneNotSupportedException cannotHappen) { } - newObj.parameters = (Hashtable)parameters.clone(); + newObj.parameters = (Hashtable)parameters.clone(); return newObj; } diff --git a/jdk/src/share/classes/java/awt/datatransfer/SystemFlavorMap.java b/jdk/src/share/classes/java/awt/datatransfer/SystemFlavorMap.java index bc6e1642001..fd54c9414a0 100644 --- a/jdk/src/share/classes/java/awt/datatransfer/SystemFlavorMap.java +++ b/jdk/src/share/classes/java/awt/datatransfer/SystemFlavorMap.java @@ -38,13 +38,14 @@ import java.net.URL; import java.net.MalformedURLException; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; -import java.util.WeakHashMap; import sun.awt.AppContext; import sun.awt.datatransfer.DataTransferer; @@ -101,20 +102,12 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { */ private static final String HTML_TEXT_BASE_TYPE = "text/html"; - /** - * This constant is passed to flavorToNativeLookup() to indicate that a - * a native should be synthesized, stored, and returned by encoding the - * DataFlavor's MIME type in case if the DataFlavor is not found in - * 'flavorToNative' map. - */ - private static final boolean SYNTHESIZE_IF_NOT_FOUND = true; - /** * Maps native Strings to Lists of DataFlavors (or base type Strings for * text DataFlavors). * Do not use the field directly, use getNativeToFlavor() instead. */ - private final Map> nativeToFlavor = new HashMap<>(); + private final Map> nativeToFlavor = new HashMap<>(); /** * Accessor to nativeToFlavor map. Since we use lazy initialization we must @@ -123,7 +116,7 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * * @return nativeToFlavor */ - private Map> getNativeToFlavor() { + private Map> getNativeToFlavor() { if (!isMapInitialized) { initSystemFlavorMap(); } @@ -135,7 +128,7 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * native Strings. * Do not use the field directly, use getFlavorToNative() instead. */ - private final Map> flavorToNative = new HashMap<>(); + private final Map> flavorToNative = new HashMap<>(); /** * Accessor to flavorToNative map. Since we use lazy initialization we must @@ -144,29 +137,52 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * * @return flavorToNative */ - private synchronized Map> getFlavorToNative() { + private synchronized Map> getFlavorToNative() { if (!isMapInitialized) { initSystemFlavorMap(); } return flavorToNative; } + /** + * Maps a text DataFlavor primary mime-type to the native. Used only to store + * standard mappings registered in the flavormap.properties + * Do not use this field directly, use getTextTypeToNative() instead. + */ + private Map> textTypeToNative = new HashMap<>(); + /** * Shows if the object has been initialized. */ private boolean isMapInitialized = false; /** - * Caches the result of getNativesForFlavor(). Maps DataFlavors to - * SoftReferences which reference Lists of String natives. + * An accessor to textTypeToNative map. Since we use lazy initialization we + * must use this accessor instead of direct access to the field which may not + * be initialized yet. This method will initialize the field if needed. + * + * @return textTypeToNative */ - private Map>> getNativesForFlavorCache = new HashMap<>(); + private synchronized Map> getTextTypeToNative() { + if (!isMapInitialized) { + initSystemFlavorMap(); + // From this point the map should not be modified + textTypeToNative = Collections.unmodifiableMap(textTypeToNative); + } + return textTypeToNative; + } + + /** + * Caches the result of getNativesForFlavor(). Maps DataFlavors to + * SoftReferences which reference LinkedHashSet of String natives. + */ + private final SoftCache nativesForFlavorCache = new SoftCache<>(); /** * Caches the result getFlavorsForNative(). Maps String natives to - * SoftReferences which reference Lists of DataFlavors. + * SoftReferences which reference LinkedHashSet of DataFlavors. */ - private Map>> getFlavorsForNativeCache = new HashMap<>(); + private final SoftCache flavorsForNativeCache = new SoftCache<>(); /** * Dynamic mapping generation used for text mappings should not be applied @@ -174,7 +190,7 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * explicitly specified with setFlavorsForNative() or * setNativesForFlavor(). This keeps all such keys. */ - private Set disabledMappingGenerationKeys = new HashSet(); + private Set disabledMappingGenerationKeys = new HashSet<>(); /** * Returns the default FlavorMap for this thread's ClassLoader. @@ -404,7 +420,7 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { flavor = new DataFlavor(value); } catch (Exception e) { try { - flavor = new DataFlavor(value, (String)null); + flavor = new DataFlavor(value, null); } catch (Exception ee) { ee.printStackTrace(); continue; @@ -412,11 +428,11 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { } final LinkedHashSet dfs = new LinkedHashSet<>(); - dfs.add(flavor); if ("text".equals(flavor.getPrimaryType())) { dfs.addAll(convertMimeTypeToDataFlavors(value)); + store(flavor.mimeType.getBaseType(), key, getTextTypeToNative()); } for (DataFlavor df : dfs) { @@ -505,10 +521,10 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * the appropriate Map location, but rather will be appended to a List * stored in that location. */ - private void store(H hashed, L listed, Map> map) { - List list = map.get(hashed); + private void store(H hashed, L listed, Map> map) { + LinkedHashSet list = map.get(hashed); if (list == null) { - list = new ArrayList<>(1); + list = new LinkedHashSet<>(1); map.put(hashed, list); } if (!list.contains(listed)) { @@ -522,17 +538,16 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * case, a new DataFlavor is synthesized, stored, and returned, if and * only if the specified native is encoded as a Java MIME type. */ - private List nativeToFlavorLookup(String nat) { - List flavors = getNativeToFlavor().get(nat); + private LinkedHashSet nativeToFlavorLookup(String nat) { + LinkedHashSet flavors = getNativeToFlavor().get(nat); if (nat != null && !disabledMappingGenerationKeys.contains(nat)) { DataTransferer transferer = DataTransferer.getInstance(); if (transferer != null) { - List platformFlavors = + LinkedHashSet platformFlavors = transferer.getPlatformMappingsForNative(nat); if (!platformFlavors.isEmpty()) { if (flavors != null) { - platformFlavors.removeAll(new HashSet<>(flavors)); // Prepending the platform-specific mappings ensures // that the flavors added with // addFlavorForUnencodedNative() are at the end of @@ -558,24 +573,22 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { } if (flavor != null) { - flavors = new ArrayList<>(1); + flavors = new LinkedHashSet<>(1); getNativeToFlavor().put(nat, flavors); flavors.add(flavor); - getFlavorsForNativeCache.remove(nat); - getFlavorsForNativeCache.remove(null); + flavorsForNativeCache.remove(nat); - List natives = getFlavorToNative().get(flavor); + LinkedHashSet natives = getFlavorToNative().get(flavor); if (natives == null) { - natives = new ArrayList<>(1); + natives = new LinkedHashSet<>(1); getFlavorToNative().put(flavor, natives); } natives.add(nat); - getNativesForFlavorCache.remove(flavor); - getNativesForFlavorCache.remove(null); + nativesForFlavorCache.remove(flavor); } } - return (flavors != null) ? flavors : new ArrayList<>(0); + return (flavors != null) ? flavors : new LinkedHashSet<>(0); } /** @@ -586,18 +599,18 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * encoding the DataFlavor's MIME type. Otherwise an empty List is returned * and 'flavorToNative' remains unaffected. */ - private List flavorToNativeLookup(final DataFlavor flav, - final boolean synthesize) { - List natives = getFlavorToNative().get(flav); + private LinkedHashSet flavorToNativeLookup(final DataFlavor flav, + final boolean synthesize) { + + LinkedHashSet natives = getFlavorToNative().get(flav); if (flav != null && !disabledMappingGenerationKeys.contains(flav)) { DataTransferer transferer = DataTransferer.getInstance(); if (transferer != null) { - List platformNatives = + LinkedHashSet platformNatives = transferer.getPlatformMappingsForFlavor(flav); if (!platformNatives.isEmpty()) { if (natives != null) { - platformNatives.removeAll(new HashSet<>(natives)); // Prepend the platform-specific mappings to ensure // that the natives added with // addUnencodedNativeForFlavor() are at the end of @@ -612,26 +625,25 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { if (natives == null) { if (synthesize) { String encoded = encodeDataFlavor(flav); - natives = new ArrayList<>(1); + natives = new LinkedHashSet<>(1); getFlavorToNative().put(flav, natives); natives.add(encoded); - getNativesForFlavorCache.remove(flav); - getNativesForFlavorCache.remove(null); - List flavors = getNativeToFlavor().get(encoded); + LinkedHashSet flavors = getNativeToFlavor().get(encoded); if (flavors == null) { - flavors = new ArrayList<>(1); + flavors = new LinkedHashSet<>(1); getNativeToFlavor().put(encoded, flavors); } flavors.add(flav); - getFlavorsForNativeCache.remove(encoded); - getFlavorsForNativeCache.remove(null); + + nativesForFlavorCache.remove(flav); + flavorsForNativeCache.remove(encoded); } else { - natives = new ArrayList<>(0); + natives = new LinkedHashSet<>(0); } } - return natives; + return new LinkedHashSet<>(natives); } /** @@ -659,103 +671,63 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * @see #encodeDataFlavor * @since 1.4 */ + @Override public synchronized List getNativesForFlavor(DataFlavor flav) { - List retval = null; - - // Check cache, even for null flav - SoftReference> ref = getNativesForFlavorCache.get(flav); - if (ref != null) { - retval = ref.get(); - if (retval != null) { - // Create a copy, because client code can modify the returned - // list. - return new ArrayList<>(retval); - } + LinkedHashSet retval = nativesForFlavorCache.check(flav); + if (retval != null) { + return new ArrayList<>(retval); } if (flav == null) { - retval = new ArrayList<>(getNativeToFlavor().keySet()); + retval = new LinkedHashSet<>(getNativeToFlavor().keySet()); } else if (disabledMappingGenerationKeys.contains(flav)) { // In this case we shouldn't synthesize a native for this flavor, // since its mappings were explicitly specified. - retval = flavorToNativeLookup(flav, !SYNTHESIZE_IF_NOT_FOUND); + retval = flavorToNativeLookup(flav, false); } else if (DataTransferer.isFlavorCharsetTextType(flav)) { + retval = new LinkedHashSet<>(0); // For text/* flavors, flavor-to-native mappings specified in // flavormap.properties are stored per flavor's base type. if ("text".equals(flav.getPrimaryType())) { - retval = getAllNativesForType(flav.mimeType.getBaseType()); - if (retval != null) { - // To prevent the List stored in the map from modification. - retval = new ArrayList(retval); + LinkedHashSet textTypeNatives = + getTextTypeToNative().get(flav.mimeType.getBaseType()); + if (textTypeNatives != null) { + retval.addAll(textTypeNatives); } } // Also include text/plain natives, but don't duplicate Strings - List textPlainList = getAllNativesForType(TEXT_PLAIN_BASE_TYPE); - - if (textPlainList != null && !textPlainList.isEmpty()) { - // To prevent the List stored in the map from modification. - // This also guarantees that removeAll() is supported. - textPlainList = new ArrayList<>(textPlainList); - if (retval != null && !retval.isEmpty()) { - // Use HashSet to get constant-time performance for search. - textPlainList.removeAll(new HashSet<>(retval)); - retval.addAll(textPlainList); - } else { - retval = textPlainList; - } + LinkedHashSet textTypeNatives = + getTextTypeToNative().get(TEXT_PLAIN_BASE_TYPE); + if (textTypeNatives != null) { + retval.addAll(textTypeNatives); } - if (retval == null || retval.isEmpty()) { - retval = flavorToNativeLookup(flav, SYNTHESIZE_IF_NOT_FOUND); + if (retval.isEmpty()) { + retval = flavorToNativeLookup(flav, true); } else { // In this branch it is guaranteed that natives explicitly // listed for flav's MIME type were added with // addUnencodedNativeForFlavor(), so they have lower priority. - List explicitList = - flavorToNativeLookup(flav, !SYNTHESIZE_IF_NOT_FOUND); - - // flavorToNativeLookup() never returns null. - // It can return an empty List, however. - if (!explicitList.isEmpty()) { - // To prevent the List stored in the map from modification. - // This also guarantees that removeAll() is supported. - explicitList = new ArrayList<>(explicitList); - // Use HashSet to get constant-time performance for search. - explicitList.removeAll(new HashSet<>(retval)); - retval.addAll(explicitList); - } + retval.addAll(flavorToNativeLookup(flav, false)); } } else if (DataTransferer.isFlavorNoncharsetTextType(flav)) { - retval = getAllNativesForType(flav.mimeType.getBaseType()); + retval = getTextTypeToNative().get(flav.mimeType.getBaseType()); if (retval == null || retval.isEmpty()) { - retval = flavorToNativeLookup(flav, SYNTHESIZE_IF_NOT_FOUND); + retval = flavorToNativeLookup(flav, true); } else { // In this branch it is guaranteed that natives explicitly // listed for flav's MIME type were added with // addUnencodedNativeForFlavor(), so they have lower priority. - List explicitList = - flavorToNativeLookup(flav, !SYNTHESIZE_IF_NOT_FOUND); - - // flavorToNativeLookup() never returns null. - // It can return an empty List, however. - if (!explicitList.isEmpty()) { - // To prevent the List stored in the map from modification. - // This also guarantees that add/removeAll() are supported. - retval = new ArrayList<>(retval); - explicitList = new ArrayList<>(explicitList); - // Use HashSet to get constant-time performance for search. - explicitList.removeAll(new HashSet<>(retval)); - retval.addAll(explicitList); - } + retval.addAll(flavorToNativeLookup(flav, false)); } } else { - retval = flavorToNativeLookup(flav, SYNTHESIZE_IF_NOT_FOUND); + retval = flavorToNativeLookup(flav, true); } - getNativesForFlavorCache.put(flav, new SoftReference<>(retval)); + nativesForFlavorCache.put(flav, retval); // Create a copy, because client code can modify the returned list. return new ArrayList<>(retval); } @@ -791,62 +763,38 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * @see #encodeJavaMIMEType * @since 1.4 */ + @Override public synchronized List getFlavorsForNative(String nat) { - - // Check cache, even for null nat - SoftReference> ref = getFlavorsForNativeCache.get(nat); - if (ref != null) { - List retval = ref.get(); - if (retval != null) { - return new ArrayList<>(retval); - } + LinkedHashSet returnValue = flavorsForNativeCache.check(nat); + if (returnValue != null) { + return new ArrayList<>(returnValue); + } else { + returnValue = new LinkedHashSet<>(); } - final LinkedHashSet returnValue = - new LinkedHashSet<>(); - if (nat == null) { - final List natives = getNativesForFlavor(null); - - for (String n : natives) - { - final List flavors = getFlavorsForNative(n); - - for (DataFlavor df : flavors) - { - returnValue.add(df); - } + for (String n : getNativesForFlavor(null)) { + returnValue.addAll(getFlavorsForNative(n)); } } else { - - final List flavors = nativeToFlavorLookup(nat); - + final LinkedHashSet flavors = nativeToFlavorLookup(nat); if (disabledMappingGenerationKeys.contains(nat)) { - return flavors; + return new ArrayList<>(flavors); } - final List flavorsAndBaseTypes = - nativeToFlavorLookup(nat); + final LinkedHashSet flavorsWithSynthesized = + nativeToFlavorLookup(nat); - for (DataFlavor df : flavorsAndBaseTypes) { + for (DataFlavor df : flavorsWithSynthesized) { returnValue.add(df); if ("text".equals(df.getPrimaryType())) { - try { - returnValue.addAll( - convertMimeTypeToDataFlavors( - new MimeType(df.getMimeType() - ).getBaseType())); - } catch (MimeTypeParseException e) { - e.printStackTrace(); - } + String baseType = df.mimeType.getBaseType(); + returnValue.addAll(convertMimeTypeToDataFlavors(baseType)); } } - } - - final List arrayList = new ArrayList<>(returnValue); - getFlavorsForNativeCache.put(nat, new SoftReference<>(arrayList)); - return new ArrayList<>(arrayList); + flavorsForNativeCache.put(nat, returnValue); + return new ArrayList<>(returnValue); } private static Set convertMimeTypeToDataFlavors( @@ -862,7 +810,6 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { } catch (MimeTypeParseException mtpe) { // Cannot happen, since we checked all mappings // on load from flavormap.properties. - assert(false); } if (DataTransferer.doesSubtypeSupportCharset(subType, null)) { @@ -941,10 +888,10 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { } private static final String [] htmlDocumntTypes = - new String [] {"all", "selection", "fragment"}; + new String [] {"all", "selection", "fragment"}; - private static LinkedHashSet handleHtmlMimeTypes( - String baseType, String mimeType) { + private static LinkedHashSet handleHtmlMimeTypes(String baseType, + String mimeType) { LinkedHashSet returnValues = new LinkedHashSet<>(); @@ -981,14 +928,14 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * @see #getNativesForFlavor * @see #encodeDataFlavor */ - public synchronized Map - getNativesForFlavors(DataFlavor[] flavors) + @Override + public synchronized Map getNativesForFlavors(DataFlavor[] flavors) { // Use getNativesForFlavor to generate extra natives for text flavors // and stringFlavor if (flavors == null) { - List flavor_list = getFlavorsForNative(null); + List flavor_list = getFlavorsForNative(null); flavors = new DataFlavor[flavor_list.size()]; flavor_list.toArray(flavors); } @@ -1027,15 +974,14 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { * @see #getFlavorsForNative * @see #encodeJavaMIMEType */ - public synchronized Map - getFlavorsForNatives(String[] natives) + @Override + public synchronized Map getFlavorsForNatives(String[] natives) { // Use getFlavorsForNative to generate extra flavors for text natives - if (natives == null) { - List native_list = getNativesForFlavor(null); - natives = new String[native_list.size()]; - native_list.toArray(natives); + List nativesList = getNativesForFlavor(null); + natives = new String[nativesList.size()]; + nativesList.toArray(natives); } Map retval = new HashMap<>(natives.length, 1.0f); @@ -1044,7 +990,6 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { DataFlavor flav = (flavors.isEmpty())? null : flavors.get(0); retval.put(aNative, flav); } - return retval; } @@ -1070,20 +1015,16 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { */ public synchronized void addUnencodedNativeForFlavor(DataFlavor flav, String nat) { - if (flav == null || nat == null) { - throw new NullPointerException("null arguments not permitted"); - } + Objects.requireNonNull(nat, "Null native not permitted"); + Objects.requireNonNull(flav, "Null flavor not permitted"); - List natives = getFlavorToNative().get(flav); + LinkedHashSet natives = getFlavorToNative().get(flav); if (natives == null) { - natives = new ArrayList<>(1); + natives = new LinkedHashSet<>(1); getFlavorToNative().put(flav, natives); - } else if (natives.contains(nat)) { - return; } natives.add(nat); - getNativesForFlavorCache.remove(flav); - getNativesForFlavorCache.remove(null); + nativesForFlavorCache.remove(flav); } /** @@ -1116,18 +1057,15 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { */ public synchronized void setNativesForFlavor(DataFlavor flav, String[] natives) { - if (flav == null || natives == null) { - throw new NullPointerException("null arguments not permitted"); - } + Objects.requireNonNull(natives, "Null natives not permitted"); + Objects.requireNonNull(flav, "Null flavors not permitted"); getFlavorToNative().remove(flav); for (String aNative : natives) { addUnencodedNativeForFlavor(flav, aNative); } disabledMappingGenerationKeys.add(flav); - // Clear the cache to handle the case of empty natives. - getNativesForFlavorCache.remove(flav); - getNativesForFlavorCache.remove(null); + nativesForFlavorCache.remove(flav); } /** @@ -1150,20 +1088,16 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { */ public synchronized void addFlavorForUnencodedNative(String nat, DataFlavor flav) { - if (nat == null || flav == null) { - throw new NullPointerException("null arguments not permitted"); - } + Objects.requireNonNull(nat, "Null native not permitted"); + Objects.requireNonNull(flav, "Null flavor not permitted"); - List flavors = getNativeToFlavor().get(nat); + LinkedHashSet flavors = getNativeToFlavor().get(nat); if (flavors == null) { - flavors = new ArrayList<>(1); + flavors = new LinkedHashSet<>(1); getNativeToFlavor().put(nat, flavors); - } else if (flavors.contains(flav)) { - return; } flavors.add(flav); - getFlavorsForNativeCache.remove(nat); - getFlavorsForNativeCache.remove(null); + flavorsForNativeCache.remove(nat); } /** @@ -1195,18 +1129,15 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { */ public synchronized void setFlavorsForNative(String nat, DataFlavor[] flavors) { - if (nat == null || flavors == null) { - throw new NullPointerException("null arguments not permitted"); - } + Objects.requireNonNull(nat, "Null native not permitted"); + Objects.requireNonNull(flavors, "Null flavors not permitted"); getNativeToFlavor().remove(nat); for (DataFlavor flavor : flavors) { addFlavorForUnencodedNative(nat, flavor); } disabledMappingGenerationKeys.add(nat); - // Clear the cache to handle the case of empty flavors. - getFlavorsForNativeCache.remove(nat); - getFlavorsForNativeCache.remove(null); + flavorsForNativeCache.remove(nat); } /** @@ -1307,17 +1238,29 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { : null; } - private List getAllNativesForType(String type) { - Set retval = null; - for (DataFlavor dataFlavor : convertMimeTypeToDataFlavors(type)) { - List natives = getFlavorToNative().get(dataFlavor); - if (natives != null && !natives.isEmpty()) { - if (retval == null) { - retval = new LinkedHashSet<>(); - } - retval.addAll(natives); + private static final class SoftCache { + Map>> cache; + + public void put(K key, LinkedHashSet value) { + if (cache == null) { + cache = new HashMap<>(1); } + cache.put(key, new SoftReference<>(value)); + } + + public void remove(K key) { + if (cache == null) return; + cache.remove(null); + cache.remove(key); + } + + public LinkedHashSet check(K key) { + if (cache == null) return null; + SoftReference> ref = cache.get(key); + if (ref != null) { + return ref.get(); + } + return null; } - return retval == null ? null : new ArrayList<>(retval); } } diff --git a/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java b/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java index e8827f44358..3dff336a794 100644 --- a/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java +++ b/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -357,6 +357,7 @@ public class DragGestureEvent extends EventObject { action = newAction; // Pre-1.4 support. 'events' was previously non-transient + @SuppressWarnings("rawtypes") List newEvents; try { newEvents = (List)f.get("events", null); diff --git a/jdk/src/share/classes/java/awt/geom/Area.java b/jdk/src/share/classes/java/awt/geom/Area.java index 507f212b4ea..ae5ab2f683b 100644 --- a/jdk/src/share/classes/java/awt/geom/Area.java +++ b/jdk/src/share/classes/java/awt/geom/Area.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -97,9 +97,9 @@ import sun.awt.geom.AreaOp; * @since 1.2 */ public class Area implements Shape, Cloneable { - private static Vector EmptyCurves = new Vector(); + private static Vector EmptyCurves = new Vector<>(); - private Vector curves; + private Vector curves; /** * Default constructor which creates an empty area. @@ -127,8 +127,8 @@ public class Area implements Shape, Cloneable { } } - private static Vector pathToCurves(PathIterator pi) { - Vector curves = new Vector(); + private static Vector pathToCurves(PathIterator pi) { + Vector curves = new Vector<>(); int windingRule = pi.getWindingRule(); // coords array is big enough for holding: // coordinates returned from currentSegment (6) @@ -334,7 +334,7 @@ public class Area implements Shape, Cloneable { * @since 1.2 */ public void reset() { - curves = new Vector(); + curves = new Vector<>(); invalidateBounds(); } @@ -357,9 +357,9 @@ public class Area implements Shape, Cloneable { * @since 1.2 */ public boolean isPolygonal() { - Enumeration enum_ = curves.elements(); + Enumeration enum_ = curves.elements(); while (enum_.hasMoreElements()) { - if (((Curve) enum_.nextElement()).getOrder() > 1) { + if (enum_.nextElement().getOrder() > 1) { return false; } } @@ -381,8 +381,8 @@ public class Area implements Shape, Cloneable { if (size > 3) { return false; } - Curve c1 = (Curve) curves.get(1); - Curve c2 = (Curve) curves.get(2); + Curve c1 = curves.get(1); + Curve c2 = curves.get(2); if (c1.getOrder() != 1 || c2.getOrder() != 1) { return false; } @@ -411,10 +411,10 @@ public class Area implements Shape, Cloneable { if (curves.size() < 3) { return true; } - Enumeration enum_ = curves.elements(); + Enumeration enum_ = curves.elements(); enum_.nextElement(); // First Order0 "moveto" while (enum_.hasMoreElements()) { - if (((Curve) enum_.nextElement()).getOrder() == 0) { + if (enum_.nextElement().getOrder() == 0) { return false; } } @@ -431,11 +431,11 @@ public class Area implements Shape, Cloneable { } Rectangle2D r = new Rectangle2D.Double(); if (curves.size() > 0) { - Curve c = (Curve) curves.get(0); + Curve c = curves.get(0); // First point is always an order 0 curve (moveto) r.setRect(c.getX0(), c.getY0(), 0, 0); for (int i = 1; i < curves.size(); i++) { - ((Curve) curves.get(i)).enlarge(r); + curves.get(i).enlarge(r); } } return (cachedBounds = r); @@ -507,7 +507,7 @@ public class Area implements Shape, Cloneable { if (other == null) { return false; } - Vector c = new AreaOp.XorOp().calculate(this.curves, other.curves); + Vector c = new AreaOp.XorOp().calculate(this.curves, other.curves); return c.isEmpty(); } @@ -555,10 +555,10 @@ public class Area implements Shape, Cloneable { if (!getCachedBounds().contains(x, y)) { return false; } - Enumeration enum_ = curves.elements(); + Enumeration enum_ = curves.elements(); int crossings = 0; while (enum_.hasMoreElements()) { - Curve c = (Curve) enum_.nextElement(); + Curve c = enum_.nextElement(); crossings += c.crossingsFor(x, y); } return ((crossings & 1) == 1); @@ -658,16 +658,16 @@ public class Area implements Shape, Cloneable { class AreaIterator implements PathIterator { private AffineTransform transform; - private Vector curves; + private Vector curves; private int index; private Curve prevcurve; private Curve thiscurve; - public AreaIterator(Vector curves, AffineTransform at) { + public AreaIterator(Vector curves, AffineTransform at) { this.curves = curves; this.transform = at; if (curves.size() >= 1) { - thiscurve = (Curve) curves.get(0); + thiscurve = curves.get(0); } } @@ -689,7 +689,7 @@ class AreaIterator implements PathIterator { prevcurve = thiscurve; index++; if (index < curves.size()) { - thiscurve = (Curve) curves.get(index); + thiscurve = curves.get(index); if (thiscurve.getOrder() != 0 && prevcurve.getX1() == thiscurve.getX0() && prevcurve.getY1() == thiscurve.getY0()) diff --git a/jdk/src/share/classes/java/awt/image/BufferedImage.java b/jdk/src/share/classes/java/awt/image/BufferedImage.java index bb272aacf69..0c819349135 100644 --- a/jdk/src/share/classes/java/awt/image/BufferedImage.java +++ b/jdk/src/share/classes/java/awt/image/BufferedImage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -76,7 +76,7 @@ public class BufferedImage extends java.awt.Image ColorModel colorModel; WritableRaster raster; OffScreenImageSource osis; - Hashtable properties; + Hashtable properties; boolean isAlphaPremultiplied;// If true, alpha has been premultiplied in // color channels @@ -1106,7 +1106,7 @@ public class BufferedImage extends java.awt.Image public ImageProducer getSource() { if (osis == null) { if (properties == null) { - properties = new Hashtable(); + properties = new Hashtable<>(); } osis = new OffScreenImageSource(this, properties); } diff --git a/jdk/src/share/classes/java/awt/image/CropImageFilter.java b/jdk/src/share/classes/java/awt/image/CropImageFilter.java index 4d75c9e0427..a1d241d33ed 100644 --- a/jdk/src/share/classes/java/awt/image/CropImageFilter.java +++ b/jdk/src/share/classes/java/awt/image/CropImageFilter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 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 @@ -79,6 +79,7 @@ public class CropImageFilter extends ImageFilter { * with the filtering operation. */ public void setProperties(Hashtable props) { + @SuppressWarnings("unchecked") Hashtable p = (Hashtable)props.clone(); p.put("croprect", new Rectangle(cropX, cropY, cropW, cropH)); super.setProperties(p); diff --git a/jdk/src/share/classes/java/awt/image/FilteredImageSource.java b/jdk/src/share/classes/java/awt/image/FilteredImageSource.java index 2f58c096474..a7013159008 100644 --- a/jdk/src/share/classes/java/awt/image/FilteredImageSource.java +++ b/jdk/src/share/classes/java/awt/image/FilteredImageSource.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 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 @@ -68,7 +68,7 @@ public class FilteredImageSource implements ImageProducer { filter = imgf; } - private Hashtable proxies; + private Hashtable proxies; /** * Adds the specified ImageConsumer @@ -94,7 +94,7 @@ public class FilteredImageSource implements ImageProducer { */ public synchronized void addConsumer(ImageConsumer ic) { if (proxies == null) { - proxies = new Hashtable(); + proxies = new Hashtable<>(); } if (!proxies.containsKey(ic)) { ImageFilter imgf = filter.getFilterInstance(ic); @@ -137,7 +137,7 @@ public class FilteredImageSource implements ImageProducer { */ public synchronized void removeConsumer(ImageConsumer ic) { if (proxies != null) { - ImageFilter imgf = (ImageFilter) proxies.get(ic); + ImageFilter imgf = proxies.get(ic); if (imgf != null) { src.removeConsumer(imgf); proxies.remove(ic); @@ -173,9 +173,9 @@ public class FilteredImageSource implements ImageProducer { */ public void startProduction(ImageConsumer ic) { if (proxies == null) { - proxies = new Hashtable(); + proxies = new Hashtable<>(); } - ImageFilter imgf = (ImageFilter) proxies.get(ic); + ImageFilter imgf = proxies.get(ic); if (imgf == null) { imgf = filter.getFilterInstance(ic); proxies.put(ic, imgf); @@ -200,7 +200,7 @@ public class FilteredImageSource implements ImageProducer { */ public void requestTopDownLeftRightResend(ImageConsumer ic) { if (proxies != null) { - ImageFilter imgf = (ImageFilter) proxies.get(ic); + ImageFilter imgf = proxies.get(ic); if (imgf != null) { imgf.resendTopDownLeftRight(src); } diff --git a/jdk/src/share/classes/java/awt/image/ImageFilter.java b/jdk/src/share/classes/java/awt/image/ImageFilter.java index 0b64d726b8e..33198346e03 100644 --- a/jdk/src/share/classes/java/awt/image/ImageFilter.java +++ b/jdk/src/share/classes/java/awt/image/ImageFilter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 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 @@ -104,6 +104,7 @@ public class ImageFilter implements ImageConsumer, Cloneable { * @exception NullPointerException if props is null */ public void setProperties(Hashtable props) { + @SuppressWarnings("unchecked") Hashtable p = (Hashtable)props.clone(); Object o = p.get("filters"); if (o == null) { diff --git a/jdk/src/share/classes/java/awt/image/MemoryImageSource.java b/jdk/src/share/classes/java/awt/image/MemoryImageSource.java index 7046f5e4667..501714fda1f 100644 --- a/jdk/src/share/classes/java/awt/image/MemoryImageSource.java +++ b/jdk/src/share/classes/java/awt/image/MemoryImageSource.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 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 @@ -111,8 +111,8 @@ public class MemoryImageSource implements ImageProducer { Object pixels; int pixeloffset; int pixelscan; - Hashtable properties; - Vector theConsumers = new Vector(); + Hashtable properties; + Vector theConsumers = new Vector<>(); boolean animating; boolean fullbuffers; @@ -197,7 +197,7 @@ public class MemoryImageSource implements ImageProducer { } private void initialize(int w, int h, ColorModel cm, - Object pix, int off, int scan, Hashtable props) { + Object pix, int off, int scan, Hashtable props) { width = w; height = h; model = cm; @@ -205,7 +205,7 @@ public class MemoryImageSource implements ImageProducer { pixeloffset = off; pixelscan = scan; if (props == null) { - props = new Hashtable(); + props = new Hashtable<>(); } properties = props; } @@ -343,9 +343,9 @@ public class MemoryImageSource implements ImageProducer { public synchronized void setAnimated(boolean animated) { this.animating = animated; if (!animating) { - Enumeration enum_ = theConsumers.elements(); + Enumeration enum_ = theConsumers.elements(); while (enum_.hasMoreElements()) { - ImageConsumer ic = (ImageConsumer) enum_.nextElement(); + ImageConsumer ic = enum_.nextElement(); ic.imageComplete(ImageConsumer.STATICIMAGEDONE); if (isConsumer(ic)) { ic.imageComplete(ImageConsumer.IMAGEERROR); @@ -376,9 +376,9 @@ public class MemoryImageSource implements ImageProducer { } this.fullbuffers = fullbuffers; if (animating) { - Enumeration enum_ = theConsumers.elements(); + Enumeration enum_ = theConsumers.elements(); while (enum_.hasMoreElements()) { - ImageConsumer ic = (ImageConsumer) enum_.nextElement(); + ImageConsumer ic = enum_.nextElement(); ic.setHints(fullbuffers ? (ImageConsumer.TOPDOWNLEFTRIGHT | ImageConsumer.COMPLETESCANLINES) @@ -474,9 +474,9 @@ public class MemoryImageSource implements ImageProducer { if ((w <= 0 || h <= 0) && !framenotify) { return; } - Enumeration enum_ = theConsumers.elements(); + Enumeration enum_ = theConsumers.elements(); while (enum_.hasMoreElements()) { - ImageConsumer ic = (ImageConsumer) enum_.nextElement(); + ImageConsumer ic = enum_.nextElement(); if (w > 0 && h > 0) { sendPixels(ic, x, y, w, h); } diff --git a/jdk/src/share/classes/java/awt/image/ReplicateScaleFilter.java b/jdk/src/share/classes/java/awt/image/ReplicateScaleFilter.java index 04a6fdfe52a..7330439f2c5 100644 --- a/jdk/src/share/classes/java/awt/image/ReplicateScaleFilter.java +++ b/jdk/src/share/classes/java/awt/image/ReplicateScaleFilter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -121,6 +121,7 @@ public class ReplicateScaleFilter extends ImageFilter { * with the filtering operation. */ public void setProperties(Hashtable props) { + @SuppressWarnings("unchecked") Hashtable p = (Hashtable)props.clone(); String key = "rescale"; String val = destWidth + "x" + destHeight; diff --git a/jdk/src/share/classes/java/awt/image/renderable/ParameterBlock.java b/jdk/src/share/classes/java/awt/image/renderable/ParameterBlock.java index ca12bfc4c4b..bf14e8ce2d3 100644 --- a/jdk/src/share/classes/java/awt/image/renderable/ParameterBlock.java +++ b/jdk/src/share/classes/java/awt/image/renderable/ParameterBlock.java @@ -153,6 +153,7 @@ public class ParameterBlock implements Cloneable, Serializable { * * @return an Object clone of the ParameterBlock. */ + @SuppressWarnings("unchecked") // casts from clone public Object clone() { ParameterBlock theClone; @@ -164,10 +165,10 @@ public class ParameterBlock implements Cloneable, Serializable { } if (sources != null) { - theClone.setSources((Vector)sources.clone()); + theClone.setSources((Vector)sources.clone()); } if (parameters != null) { - theClone.setParameters((Vector)parameters.clone()); + theClone.setParameters((Vector)parameters.clone()); } return (Object) theClone; } @@ -280,7 +281,7 @@ public class ParameterBlock implements Cloneable, Serializable { /** Clears the list of source images. */ public void removeSources() { - sources = new Vector(); + sources = new Vector<>(); } /** @@ -313,7 +314,7 @@ public class ParameterBlock implements Cloneable, Serializable { /** Clears the list of parameters. */ public void removeParameters() { - parameters = new Vector(); + parameters = new Vector<>(); } /** @@ -696,9 +697,9 @@ public class ParameterBlock implements Cloneable, Serializable { * of the parameters. * @return an array of Class objects. */ - public Class [] getParamClasses() { + public Class[] getParamClasses() { int numParams = getNumParameters(); - Class [] classes = new Class[numParams]; + Class[] classes = new Class[numParams]; int i; for (i = 0; i < numParams; i++) { diff --git a/jdk/src/share/classes/java/awt/image/renderable/RenderableImageOp.java b/jdk/src/share/classes/java/awt/image/renderable/RenderableImageOp.java index 6c51f65a8bf..9d5aaa954a8 100644 --- a/jdk/src/share/classes/java/awt/image/renderable/RenderableImageOp.java +++ b/jdk/src/share/classes/java/awt/image/renderable/RenderableImageOp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -87,11 +87,11 @@ public class RenderableImageOp implements RenderableImage { return getRenderableSources(); } - private Vector getRenderableSources() { - Vector sources = null; + private Vector getRenderableSources() { + Vector sources = null; if (paramBlock.getNumSources() > 0) { - sources = new Vector(); + sources = new Vector<>(); int i = 0; while (i < paramBlock.getNumSources()) { Object o = paramBlock.getSource(i); @@ -314,19 +314,19 @@ public class RenderableImageOp implements RenderableImage { // contains RenderableImage sources, they will be replaced by // RenderedImages. ParameterBlock renderedParamBlock = (ParameterBlock)paramBlock.clone(); - Vector sources = getRenderableSources(); + Vector sources = getRenderableSources(); try { // This assumes that if there is no renderable source, that there // is a rendered source in paramBlock if (sources != null) { - Vector renderedSources = new Vector(); + Vector renderedSources = new Vector<>(); for (int i = 0; i < sources.size(); i++) { rcOut = myCRIF.mapRenderContext(i, renderContext, paramBlock, this); RenderedImage rdrdImage = - ((RenderableImage)sources.elementAt(i)).createRendering(rcOut); + ((RenderableImage)sources.elementAt(i)).createRendering(rcOut); if (rdrdImage == null) { return null; } diff --git a/jdk/src/share/classes/java/awt/image/renderable/RenderableImageProducer.java b/jdk/src/share/classes/java/awt/image/renderable/RenderableImageProducer.java index c5e357a28c2..206869ae1bf 100644 --- a/jdk/src/share/classes/java/awt/image/renderable/RenderableImageProducer.java +++ b/jdk/src/share/classes/java/awt/image/renderable/RenderableImageProducer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -68,7 +68,7 @@ public class RenderableImageProducer implements ImageProducer, Runnable { RenderContext rc; /** A Vector of image consumers. */ - Vector ics = new Vector(); + Vector ics = new Vector<>(); /** * Constructs a new RenderableImageProducer from a RenderableImage @@ -177,12 +177,12 @@ public class RenderableImageProducer implements ImageProducer, Runnable { int width = raster.getWidth(); int height = raster.getHeight(); - Enumeration icList; + Enumeration icList; ImageConsumer ic; // Set up the ImageConsumers icList = ics.elements(); while (icList.hasMoreElements()) { - ic = (ImageConsumer)icList.nextElement(); + ic = icList.nextElement(); ic.setDimensions(width,height); ic.setHints(ImageConsumer.TOPDOWNLEFTRIGHT | ImageConsumer.COMPLETESCANLINES | @@ -204,7 +204,7 @@ public class RenderableImageProducer implements ImageProducer, Runnable { // Now send the scanline to the Consumers icList = ics.elements(); while (icList.hasMoreElements()) { - ic = (ImageConsumer)icList.nextElement(); + ic = icList.nextElement(); ic.setPixels(0, j, width, 1, colorModel, pix, 0, width); } } @@ -212,7 +212,7 @@ public class RenderableImageProducer implements ImageProducer, Runnable { // Now tell the consumers we're done. icList = ics.elements(); while (icList.hasMoreElements()) { - ic = (ImageConsumer)icList.nextElement(); + ic = icList.nextElement(); ic.imageComplete(ImageConsumer.STATICIMAGEDONE); } } diff --git a/jdk/src/share/classes/java/awt/print/Book.java b/jdk/src/share/classes/java/awt/print/Book.java index 672b842e8e7..eaab083789c 100644 --- a/jdk/src/share/classes/java/awt/print/Book.java +++ b/jdk/src/share/classes/java/awt/print/Book.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -47,7 +47,7 @@ public class Book implements Pageable { /** * The set of pages that make up the Book. */ - private Vector mPages; + private Vector mPages; /* Instance Methods */ @@ -55,7 +55,7 @@ public class Book implements Pageable { * Creates a new, empty Book. */ public Book() { - mPages = new Vector(); + mPages = new Vector<>(); } /** @@ -167,7 +167,7 @@ public class Book implements Pageable { private BookPage getPage(int pageIndex) throws ArrayIndexOutOfBoundsException { - return (BookPage) mPages.elementAt(pageIndex); + return mPages.elementAt(pageIndex); } /** diff --git a/jdk/src/share/classes/java/awt/print/PrinterJob.java b/jdk/src/share/classes/java/awt/print/PrinterJob.java index b9b0d134d64..0c80d1490d4 100644 --- a/jdk/src/share/classes/java/awt/print/PrinterJob.java +++ b/jdk/src/share/classes/java/awt/print/PrinterJob.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -74,9 +74,9 @@ public abstract class PrinterJob { if (security != null) { security.checkPrintJobAccess(); } - return (PrinterJob) java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + return java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public PrinterJob run() { String nm = System.getProperty("java.awt.printerjob", null); try { return (PrinterJob)Class.forName(nm).newInstance(); diff --git a/jdk/src/share/classes/java/beans/MethodDescriptor.java b/jdk/src/share/classes/java/beans/MethodDescriptor.java index da2f754c97e..1e169046746 100644 --- a/jdk/src/share/classes/java/beans/MethodDescriptor.java +++ b/jdk/src/share/classes/java/beans/MethodDescriptor.java @@ -162,6 +162,16 @@ public class MethodDescriptor extends FeatureDescriptor { : null; } + private static Method resolve(Method oldMethod, Method newMethod) { + if (oldMethod == null) { + return newMethod; + } + if (newMethod == null) { + return oldMethod; + } + return !oldMethod.isSynthetic() && newMethod.isSynthetic() ? oldMethod : newMethod; + } + /* * Package-private constructor * Merge two method descriptors. Where they conflict, give the @@ -173,8 +183,7 @@ public class MethodDescriptor extends FeatureDescriptor { MethodDescriptor(MethodDescriptor x, MethodDescriptor y) { super(x, y); - Method method = y.methodRef.get(); - this.methodRef.set(null != method ? method : x.methodRef.get()); + this.methodRef.set(resolve(x.methodRef.get(), y.methodRef.get())); params = x.params; if (y.params != null) { params = y.params; diff --git a/jdk/src/share/classes/java/lang/ClassValue.java b/jdk/src/share/classes/java/lang/ClassValue.java index e58634b155d..4fc33d355bd 100644 --- a/jdk/src/share/classes/java/lang/ClassValue.java +++ b/jdk/src/share/classes/java/lang/ClassValue.java @@ -25,7 +25,6 @@ package java.lang; -import java.lang.ClassValue.ClassValueMap; import java.util.WeakHashMap; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicInteger; @@ -375,10 +374,10 @@ public abstract class ClassValue { synchronized (CRITICAL_SECTION) { // private object to avoid deadlocks // happens about once per type if ((map = type.classValueMap) == null) - type.classValueMap = map = new ClassValueMap(type); - } - return map; + type.classValueMap = map = new ClassValueMap(); } + return map; + } static Entry makeEntry(Version explicitVersion, T value) { // Note that explicitVersion might be different from this.version. @@ -398,12 +397,11 @@ public abstract class ClassValue { // The following class could also be top level and non-public: - /** A backing map for all ClassValues, relative a single given type. + /** A backing map for all ClassValues. * Gives a fully serialized "true state" for each pair (ClassValue cv, Class type). * Also manages an unserialized fast-path cache. */ static class ClassValueMap extends WeakHashMap> { - private final Class type; private Entry[] cacheArray; private int cacheLoad, cacheLoadLimit; @@ -413,11 +411,10 @@ public abstract class ClassValue { */ private static final int INITIAL_ENTRIES = 32; - /** Build a backing map for ClassValues, relative the given type. + /** Build a backing map for ClassValues. * Also, create an empty cache array and install it on the class. */ - ClassValueMap(Class type) { - this.type = type; + ClassValueMap() { sizeCache(INITIAL_ENTRIES); } diff --git a/jdk/src/share/classes/java/lang/Process.java b/jdk/src/share/classes/java/lang/Process.java index 4e945382465..9d9bc3316ba 100644 --- a/jdk/src/share/classes/java/lang/Process.java +++ b/jdk/src/share/classes/java/lang/Process.java @@ -262,4 +262,18 @@ public abstract class Process { return true; } } + + /** + * Returns the native process id of the subprocess. + * The native process id is an identification number that the operating + * system assigns to the process. + * + * @return the native process id of the subprocess + * @throws UnsupportedOperationException if the Process implementation + * does not support this operation + * @since 1.9 + */ + public long getPid() { + throw new UnsupportedOperationException(); + } } diff --git a/jdk/src/share/classes/java/lang/invoke/BoundMethodHandle.java b/jdk/src/share/classes/java/lang/invoke/BoundMethodHandle.java index ea75ddfef6f..f860c77e5e2 100644 --- a/jdk/src/share/classes/java/lang/invoke/BoundMethodHandle.java +++ b/jdk/src/share/classes/java/lang/invoke/BoundMethodHandle.java @@ -26,11 +26,10 @@ package java.lang.invoke; import static jdk.internal.org.objectweb.asm.Opcodes.*; -import static java.lang.invoke.LambdaForm.basicTypes; -import static java.lang.invoke.MethodHandleNatives.Constants.REF_invokeStatic; +import static java.lang.invoke.LambdaForm.*; +import static java.lang.invoke.LambdaForm.BasicType.*; import static java.lang.invoke.MethodHandleStatics.*; -import java.lang.invoke.LambdaForm.Name; import java.lang.invoke.LambdaForm.NamedFunction; import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.Field; @@ -61,22 +60,22 @@ import jdk.internal.org.objectweb.asm.Type; // BMH API and internals // - static MethodHandle bindSingle(MethodType type, LambdaForm form, char xtype, Object x) { + static MethodHandle bindSingle(MethodType type, LambdaForm form, BasicType xtype, Object x) { // for some type signatures, there exist pre-defined concrete BMH classes try { switch (xtype) { - case 'L': + case L_TYPE: if (true) return bindSingle(type, form, x); // Use known fast path. - return (BoundMethodHandle) SpeciesData.EMPTY.extendWithType('L').constructor[0].invokeBasic(type, form, x); - case 'I': - return (BoundMethodHandle) SpeciesData.EMPTY.extendWithType('I').constructor[0].invokeBasic(type, form, ValueConversions.widenSubword(x)); - case 'J': - return (BoundMethodHandle) SpeciesData.EMPTY.extendWithType('J').constructor[0].invokeBasic(type, form, (long) x); - case 'F': - return (BoundMethodHandle) SpeciesData.EMPTY.extendWithType('F').constructor[0].invokeBasic(type, form, (float) x); - case 'D': - return (BoundMethodHandle) SpeciesData.EMPTY.extendWithType('D').constructor[0].invokeBasic(type, form, (double) x); - default : throw new InternalError("unexpected xtype: " + xtype); + return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(L_TYPE).constructor[0].invokeBasic(type, form, x); + case I_TYPE: + return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(I_TYPE).constructor[0].invokeBasic(type, form, ValueConversions.widenSubword(x)); + case J_TYPE: + return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(J_TYPE).constructor[0].invokeBasic(type, form, (long) x); + case F_TYPE: + return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(F_TYPE).constructor[0].invokeBasic(type, form, (float) x); + case D_TYPE: + return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(D_TYPE).constructor[0].invokeBasic(type, form, (double) x); + default : throw newInternalError("unexpected xtype: " + xtype); } } catch (Throwable t) { throw newInternalError(t); @@ -87,23 +86,23 @@ import jdk.internal.org.objectweb.asm.Type; return new Species_L(type, form, x); } - MethodHandle cloneExtend(MethodType type, LambdaForm form, char xtype, Object x) { + MethodHandle cloneExtend(MethodType type, LambdaForm form, BasicType xtype, Object x) { try { switch (xtype) { - case 'L': return cloneExtendL(type, form, x); - case 'I': return cloneExtendI(type, form, ValueConversions.widenSubword(x)); - case 'J': return cloneExtendJ(type, form, (long) x); - case 'F': return cloneExtendF(type, form, (float) x); - case 'D': return cloneExtendD(type, form, (double) x); + case L_TYPE: return copyWithExtendL(type, form, x); + case I_TYPE: return copyWithExtendI(type, form, ValueConversions.widenSubword(x)); + case J_TYPE: return copyWithExtendJ(type, form, (long) x); + case F_TYPE: return copyWithExtendF(type, form, (float) x); + case D_TYPE: return copyWithExtendD(type, form, (double) x); } } catch (Throwable t) { throw newInternalError(t); } - throw new InternalError("unexpected type: " + xtype); + throw newInternalError("unexpected type: " + xtype); } @Override - MethodHandle bindArgument(int pos, char basicType, Object value) { + MethodHandle bindArgument(int pos, BasicType basicType, Object value) { MethodType type = type().dropParameterTypes(pos, pos+1); LambdaForm form = internalForm().bind(1+pos, speciesData()); return cloneExtend(type, form, basicType, value); @@ -111,9 +110,9 @@ import jdk.internal.org.objectweb.asm.Type; @Override MethodHandle dropArguments(MethodType srcType, int pos, int drops) { - LambdaForm form = internalForm().addArguments(pos, srcType.parameterList().subList(pos, pos+drops)); + LambdaForm form = internalForm().addArguments(pos, srcType.parameterList().subList(pos, pos + drops)); try { - return clone(srcType, form); + return copyWith(srcType, form); } catch (Throwable t) { throw newInternalError(t); } @@ -122,26 +121,23 @@ import jdk.internal.org.objectweb.asm.Type; @Override MethodHandle permuteArguments(MethodType newType, int[] reorder) { try { - return clone(newType, form.permuteArguments(1, reorder, basicTypes(newType.parameterList()))); + return copyWith(newType, form.permuteArguments(1, reorder, basicTypes(newType.parameterList()))); } catch (Throwable t) { throw newInternalError(t); } } - static final String EXTENSION_TYPES = "LIJFD"; - static final byte INDEX_L = 0, INDEX_I = 1, INDEX_J = 2, INDEX_F = 3, INDEX_D = 4; - static byte extensionIndex(char type) { - int i = EXTENSION_TYPES.indexOf(type); - if (i < 0) throw new InternalError(); - return (byte) i; - } - /** * Return the {@link SpeciesData} instance representing this BMH species. All subclasses must provide a * static field containing this value, and they must accordingly implement this method. */ /*non-public*/ abstract SpeciesData speciesData(); + /** + * Return the number of fields in this BMH. Equivalent to speciesData().fieldCount(). + */ + /*non-public*/ abstract int fieldCount(); + @Override final Object internalProperties() { return "/BMH="+internalValues(); @@ -159,38 +155,33 @@ import jdk.internal.org.objectweb.asm.Type; /*non-public*/ final Object arg(int i) { try { switch (speciesData().fieldType(i)) { - case 'L': return argL(i); - case 'I': return argI(i); - case 'F': return argF(i); - case 'D': return argD(i); - case 'J': return argJ(i); + case L_TYPE: return speciesData().getters[i].invokeBasic(this); + case I_TYPE: return (int) speciesData().getters[i].invokeBasic(this); + case J_TYPE: return (long) speciesData().getters[i].invokeBasic(this); + case F_TYPE: return (float) speciesData().getters[i].invokeBasic(this); + case D_TYPE: return (double) speciesData().getters[i].invokeBasic(this); } } catch (Throwable ex) { throw newInternalError(ex); } - throw new InternalError("unexpected type: " + speciesData().types+"."+i); + throw new InternalError("unexpected type: " + speciesData().typeChars+"."+i); } - /*non-public*/ final Object argL(int i) throws Throwable { return speciesData().getters[i].invokeBasic(this); } - /*non-public*/ final int argI(int i) throws Throwable { return (int) speciesData().getters[i].invokeBasic(this); } - /*non-public*/ final float argF(int i) throws Throwable { return (float) speciesData().getters[i].invokeBasic(this); } - /*non-public*/ final double argD(int i) throws Throwable { return (double) speciesData().getters[i].invokeBasic(this); } - /*non-public*/ final long argJ(int i) throws Throwable { return (long) speciesData().getters[i].invokeBasic(this); } // // cloning API // - /*non-public*/ abstract BoundMethodHandle clone(MethodType mt, LambdaForm lf) throws Throwable; - /*non-public*/ abstract BoundMethodHandle cloneExtendL(MethodType mt, LambdaForm lf, Object narg) throws Throwable; - /*non-public*/ abstract BoundMethodHandle cloneExtendI(MethodType mt, LambdaForm lf, int narg) throws Throwable; - /*non-public*/ abstract BoundMethodHandle cloneExtendJ(MethodType mt, LambdaForm lf, long narg) throws Throwable; - /*non-public*/ abstract BoundMethodHandle cloneExtendF(MethodType mt, LambdaForm lf, float narg) throws Throwable; - /*non-public*/ abstract BoundMethodHandle cloneExtendD(MethodType mt, LambdaForm lf, double narg) throws Throwable; + /*non-public*/ abstract BoundMethodHandle copyWith(MethodType mt, LambdaForm lf); + /*non-public*/ abstract BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg); + /*non-public*/ abstract BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg); + /*non-public*/ abstract BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg); + /*non-public*/ abstract BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg); + /*non-public*/ abstract BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg); // The following is a grossly irregular hack: @Override MethodHandle reinvokerTarget() { try { - return (MethodHandle) argL(0); + return (MethodHandle) arg(0); } catch (Throwable ex) { throw newInternalError(ex); } @@ -203,7 +194,7 @@ import jdk.internal.org.objectweb.asm.Type; private // make it private to force users to access the enclosing class first static final class Species_L extends BoundMethodHandle { final Object argL0; - /*non-public*/ Species_L(MethodType mt, LambdaForm lf, Object argL0) { + private Species_L(MethodType mt, LambdaForm lf, Object argL0) { super(mt, lf); this.argL0 = argL0; } @@ -213,140 +204,95 @@ import jdk.internal.org.objectweb.asm.Type; /*non-public*/ SpeciesData speciesData() { return SPECIES_DATA; } - /*non-public*/ static final SpeciesData SPECIES_DATA = SpeciesData.getForClass("L", Species_L.class); @Override - /*non-public*/ final BoundMethodHandle clone(MethodType mt, LambdaForm lf) throws Throwable { + /*non-public*/ int fieldCount() { + return 1; + } + /*non-public*/ static final SpeciesData SPECIES_DATA = SpeciesData.getForClass("L", Species_L.class); + /*non-public*/ static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0) { return new Species_L(mt, lf, argL0); } @Override - /*non-public*/ final BoundMethodHandle cloneExtendL(MethodType mt, LambdaForm lf, Object narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_L).constructor[0].invokeBasic(mt, lf, argL0, narg); + /*non-public*/ final BoundMethodHandle copyWith(MethodType mt, LambdaForm lf) { + return new Species_L(mt, lf, argL0); } @Override - /*non-public*/ final BoundMethodHandle cloneExtendI(MethodType mt, LambdaForm lf, int narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_I).constructor[0].invokeBasic(mt, lf, argL0, narg); + /*non-public*/ final BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg) { + try { + return (BoundMethodHandle) SPECIES_DATA.extendWith(L_TYPE).constructor[0].invokeBasic(mt, lf, argL0, narg); + } catch (Throwable ex) { + throw uncaughtException(ex); + } } @Override - /*non-public*/ final BoundMethodHandle cloneExtendJ(MethodType mt, LambdaForm lf, long narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_J).constructor[0].invokeBasic(mt, lf, argL0, narg); + /*non-public*/ final BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg) { + try { + return (BoundMethodHandle) SPECIES_DATA.extendWith(I_TYPE).constructor[0].invokeBasic(mt, lf, argL0, narg); + } catch (Throwable ex) { + throw uncaughtException(ex); + } } @Override - /*non-public*/ final BoundMethodHandle cloneExtendF(MethodType mt, LambdaForm lf, float narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_F).constructor[0].invokeBasic(mt, lf, argL0, narg); + /*non-public*/ final BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg) { + try { + return (BoundMethodHandle) SPECIES_DATA.extendWith(J_TYPE).constructor[0].invokeBasic(mt, lf, argL0, narg); + } catch (Throwable ex) { + throw uncaughtException(ex); + } } @Override - /*non-public*/ final BoundMethodHandle cloneExtendD(MethodType mt, LambdaForm lf, double narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_D).constructor[0].invokeBasic(mt, lf, argL0, narg); + /*non-public*/ final BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg) { + try { + return (BoundMethodHandle) SPECIES_DATA.extendWith(F_TYPE).constructor[0].invokeBasic(mt, lf, argL0, narg); + } catch (Throwable ex) { + throw uncaughtException(ex); + } + } + @Override + /*non-public*/ final BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg) { + try { + return (BoundMethodHandle) SPECIES_DATA.extendWith(D_TYPE).constructor[0].invokeBasic(mt, lf, argL0, narg); + } catch (Throwable ex) { + throw uncaughtException(ex); + } } } -/* - static final class Species_LL extends BoundMethodHandle { - final Object argL0; - final Object argL1; - public Species_LL(MethodType mt, LambdaForm lf, Object argL0, Object argL1) { - super(mt, lf); - this.argL0 = argL0; - this.argL1 = argL1; - } - @Override - public SpeciesData speciesData() { - return SPECIES_DATA; - } - public static final SpeciesData SPECIES_DATA = SpeciesData.getForClass("LL", Species_LL.class); - @Override - public final BoundMethodHandle clone(MethodType mt, LambdaForm lf) throws Throwable { - return new Species_LL(mt, lf, argL0, argL1); - } - @Override - public final BoundMethodHandle cloneExtendL(MethodType mt, LambdaForm lf, Object narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_L).constructor[0].invokeBasic(mt, lf, argL0, argL1, narg); - } - @Override - public final BoundMethodHandle cloneExtendI(MethodType mt, LambdaForm lf, int narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_I).constructor[0].invokeBasic(mt, lf, argL0, argL1, narg); - } - @Override - public final BoundMethodHandle cloneExtendJ(MethodType mt, LambdaForm lf, long narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_J).constructor[0].invokeBasic(mt, lf, argL0, argL1, narg); - } - @Override - public final BoundMethodHandle cloneExtendF(MethodType mt, LambdaForm lf, float narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_F).constructor[0].invokeBasic(mt, lf, argL0, argL1, narg); - } - @Override - public final BoundMethodHandle cloneExtendD(MethodType mt, LambdaForm lf, double narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_D).constructor[0].invokeBasic(mt, lf, argL0, argL1, narg); - } - } - - static final class Species_JL extends BoundMethodHandle { - final long argJ0; - final Object argL1; - public Species_JL(MethodType mt, LambdaForm lf, long argJ0, Object argL1) { - super(mt, lf); - this.argJ0 = argJ0; - this.argL1 = argL1; - } - @Override - public SpeciesData speciesData() { - return SPECIES_DATA; - } - public static final SpeciesData SPECIES_DATA = SpeciesData.getForClass("JL", Species_JL.class); - @Override public final long argJ0() { return argJ0; } - @Override public final Object argL1() { return argL1; } - @Override - public final BoundMethodHandle clone(MethodType mt, LambdaForm lf) throws Throwable { - return new Species_JL(mt, lf, argJ0, argL1); - } - @Override - public final BoundMethodHandle cloneExtendL(MethodType mt, LambdaForm lf, Object narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_L).constructor[0].invokeBasic(mt, lf, argJ0, argL1, narg); - } - @Override - public final BoundMethodHandle cloneExtendI(MethodType mt, LambdaForm lf, int narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_I).constructor[0].invokeBasic(mt, lf, argJ0, argL1, narg); - } - @Override - public final BoundMethodHandle cloneExtendJ(MethodType mt, LambdaForm lf, long narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_J).constructor[0].invokeBasic(mt, lf, argJ0, argL1, narg); - } - @Override - public final BoundMethodHandle cloneExtendF(MethodType mt, LambdaForm lf, float narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_F).constructor[0].invokeBasic(mt, lf, argJ0, argL1, narg); - } - @Override - public final BoundMethodHandle cloneExtendD(MethodType mt, LambdaForm lf, double narg) throws Throwable { - return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_D).constructor[0].invokeBasic(mt, lf, argJ0, argL1, narg); - } - } -*/ - // // BMH species meta-data // /** - * Meta-data wrapper for concrete BMH classes. + * Meta-data wrapper for concrete BMH types. + * Each BMH type corresponds to a given sequence of basic field types (LIJFD). + * The fields are immutable; their values are fully specified at object construction. + * Each BMH type supplies an array of getter functions which may be used in lambda forms. + * A BMH is constructed by cloning a shorter BMH and adding one or more new field values. + * As a degenerate and common case, the "shorter BMH" can be missing, and contributes zero prior fields. */ static class SpeciesData { - final String types; + final String typeChars; + final BasicType[] typeCodes; final Class clazz; // Bootstrapping requires circular relations MH -> BMH -> SpeciesData -> MH // Therefore, we need a non-final link in the chain. Use array elements. final MethodHandle[] constructor; final MethodHandle[] getters; + final NamedFunction[] nominalGetters; final SpeciesData[] extensions; /*non-public*/ int fieldCount() { - return types.length(); + return typeCodes.length; } - /*non-public*/ char fieldType(int i) { - return types.charAt(i); + /*non-public*/ BasicType fieldType(int i) { + return typeCodes[i]; + } + /*non-public*/ char fieldTypeChar(int i) { + return typeChars.charAt(i); } public String toString() { - return "SpeciesData["+(isPlaceholder() ? "" : clazz.getSimpleName())+":"+types+"]"; + return "SpeciesData["+(isPlaceholder() ? "" : clazz.getSimpleName())+":"+typeChars+"]"; } /** @@ -354,45 +300,46 @@ import jdk.internal.org.objectweb.asm.Type; * represents a MH bound to a generic invoker, which in turn forwards to the corresponding * getter. */ - Name getterName(Name mhName, int i) { - MethodHandle mh = getters[i]; - assert(mh != null) : this+"."+i; - return new Name(mh, mhName); - } - NamedFunction getterFunction(int i) { - return new NamedFunction(getters[i]); + return nominalGetters[i]; } static final SpeciesData EMPTY = new SpeciesData("", BoundMethodHandle.class); private SpeciesData(String types, Class clazz) { - this.types = types; + this.typeChars = types; + this.typeCodes = basicTypes(types); this.clazz = clazz; if (!INIT_DONE) { - this.constructor = new MethodHandle[1]; + this.constructor = new MethodHandle[1]; // only one ctor this.getters = new MethodHandle[types.length()]; + this.nominalGetters = new NamedFunction[types.length()]; } else { this.constructor = Factory.makeCtors(clazz, types, null); this.getters = Factory.makeGetters(clazz, types, null); + this.nominalGetters = Factory.makeNominalGetters(types, null, this.getters); } - this.extensions = new SpeciesData[EXTENSION_TYPES.length()]; + this.extensions = new SpeciesData[ARG_TYPE_LIMIT]; } private void initForBootstrap() { assert(!INIT_DONE); if (constructor[0] == null) { + String types = typeChars; Factory.makeCtors(clazz, types, this.constructor); Factory.makeGetters(clazz, types, this.getters); + Factory.makeNominalGetters(types, this.nominalGetters, this.getters); } } - private SpeciesData(String types) { + private SpeciesData(String typeChars) { // Placeholder only. - this.types = types; + this.typeChars = typeChars; + this.typeCodes = basicTypes(typeChars); this.clazz = null; this.constructor = null; this.getters = null; + this.nominalGetters = null; this.extensions = null; } private boolean isPlaceholder() { return clazz == null; } @@ -401,18 +348,15 @@ import jdk.internal.org.objectweb.asm.Type; static { CACHE.put("", EMPTY); } // make bootstrap predictable private static final boolean INIT_DONE; // set after finishes... - SpeciesData extendWithType(char type) { - int i = extensionIndex(type); - SpeciesData d = extensions[i]; - if (d != null) return d; - extensions[i] = d = get(types+type); - return d; + SpeciesData extendWith(byte type) { + return extendWith(BasicType.basicType(type)); } - SpeciesData extendWithIndex(byte index) { - SpeciesData d = extensions[index]; + SpeciesData extendWith(BasicType type) { + int ord = type.ordinal(); + SpeciesData d = extensions[ord]; if (d != null) return d; - extensions[index] = d = get(types+EXTENSION_TYPES.charAt(index)); + extensions[ord] = d = get(typeChars+type.basicTypeChar()); return d; } @@ -456,8 +400,6 @@ import jdk.internal.org.objectweb.asm.Type; static { // pre-fill the BMH speciesdata cache with BMH's inner classes final Class rootCls = BoundMethodHandle.class; - SpeciesData d0 = BoundMethodHandle.SPECIES_DATA; // trigger class init - assert(d0 == null || d0 == lookupCache("")) : d0; try { for (Class c : rootCls.getDeclaredClasses()) { if (rootCls.isAssignableFrom(c)) { @@ -465,7 +407,7 @@ import jdk.internal.org.objectweb.asm.Type; SpeciesData d = Factory.speciesDataFromConcreteBMHClass(cbmh); assert(d != null) : cbmh.getName(); assert(d.clazz == cbmh); - assert(d == lookupCache(d.types)); + assert(d == lookupCache(d.typeChars)); } } } catch (Throwable e) { @@ -516,11 +458,10 @@ import jdk.internal.org.objectweb.asm.Type; static final String BMHSPECIES_DATA_GFC_SIG = "(" + JLS_SIG + JLC_SIG + ")" + SPECIES_DATA_SIG; static final String MYSPECIES_DATA_SIG = "()" + SPECIES_DATA_SIG; static final String VOID_SIG = "()V"; + static final String INT_SIG = "()I"; static final String SIG_INCIPIT = "(Ljava/lang/invoke/MethodType;Ljava/lang/invoke/LambdaForm;"; - static final Class[] TYPES = new Class[] { Object.class, int.class, long.class, float.class, double.class }; - static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" }; /** @@ -551,31 +492,35 @@ import jdk.internal.org.objectweb.asm.Type; * final Object argL0; * final Object argL1; * final int argI2; - * Species_LLI(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) { + * private Species_LLI(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) { * super(mt, lf); * this.argL0 = argL0; * this.argL1 = argL1; * this.argI2 = argI2; * } * final SpeciesData speciesData() { return SPECIES_DATA; } + * final int fieldCount() { return 3; } * static final SpeciesData SPECIES_DATA = SpeciesData.getForClass("LLI", Species_LLI.class); - * final BoundMethodHandle clone(MethodType mt, LambdaForm lf) { - * return SPECIES_DATA.constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2); + * static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) { + * return new Species_LLI(mt, lf, argL0, argL1, argI2); * } - * final BoundMethodHandle cloneExtendL(MethodType mt, LambdaForm lf, Object narg) { - * return SPECIES_DATA.extendWithIndex(INDEX_L).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg); + * final BoundMethodHandle copyWith(MethodType mt, LambdaForm lf) { + * return new Species_LLI(mt, lf, argL0, argL1, argI2); * } - * final BoundMethodHandle cloneExtendI(MethodType mt, LambdaForm lf, int narg) { - * return SPECIES_DATA.extendWithIndex(INDEX_I).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg); + * final BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg) { + * return SPECIES_DATA.extendWith(L_TYPE).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg); * } - * final BoundMethodHandle cloneExtendJ(MethodType mt, LambdaForm lf, long narg) { - * return SPECIES_DATA.extendWithIndex(INDEX_J).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg); + * final BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg) { + * return SPECIES_DATA.extendWith(I_TYPE).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg); * } - * final BoundMethodHandle cloneExtendF(MethodType mt, LambdaForm lf, float narg) { - * return SPECIES_DATA.extendWithIndex(INDEX_F).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg); + * final BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg) { + * return SPECIES_DATA.extendWith(J_TYPE).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg); * } - * final BoundMethodHandle cloneExtendD(MethodType mt, LambdaForm lf, double narg) { - * return SPECIES_DATA.extendWithIndex(INDEX_D).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg); + * final BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg) { + * return SPECIES_DATA.extendWith(F_TYPE).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg); + * } + * public final BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg) { + * return SPECIES_DATA.extendWith(D_TYPE).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg); * } * } * @@ -586,8 +531,9 @@ import jdk.internal.org.objectweb.asm.Type; static Class generateConcreteBMHClass(String types) { final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); - final String className = SPECIES_PREFIX_PATH + types; - final String sourceFile = SPECIES_PREFIX_NAME + types; + String shortTypes = LambdaForm.shortenSignature(types); + final String className = SPECIES_PREFIX_PATH + shortTypes; + final String sourceFile = SPECIES_PREFIX_NAME + shortTypes; 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); @@ -606,11 +552,11 @@ import jdk.internal.org.objectweb.asm.Type; MethodVisitor mv; // emit constructor - mv = cw.visitMethod(NOT_ACC_PUBLIC, "", makeSignature(types, true), null, null); + mv = cw.visitMethod(ACC_PRIVATE, "", makeSignature(types, true), null, null); mv.visitCode(); - mv.visitVarInsn(ALOAD, 0); - mv.visitVarInsn(ALOAD, 1); - mv.visitVarInsn(ALOAD, 2); + mv.visitVarInsn(ALOAD, 0); // this + mv.visitVarInsn(ALOAD, 1); // type + mv.visitVarInsn(ALOAD, 2); // form mv.visitMethodInsn(INVOKESPECIAL, BMH, "", makeSignature("", true), false); @@ -647,39 +593,73 @@ import jdk.internal.org.objectweb.asm.Type; mv.visitMaxs(0, 0); mv.visitEnd(); - // emit clone() - mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "clone", makeSignature("", false), null, E_THROWABLE); + // emit implementation of fieldCount() + mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "fieldCount", INT_SIG, null, null); mv.visitCode(); - // return speciesData().constructor[0].invokeBasic(mt, lf, argL0, ...) - // obtain constructor - mv.visitVarInsn(ALOAD, 0); - mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG); - mv.visitFieldInsn(GETFIELD, SPECIES_DATA, "constructor", "[" + MH_SIG); - mv.visitInsn(ICONST_0); - mv.visitInsn(AALOAD); + int fc = types.length(); + if (fc <= (ICONST_5 - ICONST_0)) { + mv.visitInsn(ICONST_0 + fc); + } else { + mv.visitIntInsn(SIPUSH, fc); + } + mv.visitInsn(IRETURN); + mv.visitMaxs(0, 0); + mv.visitEnd(); + // emit make() ...factory method wrapping constructor + mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_STATIC, "make", makeSignature(types, false), null, null); + mv.visitCode(); + // make instance + mv.visitTypeInsn(NEW, className); + mv.visitInsn(DUP); + // load mt, lf + mv.visitVarInsn(ALOAD, 0); // type + mv.visitVarInsn(ALOAD, 1); // form + // load factory method arguments + for (int i = 0, j = 0; i < types.length(); ++i, ++j) { + // i counts the arguments, j counts corresponding argument slots + char t = types.charAt(i); + mv.visitVarInsn(typeLoadOp(t), j + 2); // parameters start at 3 + if (t == 'J' || t == 'D') { + ++j; // adjust argument register access + } + } + + // finally, invoke the constructor and return + mv.visitMethodInsn(INVOKESPECIAL, className, "", makeSignature(types, true), false); + mv.visitInsn(ARETURN); + mv.visitMaxs(0, 0); + mv.visitEnd(); + + // emit copyWith() + mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "copyWith", makeSignature("", false), null, null); + mv.visitCode(); + // make instance + mv.visitTypeInsn(NEW, className); + mv.visitInsn(DUP); // load mt, lf mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ALOAD, 2); // put fields on the stack emitPushFields(types, className, mv); // finally, invoke the constructor and return - mv.visitMethodInsn(INVOKEVIRTUAL, MH, "invokeBasic", makeSignature(types, false), false); + mv.visitMethodInsn(INVOKESPECIAL, className, "", makeSignature(types, true), false); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); - // for each type, emit cloneExtendT() - for (Class c : TYPES) { - char t = Wrapper.basicTypeChar(c); - mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "cloneExtend" + t, makeSignature(String.valueOf(t), false), null, E_THROWABLE); + // for each type, emit copyWithExtendT() + for (BasicType type : BasicType.ARG_TYPES) { + int ord = type.ordinal(); + char btChar = type.basicTypeChar(); + mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "copyWithExtend" + btChar, makeSignature(String.valueOf(btChar), false), null, E_THROWABLE); mv.visitCode(); - // return SPECIES_DATA.extendWithIndex(extensionIndex(t)).constructor[0].invokeBasic(mt, lf, argL0, ..., narg) + // return SPECIES_DATA.extendWith(t).constructor[0].invokeBasic(mt, lf, argL0, ..., narg) // obtain constructor mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG); - int iconstInsn = ICONST_0 + extensionIndex(t); + int iconstInsn = ICONST_0 + ord; assert(iconstInsn <= ICONST_5); mv.visitInsn(iconstInsn); - mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, "extendWithIndex", BMHSPECIES_DATA_EWI_SIG, false); + mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, "extendWith", BMHSPECIES_DATA_EWI_SIG, false); mv.visitFieldInsn(GETFIELD, SPECIES_DATA, "constructor", "[" + MH_SIG); mv.visitInsn(ICONST_0); mv.visitInsn(AALOAD); @@ -689,9 +669,9 @@ import jdk.internal.org.objectweb.asm.Type; // put fields on the stack emitPushFields(types, className, mv); // put narg on stack - mv.visitVarInsn(typeLoadOp(t), 3); + mv.visitVarInsn(typeLoadOp(btChar), 3); // finally, invoke the constructor and return - mv.visitMethodInsn(INVOKEVIRTUAL, MH, "invokeBasic", makeSignature(types + t, false), false); + mv.visitMethodInsn(INVOKEVIRTUAL, MH, "invokeBasic", makeSignature(types + btChar, false), false); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); @@ -730,7 +710,7 @@ import jdk.internal.org.objectweb.asm.Type; case 'J': return LLOAD; case 'F': return FLOAD; case 'D': return DLOAD; - default : throw new InternalError("unrecognized type " + t); + default : throw newInternalError("unrecognized type " + t); } } @@ -771,10 +751,19 @@ import jdk.internal.org.objectweb.asm.Type; static MethodHandle[] makeCtors(Class cbmh, String types, MethodHandle mhs[]) { if (mhs == null) mhs = new MethodHandle[1]; + if (types.equals("")) return mhs; // hack for empty BMH species mhs[0] = makeCbmhCtor(cbmh, types); return mhs; } + static NamedFunction[] makeNominalGetters(String types, NamedFunction[] nfs, MethodHandle[] getters) { + if (nfs == null) nfs = new NamedFunction[types.length()]; + for (int i = 0; i < nfs.length; ++i) { + nfs[i] = new NamedFunction(getters[i]); + } + return nfs; + } + // // Auxiliary methods. // @@ -808,52 +797,11 @@ import jdk.internal.org.objectweb.asm.Type; static MethodHandle makeCbmhCtor(Class cbmh, String types) { try { - return linkConstructor(LOOKUP.findConstructor(cbmh, MethodType.fromMethodDescriptorString(makeSignature(types, true), null))); + return LOOKUP.findStatic(cbmh, "make", MethodType.fromMethodDescriptorString(makeSignature(types, false), null)); } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | TypeNotPresentException e) { throw newInternalError(e); } } - - /** - * Wrap a constructor call in a {@link LambdaForm}. - * - * If constructors ({@code } methods) are called in LFs, problems might arise if the LFs - * are turned into bytecode, because the call to the allocator is routed through an MH, and the - * verifier cannot find a {@code NEW} instruction preceding the {@code INVOKESPECIAL} to - * {@code }. To avoid this, we add an indirection by invoking {@code } through - * {@link MethodHandle#linkToSpecial}. - * - * The last {@link LambdaForm.Name Name} in the argument's form is expected to be the {@code void} - * result of the {@code } invocation. This entry is replaced. - */ - private static MethodHandle linkConstructor(MethodHandle cmh) { - final LambdaForm lf = cmh.form; - final int initNameIndex = lf.names.length - 1; - final Name initName = lf.names[initNameIndex]; - final MemberName ctorMN = initName.function.member; - final MethodType ctorMT = ctorMN.getInvocationType(); - - // obtain function member (call target) - // linker method type replaces initial parameter (BMH species) with BMH to avoid naming a species (anonymous class!) - final MethodType linkerMT = ctorMT.changeParameterType(0, BoundMethodHandle.class).appendParameterTypes(MemberName.class); - MemberName linkerMN = new MemberName(MethodHandle.class, "linkToSpecial", linkerMT, REF_invokeStatic); - try { - linkerMN = MemberName.getFactory().resolveOrFail(REF_invokeStatic, linkerMN, null, NoSuchMethodException.class); - assert(linkerMN.isStatic()); - } catch (ReflectiveOperationException ex) { - throw newInternalError(ex); - } - // extend arguments array - Object[] newArgs = Arrays.copyOf(initName.arguments, initName.arguments.length + 1); - newArgs[newArgs.length - 1] = ctorMN; - // replace function - final NamedFunction nf = new NamedFunction(linkerMN); - final Name linkedCtor = new Name(nf, newArgs); - linkedCtor.initIndex(initNameIndex); - lf.names[initNameIndex] = linkedCtor; - return cmh; - } - } private static final Lookup LOOKUP = Lookup.IMPL_LOOKUP; diff --git a/jdk/src/share/classes/java/lang/invoke/DirectMethodHandle.java b/jdk/src/share/classes/java/lang/invoke/DirectMethodHandle.java index 9c054519b43..0fbc4619e22 100644 --- a/jdk/src/share/classes/java/lang/invoke/DirectMethodHandle.java +++ b/jdk/src/share/classes/java/lang/invoke/DirectMethodHandle.java @@ -31,6 +31,7 @@ import java.util.Arrays; import sun.invoke.util.VerifyAccess; import static java.lang.invoke.MethodHandleNatives.Constants.*; import static java.lang.invoke.LambdaForm.*; +import static java.lang.invoke.LambdaForm.BasicType.*; import static java.lang.invoke.MethodTypeForm.*; import static java.lang.invoke.MethodHandleStatics.*; import java.lang.ref.WeakReference; @@ -124,11 +125,6 @@ class DirectMethodHandle extends MethodHandle { return new Constructor(mtype, lform, ctor, init, instanceClass); } - @Override - MethodHandle copyWith(MethodType mt, LambdaForm lf) { - return new DirectMethodHandle(mt, lf, member); - } - @Override String internalProperties() { return "/DMH="+member.toString(); @@ -146,9 +142,9 @@ class DirectMethodHandle extends MethodHandle { } @Override - MethodHandle bindArgument(int pos, char basicType, Object value) { + MethodHandle bindArgument(int pos, BasicType basicType, Object value) { // If the member needs dispatching, do so. - if (pos == 0 && basicType == 'L') { + if (pos == 0 && basicType == L_TYPE) { DirectMethodHandle concrete = maybeRebind(value); if (concrete != null) return concrete.bindReceiver(value); @@ -274,7 +270,7 @@ class DirectMethodHandle extends MethodHandle { result = NEW_OBJ; } names[LINKER_CALL] = new Name(linker, outArgs); - lambdaName += "_" + LambdaForm.basicTypeSignature(mtype); + lambdaName += "_" + shortenSignature(basicTypeSignature(mtype)); LambdaForm lform = new LambdaForm(lambdaName, ARG_LIMIT, names, result); // This is a tricky bit of code. Don't send it through the LF interpreter. lform.compileToBytecode(); diff --git a/jdk/src/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java b/jdk/src/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java index 145203b0a07..7bcdfaf5e89 100644 --- a/jdk/src/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java +++ b/jdk/src/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java @@ -26,7 +26,7 @@ package java.lang.invoke; import sun.invoke.util.VerifyAccess; -import java.lang.invoke.LambdaForm.Name; +import static java.lang.invoke.LambdaForm.*; import sun.invoke.util.Wrapper; @@ -38,6 +38,7 @@ import jdk.internal.org.objectweb.asm.*; import java.lang.reflect.*; import static java.lang.invoke.MethodHandleStatics.*; import static java.lang.invoke.MethodHandleNatives.Constants.*; +import static java.lang.invoke.LambdaForm.BasicType.*; import sun.invoke.util.VerifyType; /** @@ -115,7 +116,7 @@ class InvokerBytecodeGenerator { Name[] names = form.names; for (int i = 0, index = 0; i < localsMap.length; i++) { localsMap[i] = index; - index += Wrapper.forBasicType(names[i].type).stackSlots(); + index += names[i].type.basicTypeSlots(); } } @@ -358,47 +359,52 @@ class InvokerBytecodeGenerator { /* * NOTE: These load/store methods use the localsMap to find the correct index! */ - private void emitLoadInsn(char type, int index) { - int opcode; - switch (type) { - case 'I': opcode = Opcodes.ILOAD; break; - case 'J': opcode = Opcodes.LLOAD; break; - case 'F': opcode = Opcodes.FLOAD; break; - case 'D': opcode = Opcodes.DLOAD; break; - case 'L': opcode = Opcodes.ALOAD; break; - default: - throw new InternalError("unknown type: " + type); - } + private void emitLoadInsn(BasicType type, int index) { + int opcode = loadInsnOpcode(type); mv.visitVarInsn(opcode, localsMap[index]); } - private void emitAloadInsn(int index) { - emitLoadInsn('L', index); - } - private void emitStoreInsn(char type, int index) { - int opcode; + private int loadInsnOpcode(BasicType type) throws InternalError { switch (type) { - case 'I': opcode = Opcodes.ISTORE; break; - case 'J': opcode = Opcodes.LSTORE; break; - case 'F': opcode = Opcodes.FSTORE; break; - case 'D': opcode = Opcodes.DSTORE; break; - case 'L': opcode = Opcodes.ASTORE; break; - default: - throw new InternalError("unknown type: " + type); + case I_TYPE: return Opcodes.ILOAD; + case J_TYPE: return Opcodes.LLOAD; + case F_TYPE: return Opcodes.FLOAD; + case D_TYPE: return Opcodes.DLOAD; + case L_TYPE: return Opcodes.ALOAD; + default: + throw new InternalError("unknown type: " + type); } + } + private void emitAloadInsn(int index) { + emitLoadInsn(L_TYPE, index); + } + + private void emitStoreInsn(BasicType type, int index) { + int opcode = storeInsnOpcode(type); mv.visitVarInsn(opcode, localsMap[index]); } + + private int storeInsnOpcode(BasicType type) throws InternalError { + switch (type) { + case I_TYPE: return Opcodes.ISTORE; + case J_TYPE: return Opcodes.LSTORE; + case F_TYPE: return Opcodes.FSTORE; + case D_TYPE: return Opcodes.DSTORE; + case L_TYPE: return Opcodes.ASTORE; + default: + throw new InternalError("unknown type: " + type); + } + } private void emitAstoreInsn(int index) { - emitStoreInsn('L', index); + emitStoreInsn(L_TYPE, index); } /** * Emit a boxing call. * - * @param type primitive type class to box. + * @param wrapper primitive type class to box. */ - private void emitBoxing(Class type) { - Wrapper wrapper = Wrapper.forPrimitiveType(type); + private void emitBoxing(Wrapper wrapper) { String owner = "java/lang/" + wrapper.wrapperType().getSimpleName(); String name = "valueOf"; String desc = "(" + wrapper.basicTypeChar() + ")L" + owner + ";"; @@ -408,10 +414,9 @@ class InvokerBytecodeGenerator { /** * Emit an unboxing call (plus preceding checkcast). * - * @param type wrapper type class to unbox. + * @param wrapper wrapper type class to unbox. */ - private void emitUnboxing(Class type) { - Wrapper wrapper = Wrapper.forWrapperType(type); + private void emitUnboxing(Wrapper wrapper) { String owner = "java/lang/" + wrapper.wrapperType().getSimpleName(); String name = wrapper.primitiveSimpleName() + "Value"; String desc = "()" + wrapper.basicTypeChar(); @@ -425,9 +430,12 @@ class InvokerBytecodeGenerator { * @param ptype type of value present on stack * @param pclass type of value required on stack */ - private void emitImplicitConversion(char ptype, Class pclass) { + private void emitImplicitConversion(BasicType ptype, Class pclass) { + assert(basicType(pclass) == ptype); // boxing/unboxing handled by caller + if (pclass == ptype.basicTypeClass() && ptype != L_TYPE) + return; // nothing to do switch (ptype) { - case 'L': + case L_TYPE: if (VerifyType.isNullConversion(Object.class, pclass)) return; if (isStaticallyNameable(pclass)) { @@ -441,18 +449,9 @@ class InvokerBytecodeGenerator { mv.visitTypeInsn(Opcodes.CHECKCAST, OBJARY); } return; - case 'I': + case I_TYPE: if (!VerifyType.isNullConversion(int.class, pclass)) - emitPrimCast(ptype, Wrapper.basicTypeChar(pclass)); - return; - case 'J': - assert(pclass == long.class); - return; - case 'F': - assert(pclass == float.class); - return; - case 'D': - assert(pclass == double.class); + emitPrimCast(ptype.basicTypeWrapper(), Wrapper.forPrimitiveType(pclass)); return; } throw new InternalError("bad implicit conversion: tc="+ptype+": "+pclass); @@ -461,15 +460,15 @@ class InvokerBytecodeGenerator { /** * Emits an actual return instruction conforming to the given return type. */ - private void emitReturnInsn(Class type) { + private void emitReturnInsn(BasicType type) { int opcode; - switch (Wrapper.basicTypeChar(type)) { - case 'I': opcode = Opcodes.IRETURN; break; - case 'J': opcode = Opcodes.LRETURN; break; - case 'F': opcode = Opcodes.FRETURN; break; - case 'D': opcode = Opcodes.DRETURN; break; - case 'L': opcode = Opcodes.ARETURN; break; - case 'V': opcode = Opcodes.RETURN; break; + switch (type) { + case I_TYPE: opcode = Opcodes.IRETURN; break; + case J_TYPE: opcode = Opcodes.LRETURN; break; + case F_TYPE: opcode = Opcodes.FRETURN; break; + case D_TYPE: opcode = Opcodes.DRETURN; break; + case L_TYPE: opcode = Opcodes.ARETURN; break; + case V_TYPE: opcode = Opcodes.RETURN; break; default: throw new InternalError("unknown return type: " + type); } @@ -531,7 +530,7 @@ class InvokerBytecodeGenerator { // avoid store/load/return and just return) if (i == lambdaForm.names.length - 1 && i == lambdaForm.result) { // return value - do nothing - } else if (name.type != 'V') { + } else if (name.type != V_TYPE) { // non-void: actually assign emitStoreInsn(name.type, name.index()); } @@ -865,20 +864,24 @@ class InvokerBytecodeGenerator { private void emitPushArgument(Name name, int paramIndex) { Object arg = name.arguments[paramIndex]; - char ptype = name.function.parameterType(paramIndex); - MethodType mtype = name.function.methodType(); + Class ptype = name.function.methodType().parameterType(paramIndex); + emitPushArgument(ptype, arg); + } + + private void emitPushArgument(Class ptype, Object arg) { + BasicType bptype = basicType(ptype); if (arg instanceof Name) { Name n = (Name) arg; emitLoadInsn(n.type, n.index()); - emitImplicitConversion(n.type, mtype.parameterType(paramIndex)); - } else if ((arg == null || arg instanceof String) && ptype == 'L') { + emitImplicitConversion(n.type, ptype); + } else if ((arg == null || arg instanceof String) && bptype == L_TYPE) { emitConst(arg); } else { - if (Wrapper.isWrapperType(arg.getClass()) && ptype != 'L') { + if (Wrapper.isWrapperType(arg.getClass()) && bptype != L_TYPE) { emitConst(arg); } else { mv.visitLdcInsn(constantPlaceholder(arg)); - emitImplicitConversion('L', mtype.parameterType(paramIndex)); + emitImplicitConversion(L_TYPE, ptype); } } } @@ -888,52 +891,33 @@ class InvokerBytecodeGenerator { */ private void emitReturn() { // return statement - if (lambdaForm.result == -1) { + Class rclass = invokerType.returnType(); + BasicType rtype = lambdaForm.returnType(); + assert(rtype == basicType(rclass)); // must agree + if (rtype == V_TYPE) { // void mv.visitInsn(Opcodes.RETURN); + // it doesn't matter what rclass is; the JVM will discard any value } else { LambdaForm.Name rn = lambdaForm.names[lambdaForm.result]; - char rtype = Wrapper.basicTypeChar(invokerType.returnType()); // put return value on the stack if it is not already there - if (lambdaForm.result != lambdaForm.names.length - 1) { + if (lambdaForm.result != lambdaForm.names.length - 1 || + lambdaForm.result < lambdaForm.arity) { emitLoadInsn(rn.type, lambdaForm.result); } - // potentially generate cast - // rtype is the return type of the invoker - generated code must conform to this - // rn.type is the type of the result Name in the LF - if (rtype != rn.type) { - // need cast - if (rtype == 'L') { - // possibly cast the primitive to the correct type for boxing - char boxedType = Wrapper.forWrapperType(invokerType.returnType()).basicTypeChar(); - if (boxedType != rn.type) { - emitPrimCast(rn.type, boxedType); - } - // cast primitive to reference ("boxing") - emitBoxing(invokerType.returnType()); - } else { - // to-primitive cast - if (rn.type != 'L') { - // prim-to-prim cast - emitPrimCast(rn.type, rtype); - } else { - // ref-to-prim cast ("unboxing") - throw new InternalError("no ref-to-prim (unboxing) casts supported right now"); - } - } - } + emitImplicitConversion(rtype, rclass); // generate actual return statement - emitReturnInsn(invokerType.returnType()); + emitReturnInsn(rtype); } } /** * Emit a type conversion bytecode casting from "from" to "to". */ - private void emitPrimCast(char from, char to) { + private void emitPrimCast(Wrapper from, Wrapper to) { // Here's how. // - indicates forbidden // <-> indicates implicit @@ -950,17 +934,15 @@ class InvokerBytecodeGenerator { // no cast required, should be dead code anyway return; } - Wrapper wfrom = Wrapper.forBasicType(from); - Wrapper wto = Wrapper.forBasicType(to); - if (wfrom.isSubwordOrInt()) { + if (from.isSubwordOrInt()) { // cast from {byte,short,char,int} to anything emitI2X(to); } else { // cast from {long,float,double} to anything - if (wto.isSubwordOrInt()) { + if (to.isSubwordOrInt()) { // cast to {byte,short,char,int} emitX2I(from); - if (wto.bitWidth() < 32) { + if (to.bitWidth() < 32) { // targets other than int require another conversion emitI2X(to); } @@ -968,20 +950,26 @@ class InvokerBytecodeGenerator { // cast to {long,float,double} - this is verbose boolean error = false; switch (from) { - case 'J': - if (to == 'F') { mv.visitInsn(Opcodes.L2F); } - else if (to == 'D') { mv.visitInsn(Opcodes.L2D); } - else error = true; + case LONG: + switch (to) { + case FLOAT: mv.visitInsn(Opcodes.L2F); break; + case DOUBLE: mv.visitInsn(Opcodes.L2D); break; + default: error = true; break; + } break; - case 'F': - if (to == 'J') { mv.visitInsn(Opcodes.F2L); } - else if (to == 'D') { mv.visitInsn(Opcodes.F2D); } - else error = true; + case FLOAT: + switch (to) { + case LONG : mv.visitInsn(Opcodes.F2L); break; + case DOUBLE: mv.visitInsn(Opcodes.F2D); break; + default: error = true; break; + } break; - case 'D': - if (to == 'J') { mv.visitInsn(Opcodes.D2L); } - else if (to == 'F') { mv.visitInsn(Opcodes.D2F); } - else error = true; + case DOUBLE: + switch (to) { + case LONG : mv.visitInsn(Opcodes.D2L); break; + case FLOAT: mv.visitInsn(Opcodes.D2F); break; + default: error = true; break; + } break; default: error = true; @@ -994,16 +982,16 @@ class InvokerBytecodeGenerator { } } - private void emitI2X(char type) { + private void emitI2X(Wrapper type) { switch (type) { - case 'B': mv.visitInsn(Opcodes.I2B); break; - case 'S': mv.visitInsn(Opcodes.I2S); break; - case 'C': mv.visitInsn(Opcodes.I2C); break; - case 'I': /* naught */ break; - case 'J': mv.visitInsn(Opcodes.I2L); break; - case 'F': mv.visitInsn(Opcodes.I2F); break; - case 'D': mv.visitInsn(Opcodes.I2D); break; - case 'Z': + case BYTE: mv.visitInsn(Opcodes.I2B); break; + case SHORT: mv.visitInsn(Opcodes.I2S); break; + case CHAR: mv.visitInsn(Opcodes.I2C); break; + case INT: /* naught */ break; + case LONG: mv.visitInsn(Opcodes.I2L); break; + case FLOAT: mv.visitInsn(Opcodes.I2F); break; + case DOUBLE: mv.visitInsn(Opcodes.I2D); break; + case BOOLEAN: // For compatibility with ValueConversions and explicitCastArguments: mv.visitInsn(Opcodes.ICONST_1); mv.visitInsn(Opcodes.IAND); @@ -1012,39 +1000,24 @@ class InvokerBytecodeGenerator { } } - private void emitX2I(char type) { + private void emitX2I(Wrapper type) { switch (type) { - case 'J': mv.visitInsn(Opcodes.L2I); break; - case 'F': mv.visitInsn(Opcodes.F2I); break; - case 'D': mv.visitInsn(Opcodes.D2I); break; - default: throw new InternalError("unknown type: " + type); + case LONG: mv.visitInsn(Opcodes.L2I); break; + case FLOAT: mv.visitInsn(Opcodes.F2I); break; + case DOUBLE: mv.visitInsn(Opcodes.D2I); break; + default: throw new InternalError("unknown type: " + type); } } - private static String basicTypeCharSignature(String prefix, MethodType type) { - StringBuilder buf = new StringBuilder(prefix); - for (Class ptype : type.parameterList()) - buf.append(Wrapper.forBasicType(ptype).basicTypeChar()); - buf.append('_').append(Wrapper.forBasicType(type.returnType()).basicTypeChar()); - return buf.toString(); - } - /** * Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments. */ static MemberName generateLambdaFormInterpreterEntryPoint(String sig) { - assert(LambdaForm.isValidSignature(sig)); - //System.out.println("generateExactInvoker "+sig); - // compute method type - // first parameter and return type - char tret = LambdaForm.signatureReturn(sig); - MethodType type = MethodType.methodType(LambdaForm.typeClass(tret), MethodHandle.class); - // other parameter types - int arity = LambdaForm.signatureArity(sig); - for (int i = 1; i < arity; i++) { - type = type.appendParameterTypes(LambdaForm.typeClass(sig.charAt(i))); - } - InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", "interpret_"+tret, type); + assert(isValidSignature(sig)); + String name = "interpret_"+signatureReturn(sig).basicTypeChar(); + MethodType type = signatureType(sig); // sig includes leading argument + type = type.changeParameterType(0, MethodHandle.class); + InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", name, type); return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes()); } @@ -1066,10 +1039,10 @@ class InvokerBytecodeGenerator { Class ptype = invokerType.parameterType(i); mv.visitInsn(Opcodes.DUP); emitIconstInsn(i); - emitLoadInsn(Wrapper.basicTypeChar(ptype), i); + emitLoadInsn(basicType(ptype), i); // box if primitive type if (ptype.isPrimitive()) { - emitBoxing(ptype); + emitBoxing(Wrapper.forPrimitiveType(ptype)); } mv.visitInsn(Opcodes.AASTORE); } @@ -1082,11 +1055,11 @@ class InvokerBytecodeGenerator { // maybe unbox Class rtype = invokerType.returnType(); if (rtype.isPrimitive() && rtype != void.class) { - emitUnboxing(Wrapper.asWrapperType(rtype)); + emitUnboxing(Wrapper.forPrimitiveType(rtype)); } // return statement - emitReturnInsn(rtype); + emitReturnInsn(basicType(rtype)); classFileEpilogue(); bogusMethod(invokerType); @@ -1100,14 +1073,12 @@ class InvokerBytecodeGenerator { * Generate bytecode for a NamedFunction invoker. */ static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) { - MethodType invokerType = LambdaForm.NamedFunction.INVOKER_METHOD_TYPE; - String invokerName = basicTypeCharSignature("invoke_", typeForm.erasedType()); + MethodType invokerType = NamedFunction.INVOKER_METHOD_TYPE; + String invokerName = "invoke_" + shortenSignature(basicTypeSignature(typeForm.erasedType())); InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType); return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm)); } - static int nfi = 0; - private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) { MethodType dstType = typeForm.erasedType(); classFilePrologue(); @@ -1133,8 +1104,8 @@ class InvokerBytecodeGenerator { Class sptype = dstType.basicType().wrap().parameterType(i); Wrapper dstWrapper = Wrapper.forBasicType(dptype); Wrapper srcWrapper = dstWrapper.isSubwordOrInt() ? Wrapper.INT : dstWrapper; // narrow subword from int - emitUnboxing(srcWrapper.wrapperType()); - emitPrimCast(srcWrapper.basicTypeChar(), dstWrapper.basicTypeChar()); + emitUnboxing(srcWrapper); + emitPrimCast(srcWrapper, dstWrapper); } } @@ -1148,15 +1119,15 @@ class InvokerBytecodeGenerator { Wrapper srcWrapper = Wrapper.forBasicType(rtype); Wrapper dstWrapper = srcWrapper.isSubwordOrInt() ? Wrapper.INT : srcWrapper; // widen subword to int // boolean casts not allowed - emitPrimCast(srcWrapper.basicTypeChar(), dstWrapper.basicTypeChar()); - emitBoxing(dstWrapper.primitiveType()); + emitPrimCast(srcWrapper, dstWrapper); + emitBoxing(dstWrapper); } // If the return type is void we return a null reference. if (rtype == void.class) { mv.visitInsn(Opcodes.ACONST_NULL); } - emitReturnInsn(Object.class); // NOTE: NamedFunction invokers always return a reference value. + emitReturnInsn(L_TYPE); // NOTE: NamedFunction invokers always return a reference value. classFileEpilogue(); bogusMethod(dstType); diff --git a/jdk/src/share/classes/java/lang/invoke/LambdaForm.java b/jdk/src/share/classes/java/lang/invoke/LambdaForm.java index a5e40ed5211..36630459b88 100644 --- a/jdk/src/share/classes/java/lang/invoke/LambdaForm.java +++ b/jdk/src/share/classes/java/lang/invoke/LambdaForm.java @@ -30,14 +30,14 @@ import java.lang.reflect.Method; import java.util.Map; import java.util.List; import java.util.Arrays; -import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import sun.invoke.util.Wrapper; +import java.lang.reflect.Field; + +import static java.lang.invoke.LambdaForm.BasicType.*; import static java.lang.invoke.MethodHandleStatics.*; import static java.lang.invoke.MethodHandleNatives.Constants.*; -import java.lang.reflect.Field; -import java.util.Objects; /** * The symbolic, non-executable form of a method handle's invocation semantics. @@ -130,13 +130,119 @@ class LambdaForm { public static final int VOID_RESULT = -1, LAST_RESULT = -2; + enum BasicType { + L_TYPE('L', Object.class, Wrapper.OBJECT), // all reference types + I_TYPE('I', int.class, Wrapper.INT), + J_TYPE('J', long.class, Wrapper.LONG), + F_TYPE('F', float.class, Wrapper.FLOAT), + D_TYPE('D', double.class, Wrapper.DOUBLE), // all primitive types + V_TYPE('V', void.class, Wrapper.VOID); // not valid in all contexts + + static final BasicType[] ALL_TYPES = BasicType.values(); + static final BasicType[] ARG_TYPES = Arrays.copyOf(ALL_TYPES, ALL_TYPES.length-1); + + static final int ARG_TYPE_LIMIT = ARG_TYPES.length; + static final int TYPE_LIMIT = ALL_TYPES.length; + + private final char btChar; + private final Class btClass; + private final Wrapper btWrapper; + + private BasicType(char btChar, Class btClass, Wrapper wrapper) { + this.btChar = btChar; + this.btClass = btClass; + this.btWrapper = wrapper; + } + + char basicTypeChar() { + return btChar; + } + Class basicTypeClass() { + return btClass; + } + Wrapper basicTypeWrapper() { + return btWrapper; + } + int basicTypeSlots() { + return btWrapper.stackSlots(); + } + + static BasicType basicType(byte type) { + return ALL_TYPES[type]; + } + static BasicType basicType(char type) { + switch (type) { + case 'L': return L_TYPE; + case 'I': return I_TYPE; + case 'J': return J_TYPE; + case 'F': return F_TYPE; + case 'D': return D_TYPE; + case 'V': return V_TYPE; + // all subword types are represented as ints + case 'Z': + case 'B': + case 'S': + case 'C': + return I_TYPE; + default: + throw newInternalError("Unknown type char: '"+type+"'"); + } + } + static BasicType basicType(Wrapper type) { + char c = type.basicTypeChar(); + return basicType(c); + } + static BasicType basicType(Class type) { + if (!type.isPrimitive()) return L_TYPE; + return basicType(Wrapper.forPrimitiveType(type)); + } + + static char basicTypeChar(Class type) { + return basicType(type).btChar; + } + static BasicType[] basicTypes(List> types) { + BasicType[] btypes = new BasicType[types.size()]; + for (int i = 0; i < btypes.length; i++) { + btypes[i] = basicType(types.get(i)); + } + return btypes; + } + static BasicType[] basicTypes(String types) { + BasicType[] btypes = new BasicType[types.length()]; + for (int i = 0; i < btypes.length; i++) { + btypes[i] = basicType(types.charAt(i)); + } + return btypes; + } + static boolean isBasicTypeChar(char c) { + return "LIJFDV".indexOf(c) >= 0; + } + static boolean isArgBasicTypeChar(char c) { + return "LIJFD".indexOf(c) >= 0; + } + + static { assert(checkBasicType()); } + private static boolean checkBasicType() { + for (int i = 0; i < ARG_TYPE_LIMIT; i++) { + assert ARG_TYPES[i].ordinal() == i; + assert ARG_TYPES[i] == ALL_TYPES[i]; + } + for (int i = 0; i < TYPE_LIMIT; i++) { + assert ALL_TYPES[i].ordinal() == i; + } + assert ALL_TYPES[TYPE_LIMIT - 1] == V_TYPE; + assert !Arrays.asList(ARG_TYPES).contains(V_TYPE); + return true; + } + } + LambdaForm(String debugName, int arity, Name[] names, int result) { assert(namesOK(arity, names)); this.arity = arity; this.result = fixResult(result, names); this.names = names.clone(); - this.debugName = debugName; + this.debugName = fixDebugName(debugName); normalize(); } @@ -168,12 +274,12 @@ class LambdaForm { // Called only from getPreparedForm. assert(isValidSignature(sig)); this.arity = signatureArity(sig); - this.result = (signatureReturn(sig) == 'V' ? -1 : arity); + this.result = (signatureReturn(sig) == V_TYPE ? -1 : arity); this.names = buildEmptyNames(arity, sig); this.debugName = "LF.zero"; assert(nameRefsAreLegal()); assert(isEmpty()); - assert(sig.equals(basicTypeSignature())); + assert(sig.equals(basicTypeSignature())) : sig + " != " + basicTypeSignature(); } private static Name[] buildEmptyNames(int arity, String basicTypeSignature) { @@ -181,24 +287,55 @@ class LambdaForm { int resultPos = arity + 1; // skip '_' if (arity < 0 || basicTypeSignature.length() != resultPos+1) throw new IllegalArgumentException("bad arity for "+basicTypeSignature); - int numRes = (basicTypeSignature.charAt(resultPos) == 'V' ? 0 : 1); + int numRes = (basicType(basicTypeSignature.charAt(resultPos)) == V_TYPE ? 0 : 1); Name[] names = arguments(numRes, basicTypeSignature.substring(0, arity)); for (int i = 0; i < numRes; i++) { - names[arity + i] = constantZero(arity + i, basicTypeSignature.charAt(resultPos + i)); + Name zero = new Name(constantZero(basicType(basicTypeSignature.charAt(resultPos + i)))); + names[arity + i] = zero.newIndex(arity + i); } return names; } private static int fixResult(int result, Name[] names) { - if (result >= 0) { - if (names[result].type == 'V') - return -1; - } else if (result == LAST_RESULT) { - return names.length - 1; - } + if (result == LAST_RESULT) + result = names.length - 1; // might still be void + if (result >= 0 && names[result].type == V_TYPE) + result = VOID_RESULT; return result; } + private static String fixDebugName(String debugName) { + if (DEBUG_NAME_COUNTERS != null) { + int under = debugName.indexOf('_'); + int length = debugName.length(); + if (under < 0) under = length; + String debugNameStem = debugName.substring(0, under); + Integer ctr; + synchronized (DEBUG_NAME_COUNTERS) { + ctr = DEBUG_NAME_COUNTERS.get(debugNameStem); + if (ctr == null) ctr = 0; + DEBUG_NAME_COUNTERS.put(debugNameStem, ctr+1); + } + StringBuilder buf = new StringBuilder(debugNameStem); + buf.append('_'); + int leadingZero = buf.length(); + buf.append((int) ctr); + for (int i = buf.length() - leadingZero; i < 3; i++) + buf.insert(leadingZero, '0'); + if (under < length) { + ++under; // skip "_" + while (under < length && Character.isDigit(debugName.charAt(under))) { + ++under; + } + if (under < length && debugName.charAt(under) == '_') ++under; + if (under < length) + buf.append('_').append(debugName, under, length); + } + return buf.toString(); + } + return debugName; + } + private static boolean namesOK(int arity, Name[] names) { for (int i = 0; i < names.length; i++) { Name n = names[i]; @@ -294,14 +431,14 @@ class LambdaForm { // } /** Report the return type. */ - char returnType() { - if (result < 0) return 'V'; + BasicType returnType() { + if (result < 0) return V_TYPE; Name n = names[result]; return n.type; } /** Report the N-th argument type. */ - char parameterType(int n) { + BasicType parameterType(int n) { assert(n < arity); return names[n].type; } @@ -319,15 +456,15 @@ class LambdaForm { final String basicTypeSignature() { StringBuilder buf = new StringBuilder(arity() + 3); for (int i = 0, a = arity(); i < a; i++) - buf.append(parameterType(i)); - return buf.append('_').append(returnType()).toString(); + buf.append(parameterType(i).basicTypeChar()); + return buf.append('_').append(returnType().basicTypeChar()).toString(); } static int signatureArity(String sig) { assert(isValidSignature(sig)); return sig.indexOf('_'); } - static char signatureReturn(String sig) { - return sig.charAt(signatureArity(sig)+1); + static BasicType signatureReturn(String sig) { + return basicType(sig.charAt(signatureArity(sig)+1)); } static boolean isValidSignature(String sig) { int arity = sig.indexOf('_'); @@ -339,27 +476,15 @@ class LambdaForm { char c = sig.charAt(i); if (c == 'V') return (i == siglen - 1 && arity == siglen - 2); - if (ALL_TYPES.indexOf(c) < 0) return false; // must be [LIJFD] + if (!isArgBasicTypeChar(c)) return false; // must be [LIJFD] } return true; // [LIJFD]*_[LIJFDV] } - static Class typeClass(char t) { - switch (t) { - case 'I': return int.class; - case 'J': return long.class; - case 'F': return float.class; - case 'D': return double.class; - case 'L': return Object.class; - case 'V': return void.class; - default: assert false; - } - return null; - } static MethodType signatureType(String sig) { Class[] ptypes = new Class[signatureArity(sig)]; for (int i = 0; i < ptypes.length; i++) - ptypes[i] = typeClass(sig.charAt(i)); - Class rtype = typeClass(signatureReturn(sig)); + ptypes[i] = basicType(sig.charAt(i)).btClass; + Class rtype = signatureReturn(sig).btClass; return MethodType.methodType(rtype, ptypes); } @@ -543,21 +668,21 @@ class LambdaForm { assert(mt.parameterCount() == arity-1); for (int i = 0; i < av.length; i++) { Class pt = (i == 0 ? MethodHandle.class : mt.parameterType(i-1)); - assert(valueMatches(sig.charAt(i), pt, av[i])); + assert(valueMatches(basicType(sig.charAt(i)), pt, av[i])); } return true; } - private static boolean valueMatches(char tc, Class type, Object x) { + private static boolean valueMatches(BasicType tc, Class type, Object x) { // The following line is needed because (...)void method handles can use non-void invokers - if (type == void.class) tc = 'V'; // can drop any kind of value + if (type == void.class) tc = V_TYPE; // can drop any kind of value assert tc == basicType(type) : tc + " == basicType(" + type + ")=" + basicType(type); switch (tc) { - case 'I': assert checkInt(type, x) : "checkInt(" + type + "," + x +")"; break; - case 'J': assert x instanceof Long : "instanceof Long: " + x; break; - case 'F': assert x instanceof Float : "instanceof Float: " + x; break; - case 'D': assert x instanceof Double : "instanceof Double: " + x; break; - case 'L': assert checkRef(type, x) : "checkRef(" + type + "," + x + ")"; break; - case 'V': break; // allow anything here; will be dropped + case I_TYPE: assert checkInt(type, x) : "checkInt(" + type + "," + x +")"; break; + case J_TYPE: assert x instanceof Long : "instanceof Long: " + x; break; + case F_TYPE: assert x instanceof Float : "instanceof Float: " + x; break; + case D_TYPE: assert x instanceof Double : "instanceof Double: " + x; break; + case L_TYPE: assert checkRef(type, x) : "checkRef(" + type + "," + x + ")"; break; + case V_TYPE: break; // allow anything here; will be dropped default: assert(false); } return true; @@ -736,7 +861,7 @@ class LambdaForm { * The first parameter to a LambdaForm, a0:L, always represents the form's method handle, so 0 is not * accepted as valid. */ - LambdaForm bindImmediate(int pos, char basicType, Object value) { + LambdaForm bindImmediate(int pos, BasicType basicType, Object value) { // must be an argument, and the types must match assert pos > 0 && pos < arity && names[pos].type == basicType && Name.typesMatch(basicType, value); @@ -782,8 +907,8 @@ class LambdaForm { LambdaForm bind(int namePos, BoundMethodHandle.SpeciesData oldData) { Name name = names[namePos]; - BoundMethodHandle.SpeciesData newData = oldData.extendWithType(name.type); - return bind(name, newData.getterName(names[0], oldData.fieldCount()), oldData, newData); + BoundMethodHandle.SpeciesData newData = oldData.extendWith(name.type); + return bind(name, new Name(newData.getterFunction(oldData.fieldCount()), names[0]), oldData, newData); } LambdaForm bind(Name name, Name binding, BoundMethodHandle.SpeciesData oldData, @@ -874,7 +999,7 @@ class LambdaForm { return false; } - LambdaForm addArguments(int pos, char... types) { + LambdaForm addArguments(int pos, BasicType... types) { assert(pos <= arity); int length = names.length; int inTypes = types.length; @@ -895,13 +1020,10 @@ class LambdaForm { } LambdaForm addArguments(int pos, List> types) { - char[] basicTypes = new char[types.size()]; - for (int i = 0; i < basicTypes.length; i++) - basicTypes[i] = basicType(types.get(i)); - return addArguments(pos, basicTypes); + return addArguments(pos, basicTypes(types)); } - LambdaForm permuteArguments(int skip, int[] reorder, char[] types) { + LambdaForm permuteArguments(int skip, int[] reorder, BasicType[] types) { // Note: When inArg = reorder[outArg], outArg is fed by a copy of inArg. // The types are the types of the new (incoming) arguments. int length = names.length; @@ -960,7 +1082,7 @@ class LambdaForm { return new LambdaForm(debugName, arity2, names2, result2); } - static boolean permutedTypesMatch(int[] reorder, char[] types, Name[] names, int skip) { + static boolean permutedTypesMatch(int[] reorder, BasicType[] types, Name[] names, int skip) { int inTypes = types.length; int outArgs = reorder.length; for (int i = 0; i < outArgs; i++) { @@ -1044,7 +1166,7 @@ class LambdaForm { String sig = m.getName().substring("invoke_".length()); int arity = LambdaForm.signatureArity(sig); MethodType srcType = MethodType.genericMethodType(arity); - if (LambdaForm.signatureReturn(sig) == 'V') + if (LambdaForm.signatureReturn(sig) == V_TYPE) srcType = srcType.changeReturnType(void.class); MethodTypeForm typeForm = srcType.form(); typeForm.namedFunctionInvoker = DirectMethodHandle.make(m); @@ -1134,7 +1256,7 @@ class LambdaForm { MethodHandle mh2 = typeForm.namedFunctionInvoker; if (mh2 != null) return mh2; // benign race if (!mh.type().equals(INVOKER_METHOD_TYPE)) - throw new InternalError(mh.debugString()); + throw newInternalError(mh.debugString()); return typeForm.namedFunctionInvoker = mh; } @@ -1193,11 +1315,6 @@ class LambdaForm { return true; } - String basicTypeSignature() { - //return LambdaForm.basicTypeSignature(resolvedHandle.type()); - return LambdaForm.basicTypeSignature(methodType()); - } - MethodType methodType() { if (resolvedHandle != null) return resolvedHandle.type(); @@ -1224,18 +1341,15 @@ class LambdaForm { return (member == null) ? null : member.getDeclaringClass(); } - char returnType() { + BasicType returnType() { return basicType(methodType().returnType()); } - char parameterType(int n) { + BasicType parameterType(int n) { return basicType(methodType().parameterType(n)); } int arity() { - //int siglen = member.getMethodType().parameterCount(); - //if (!member.isStatic()) siglen += 1; - //return siglen; return methodType().parameterCount(); } @@ -1243,44 +1357,63 @@ class LambdaForm { if (member == null) return String.valueOf(resolvedHandle); return member.getDeclaringClass().getSimpleName()+"."+member.getName(); } - } - void resolve() { - for (Name n : names) n.resolve(); - } - - public static char basicType(Class type) { - char c = Wrapper.basicTypeChar(type); - if ("ZBSC".indexOf(c) >= 0) c = 'I'; - assert("LIJFDV".indexOf(c) >= 0); - return c; - } - public static char[] basicTypes(List> types) { - char[] btypes = new char[types.size()]; - for (int i = 0; i < btypes.length; i++) { - btypes[i] = basicType(types.get(i)); + public boolean isIdentity() { + return this.equals(identity(returnType())); + } + + public boolean isConstantZero() { + return this.equals(constantZero(returnType())); } - return btypes; } + public static String basicTypeSignature(MethodType type) { char[] sig = new char[type.parameterCount() + 2]; int sigp = 0; for (Class pt : type.parameterList()) { - sig[sigp++] = basicType(pt); + sig[sigp++] = basicTypeChar(pt); } sig[sigp++] = '_'; - sig[sigp++] = basicType(type.returnType()); + sig[sigp++] = basicTypeChar(type.returnType()); assert(sigp == sig.length); return String.valueOf(sig); } + public static String shortenSignature(String signature) { + // Hack to make signatures more readable when they show up in method names. + final int NO_CHAR = -1, MIN_RUN = 3; + int c0, c1 = NO_CHAR, c1reps = 0; + StringBuilder buf = null; + int len = signature.length(); + if (len < MIN_RUN) return signature; + for (int i = 0; i <= len; i++) { + // shift in the next char: + c0 = c1; c1 = (i == len ? NO_CHAR : signature.charAt(i)); + if (c1 == c0) { ++c1reps; continue; } + // shift in the next count: + int c0reps = c1reps; c1reps = 1; + // end of a character run + if (c0reps < MIN_RUN) { + if (buf != null) { + while (--c0reps >= 0) + buf.append((char)c0); + } + continue; + } + // found three or more in a row + if (buf == null) + buf = new StringBuilder().append(signature, 0, i - c0reps); + buf.append((char)c0).append(c0reps); + } + return (buf == null) ? signature : buf.toString(); + } static final class Name { - final char type; + final BasicType type; private short index; final NamedFunction function; @Stable final Object[] arguments; - private Name(int index, char type, NamedFunction function, Object[] arguments) { + private Name(int index, BasicType type, NamedFunction function, Object[] arguments) { this.index = (short)index; this.type = type; this.function = function; @@ -1292,7 +1425,7 @@ class LambdaForm { } Name(MethodType functionType, Object... arguments) { this(new NamedFunction(functionType), arguments); - assert(arguments[0] instanceof Name && ((Name)arguments[0]).type == 'L'); + assert(arguments[0] instanceof Name && ((Name)arguments[0]).type == L_TYPE); } Name(MemberName function, Object... arguments) { this(new NamedFunction(function), arguments); @@ -1303,14 +1436,14 @@ class LambdaForm { for (int i = 0; i < arguments.length; i++) assert(typesMatch(function.parameterType(i), arguments[i])) : "types don't match: function.parameterType(" + i + ")=" + function.parameterType(i) + ", arguments[" + i + "]=" + arguments[i] + " in " + debugString(); } - Name(int index, char type) { + /** Create a raw parameter of the given type, with an expected index. */ + Name(int index, BasicType type) { this(index, type, null, null); } - Name(char type) { - this(-1, type); - } + /** Create a raw parameter of the given type. */ + Name(BasicType type) { this(-1, type); } - char type() { return type; } + BasicType type() { return type; } int index() { return index; } boolean initIndex(int i) { if (index != i) { @@ -1319,7 +1452,9 @@ class LambdaForm { } return true; } - + char typeChar() { + return type.btChar; + } void resolve() { if (function != null) @@ -1397,18 +1532,18 @@ class LambdaForm { return function == null; } boolean isConstantZero() { - return !isParam() && arguments.length == 0 && function.equals(constantZero(0, type).function); + return !isParam() && arguments.length == 0 && function.isConstantZero(); } public String toString() { - return (isParam()?"a":"t")+(index >= 0 ? index : System.identityHashCode(this))+":"+type; + return (isParam()?"a":"t")+(index >= 0 ? index : System.identityHashCode(this))+":"+typeChar(); } public String debugString() { String s = toString(); return (function == null) ? s : s + "=" + exprString(); } public String exprString() { - if (function == null) return "null"; + if (function == null) return toString(); StringBuilder buf = new StringBuilder(function.toString()); buf.append("("); String cma = ""; @@ -1423,17 +1558,17 @@ class LambdaForm { return buf.toString(); } - private static boolean typesMatch(char parameterType, Object object) { + static boolean typesMatch(BasicType parameterType, Object object) { if (object instanceof Name) { return ((Name)object).type == parameterType; } switch (parameterType) { - case 'I': return object instanceof Integer; - case 'J': return object instanceof Long; - case 'F': return object instanceof Float; - case 'D': return object instanceof Double; + case I_TYPE: return object instanceof Integer; + case J_TYPE: return object instanceof Long; + case F_TYPE: return object instanceof Float; + case D_TYPE: return object instanceof Double; } - assert(parameterType == 'L'); + assert(parameterType == L_TYPE); return true; } @@ -1510,7 +1645,7 @@ class LambdaForm { @Override public int hashCode() { if (isParam()) - return index | (type << 8); + return index | (type.ordinal() << 8); return function.hashCode() ^ Arrays.hashCode(arguments); } } @@ -1545,10 +1680,12 @@ class LambdaForm { } static Name argument(int which, char type) { - int tn = ALL_TYPES.indexOf(type); - if (tn < 0 || which >= INTERNED_ARGUMENT_LIMIT) + return argument(which, basicType(type)); + } + static Name argument(int which, BasicType type) { + if (which >= INTERNED_ARGUMENT_LIMIT) return new Name(which, type); - return INTERNED_ARGUMENTS[tn][which]; + return INTERNED_ARGUMENTS[type.ordinal()][which]; } static Name internArgument(Name n) { assert(n.isParam()) : "not param: " + n; @@ -1590,56 +1727,118 @@ class LambdaForm { names[i] = argument(i, basicType(types.parameterType(i))); return names; } - static final String ALL_TYPES = "LIJFD"; // omit V, not an argument type static final int INTERNED_ARGUMENT_LIMIT = 10; private static final Name[][] INTERNED_ARGUMENTS - = new Name[ALL_TYPES.length()][INTERNED_ARGUMENT_LIMIT]; + = new Name[ARG_TYPE_LIMIT][INTERNED_ARGUMENT_LIMIT]; static { - for (int tn = 0; tn < ALL_TYPES.length(); tn++) { - for (int i = 0; i < INTERNED_ARGUMENTS[tn].length; i++) { - char type = ALL_TYPES.charAt(tn); - INTERNED_ARGUMENTS[tn][i] = new Name(i, type); + for (BasicType type : BasicType.ARG_TYPES) { + int ord = type.ordinal(); + for (int i = 0; i < INTERNED_ARGUMENTS[ord].length; i++) { + INTERNED_ARGUMENTS[ord][i] = new Name(i, type); } } } private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); - static Name constantZero(int which, char type) { - return CONSTANT_ZERO[ALL_TYPES.indexOf(type)].newIndex(which); + static LambdaForm identityForm(BasicType type) { + return LF_identityForm[type.ordinal()]; } - private static final Name[] CONSTANT_ZERO - = new Name[ALL_TYPES.length()]; - static { - for (int tn = 0; tn < ALL_TYPES.length(); tn++) { - char bt = ALL_TYPES.charAt(tn); - Wrapper wrap = Wrapper.forBasicType(bt); - MemberName zmem = new MemberName(LambdaForm.class, "zero"+bt, MethodType.methodType(wrap.primitiveType()), REF_invokeStatic); + static LambdaForm zeroForm(BasicType type) { + return LF_zeroForm[type.ordinal()]; + } + static NamedFunction identity(BasicType type) { + return NF_identity[type.ordinal()]; + } + static NamedFunction constantZero(BasicType type) { + return NF_zero[type.ordinal()]; + } + private static final LambdaForm[] LF_identityForm = new LambdaForm[TYPE_LIMIT]; + private static final LambdaForm[] LF_zeroForm = new LambdaForm[TYPE_LIMIT]; + private static final NamedFunction[] NF_identity = new NamedFunction[TYPE_LIMIT]; + private static final NamedFunction[] NF_zero = new NamedFunction[TYPE_LIMIT]; + private static void createIdentityForms() { + for (BasicType type : BasicType.ALL_TYPES) { + int ord = type.ordinal(); + char btChar = type.basicTypeChar(); + boolean isVoid = (type == V_TYPE); + Class btClass = type.btClass; + MethodType zeType = MethodType.methodType(btClass); + MethodType idType = isVoid ? zeType : zeType.appendParameterTypes(btClass); + + // Look up some symbolic names. It might not be necessary to have these, + // but if we need to emit direct references to bytecodes, it helps. + // Zero is built from a call to an identity function with a constant zero input. + MemberName idMem = new MemberName(LambdaForm.class, "identity_"+btChar, idType, REF_invokeStatic); + MemberName zeMem = new MemberName(LambdaForm.class, "zero_"+btChar, zeType, REF_invokeStatic); try { - zmem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, zmem, null, NoSuchMethodException.class); + zeMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, zeMem, null, NoSuchMethodException.class); + idMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, idMem, null, NoSuchMethodException.class); } catch (IllegalAccessException|NoSuchMethodException ex) { throw newInternalError(ex); } - NamedFunction zcon = new NamedFunction(zmem); - Name n = new Name(zcon).newIndex(0); - assert(n.type == ALL_TYPES.charAt(tn)); - CONSTANT_ZERO[tn] = n; - assert(n.isConstantZero()); + + NamedFunction idFun = new NamedFunction(idMem); + LambdaForm idForm; + if (isVoid) { + Name[] idNames = new Name[] { argument(0, L_TYPE) }; + idForm = new LambdaForm(idMem.getName(), 1, idNames, VOID_RESULT); + } else { + Name[] idNames = new Name[] { argument(0, L_TYPE), argument(1, type) }; + idForm = new LambdaForm(idMem.getName(), 2, idNames, 1); + } + LF_identityForm[ord] = idForm; + NF_identity[ord] = idFun; + + NamedFunction zeFun = new NamedFunction(zeMem); + LambdaForm zeForm; + if (isVoid) { + zeForm = idForm; + } else { + Object zeValue = Wrapper.forBasicType(btChar).zero(); + Name[] zeNames = new Name[] { argument(0, L_TYPE), new Name(idFun, zeValue) }; + zeForm = new LambdaForm(zeMem.getName(), 1, zeNames, 1); + } + LF_zeroForm[ord] = zeForm; + NF_zero[ord] = zeFun; + + assert(idFun.isIdentity()); + assert(zeFun.isConstantZero()); + assert(new Name(zeFun).isConstantZero()); + } + + // Do this in a separate pass, so that SimpleMethodHandle.make can see the tables. + for (BasicType type : BasicType.ALL_TYPES) { + int ord = type.ordinal(); + NamedFunction idFun = NF_identity[ord]; + LambdaForm idForm = LF_identityForm[ord]; + MemberName idMem = idFun.member; + idFun.resolvedHandle = SimpleMethodHandle.make(idMem.getInvocationType(), idForm); + + NamedFunction zeFun = NF_zero[ord]; + LambdaForm zeForm = LF_zeroForm[ord]; + MemberName zeMem = zeFun.member; + zeFun.resolvedHandle = SimpleMethodHandle.make(zeMem.getInvocationType(), zeForm); + + assert(idFun.isIdentity()); + assert(zeFun.isConstantZero()); + assert(new Name(zeFun).isConstantZero()); } } // Avoid appealing to ValueConversions at bootstrap time: - private static int zeroI() { return 0; } - private static long zeroJ() { return 0; } - private static float zeroF() { return 0; } - private static double zeroD() { return 0; } - private static Object zeroL() { return null; } - - // Put this last, so that previous static inits can run before. - static { - if (USE_PREDEFINED_INTERPRET_METHODS) - PREPARED_FORMS.putAll(computeInitialPreparedForms()); - } + private static int identity_I(int x) { return x; } + private static long identity_J(long x) { return x; } + private static float identity_F(float x) { return x; } + private static double identity_D(double x) { return x; } + private static Object identity_L(Object x) { return x; } + private static void identity_V() { return; } // same as zeroV, but that's OK + private static int zero_I() { return 0; } + private static long zero_J() { return 0; } + private static float zero_F() { return 0; } + private static double zero_D() { return 0; } + private static Object zero_L() { return null; } + private static void zero_V() { return; } /** * Internal marker for byte-compiled LambdaForms. @@ -1690,7 +1889,21 @@ class LambdaForm { static final native Object linkToInterface(Object x1, MemberName mn) throws Throwable; */ - static { NamedFunction.initializeInvokers(); } + private static final HashMap DEBUG_NAME_COUNTERS; + static { + if (debugEnabled()) + DEBUG_NAME_COUNTERS = new HashMap<>(); + else + DEBUG_NAME_COUNTERS = null; + } + + // Put this last, so that previous static inits can run before. + static { + createIdentityForms(); + if (USE_PREDEFINED_INTERPRET_METHODS) + PREPARED_FORMS.putAll(computeInitialPreparedForms()); + NamedFunction.initializeInvokers(); + } // The following hack is necessary in order to suppress TRACE_INTERPRETER // during execution of the static initializes of this class. diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandle.java b/jdk/src/share/classes/java/lang/invoke/MethodHandle.java index f142076f528..19664528f26 100644 --- a/jdk/src/share/classes/java/lang/invoke/MethodHandle.java +++ b/jdk/src/share/classes/java/lang/invoke/MethodHandle.java @@ -27,10 +27,12 @@ package java.lang.invoke; import java.util.*; +import java.lang.invoke.LambdaForm.BasicType; import sun.invoke.util.*; import sun.misc.Unsafe; import static java.lang.invoke.MethodHandleStatics.*; +import static java.lang.invoke.LambdaForm.BasicType.*; /** * A method handle is a typed, directly executable reference to an underlying method, @@ -729,7 +731,7 @@ public abstract class MethodHandle { *
  • If the return type T0 is void and T1 a primitive, * a zero value is introduced. * - * (Note: Both T0 and T1 may be regarded as static types, + * (Note: Both T0 and T1 may be regarded as static types, * because neither corresponds specifically to the dynamic type of any * actual argument or return value.) *

    @@ -1374,7 +1376,7 @@ assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString()); } /*non-public*/ - MethodHandle bindArgument(int pos, char basicType, Object value) { + MethodHandle bindArgument(int pos, BasicType basicType, Object value) { // Override this if it can be improved. return rebind().bindArgument(pos, basicType, value); } @@ -1382,26 +1384,7 @@ assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString()); /*non-public*/ MethodHandle bindReceiver(Object receiver) { // Override this if it can be improved. - return bindArgument(0, 'L', receiver); - } - - /*non-public*/ - MethodHandle bindImmediate(int pos, char basicType, Object value) { - // Bind an immediate value to a position in the arguments. - // This means, elide the respective argument, - // and replace all references to it in NamedFunction args with the specified value. - - // CURRENT RESTRICTIONS - // * only for pos 0 and UNSAFE (position is adjusted in MHImpl to make API usable for others) - assert pos == 0 && basicType == 'L' && value instanceof Unsafe; - MethodType type2 = type.dropParameterTypes(pos, pos + 1); // adjustment: ignore receiver! - LambdaForm form2 = form.bindImmediate(pos + 1, basicType, value); // adjust pos to form-relative pos - return copyWith(type2, form2); - } - - /*non-public*/ - MethodHandle copyWith(MethodType mt, LambdaForm lf) { - throw new InternalError("copyWith: " + this.getClass()); + return bindArgument(0, L_TYPE, receiver); } /*non-public*/ diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java b/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java index cdf6e5a75ce..6abceb5ad19 100644 --- a/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java +++ b/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java @@ -412,7 +412,7 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; @Override - MethodHandle bindArgument(int pos, char basicType, Object value) { + MethodHandle bindArgument(int pos, BasicType basicType, Object value) { return asFixedArity().bindArgument(pos, basicType, value); } diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandleNatives.java b/jdk/src/share/classes/java/lang/invoke/MethodHandleNatives.java index fd5cac8cd7b..0f5169e95e2 100644 --- a/jdk/src/share/classes/java/lang/invoke/MethodHandleNatives.java +++ b/jdk/src/share/classes/java/lang/invoke/MethodHandleNatives.java @@ -78,7 +78,7 @@ class MethodHandleNatives { // The JVM calls MethodHandleNatives.. Cascade the calls as needed: MethodHandleImpl.initStatics(); -} + } // All compile-time constants go here. // There is an opportunity to check them against the JVM's idea of them. @@ -293,6 +293,17 @@ class MethodHandleNatives { Class caller = (Class)callerObj; String name = nameObj.toString().intern(); MethodType type = (MethodType)typeObj; + if (!TRACE_METHOD_LINKAGE) + return linkCallSiteImpl(caller, bootstrapMethod, name, type, + staticArguments, appendixResult); + return linkCallSiteTracing(caller, bootstrapMethod, name, type, + staticArguments, appendixResult); + } + static MemberName linkCallSiteImpl(Class caller, + MethodHandle bootstrapMethod, + String name, MethodType type, + Object staticArguments, + Object[] appendixResult) { CallSite callSite = CallSite.makeSite(bootstrapMethod, name, type, @@ -306,6 +317,30 @@ class MethodHandleNatives { return Invokers.linkToCallSiteMethod(type); } } + // Tracing logic: + static MemberName linkCallSiteTracing(Class caller, + MethodHandle bootstrapMethod, + String name, MethodType type, + Object staticArguments, + Object[] appendixResult) { + Object bsmReference = bootstrapMethod.internalMemberName(); + if (bsmReference == null) bsmReference = bootstrapMethod; + Object staticArglist = (staticArguments instanceof Object[] ? + java.util.Arrays.asList((Object[]) staticArguments) : + staticArguments); + System.out.println("linkCallSite "+caller.getName()+" "+ + bsmReference+" "+ + name+type+"/"+staticArglist); + try { + MemberName res = linkCallSiteImpl(caller, bootstrapMethod, name, type, + staticArguments, appendixResult); + System.out.println("linkCallSite => "+res+" + "+appendixResult[0]); + return res; + } catch (Throwable ex) { + System.out.println("linkCallSite => throw "+ex); + throw ex; + } + } /** * The JVM wants a pointer to a MethodType. Oblige it by finding or creating one. diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandleStatics.java b/jdk/src/share/classes/java/lang/invoke/MethodHandleStatics.java index 8a8eedfe1bf..50a14b35d52 100644 --- a/jdk/src/share/classes/java/lang/invoke/MethodHandleStatics.java +++ b/jdk/src/share/classes/java/lang/invoke/MethodHandleStatics.java @@ -65,6 +65,16 @@ import sun.misc.Unsafe; COMPILE_THRESHOLD = (Integer) values[4]; } + /** Tell if any of the debugging switches are turned on. + * If this is the case, it is reasonable to perform extra checks or save extra information. + */ + /*non-public*/ static boolean debugEnabled() { + return (DEBUG_METHOD_HANDLE_NAMES | + DUMP_CLASS_FILES | + TRACE_INTERPRETER | + TRACE_METHOD_LINKAGE); + } + /*non-public*/ static String getNameString(MethodHandle target, MethodType type) { if (type == null) type = target.type(); @@ -93,6 +103,9 @@ import sun.misc.Unsafe; } // handy shared exception makers (they simplify the common case code) + /*non-public*/ static InternalError newInternalError(String message) { + return new InternalError(message); + } /*non-public*/ static InternalError newInternalError(String message, Throwable cause) { return new InternalError(message, cause); } diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java index 834650c84fa..48a937c1998 100644 --- a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java +++ b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java @@ -37,10 +37,11 @@ import sun.reflect.CallerSensitive; import sun.reflect.Reflection; import sun.reflect.misc.ReflectUtil; import sun.security.util.SecurityConstants; +import java.lang.invoke.LambdaForm.BasicType; +import static java.lang.invoke.LambdaForm.BasicType.*; import static java.lang.invoke.MethodHandleStatics.*; import static java.lang.invoke.MethodHandleNatives.Constants.*; import java.util.concurrent.ConcurrentHashMap; -import sun.security.util.SecurityConstants; /** * This class consists exclusively of static methods that operate on or return @@ -2189,12 +2190,12 @@ assert((int)twice.invokeExact(21) == 42); Object value = values[i]; Class ptype = oldType.parameterType(pos+i); if (ptype.isPrimitive()) { - char btype = 'I'; + BasicType btype = I_TYPE; Wrapper w = Wrapper.forPrimitiveType(ptype); switch (w) { - case LONG: btype = 'J'; break; - case FLOAT: btype = 'F'; break; - case DOUBLE: btype = 'D'; break; + case LONG: btype = J_TYPE; break; + case FLOAT: btype = F_TYPE; break; + case DOUBLE: btype = D_TYPE; break; } // perform unboxing and/or primitive conversion value = w.convert(value, ptype); @@ -2205,7 +2206,7 @@ assert((int)twice.invokeExact(21) == 42); if (pos == 0) { result = result.bindReceiver(value); } else { - result = result.bindArgument(pos, 'L', value); + result = result.bindArgument(pos, L_TYPE, value); } } return result; diff --git a/jdk/src/share/classes/java/lang/invoke/SimpleMethodHandle.java b/jdk/src/share/classes/java/lang/invoke/SimpleMethodHandle.java index 07f08dd6962..752505ee68e 100644 --- a/jdk/src/share/classes/java/lang/invoke/SimpleMethodHandle.java +++ b/jdk/src/share/classes/java/lang/invoke/SimpleMethodHandle.java @@ -26,7 +26,7 @@ package java.lang.invoke; import static java.lang.invoke.LambdaForm.*; -import static java.lang.invoke.MethodHandleNatives.Constants.*; +import static java.lang.invoke.LambdaForm.BasicType.*; /** * A method handle whose behavior is determined only by its LambdaForm. @@ -42,7 +42,7 @@ final class SimpleMethodHandle extends MethodHandle { } @Override - MethodHandle bindArgument(int pos, char basicType, Object value) { + MethodHandle bindArgument(int pos, BasicType basicType, Object value) { MethodType type2 = type().dropParameterTypes(pos, pos+1); LambdaForm form2 = internalForm().bind(1+pos, BoundMethodHandle.SpeciesData.EMPTY); return BoundMethodHandle.bindSingle(type2, form2, basicType, value); @@ -59,10 +59,4 @@ final class SimpleMethodHandle extends MethodHandle { LambdaForm form2 = internalForm().permuteArguments(1, reorder, basicTypes(newType.parameterList())); return new SimpleMethodHandle(newType, form2); } - - @Override - MethodHandle copyWith(MethodType mt, LambdaForm lf) { - return new SimpleMethodHandle(mt, lf); - } - } diff --git a/jdk/src/share/classes/java/util/DoubleSummaryStatistics.java b/jdk/src/share/classes/java/util/DoubleSummaryStatistics.java index 222d9672d29..569c35899bc 100644 --- a/jdk/src/share/classes/java/util/DoubleSummaryStatistics.java +++ b/jdk/src/share/classes/java/util/DoubleSummaryStatistics.java @@ -54,7 +54,7 @@ import java.util.stream.Collector; * * @implNote This implementation is not thread safe. However, it is safe to use * {@link java.util.stream.Collectors#summarizingDouble(java.util.function.ToDoubleFunction) - * Collectors.toDoubleStatistics()} on a parallel stream, because the parallel + * Collectors.summarizingDouble()} on a parallel stream, because the parallel * implementation of {@link java.util.stream.Stream#collect Stream.collect()} * provides the necessary partitioning, isolation, and merging of results for * safe and efficient parallel execution. diff --git a/jdk/src/share/classes/java/util/IntSummaryStatistics.java b/jdk/src/share/classes/java/util/IntSummaryStatistics.java index f93436e7017..3a38b91f981 100644 --- a/jdk/src/share/classes/java/util/IntSummaryStatistics.java +++ b/jdk/src/share/classes/java/util/IntSummaryStatistics.java @@ -54,7 +54,7 @@ import java.util.stream.Collector; * * @implNote This implementation is not thread safe. However, it is safe to use * {@link java.util.stream.Collectors#summarizingInt(java.util.function.ToIntFunction) - * Collectors.toIntStatistics()} on a parallel stream, because the parallel + * Collectors.summarizingInt()} on a parallel stream, because the parallel * implementation of {@link java.util.stream.Stream#collect Stream.collect()} * provides the necessary partitioning, isolation, and merging of results for * safe and efficient parallel execution. diff --git a/jdk/src/share/classes/java/util/LongSummaryStatistics.java b/jdk/src/share/classes/java/util/LongSummaryStatistics.java index 085aa298075..d1a7de7aa36 100644 --- a/jdk/src/share/classes/java/util/LongSummaryStatistics.java +++ b/jdk/src/share/classes/java/util/LongSummaryStatistics.java @@ -42,7 +42,7 @@ import java.util.stream.Collector; * } * *

    {@code LongSummaryStatistics} can be used as a - * {@linkplain java.util.stream.Stream#collect(Collector)} reduction} + * {@linkplain java.util.stream.Stream#collect(Collector) reduction} * target for a {@linkplain java.util.stream.Stream stream}. For example: * *

     {@code
    @@ -55,7 +55,7 @@ import java.util.stream.Collector;
      *
      * @implNote This implementation is not thread safe. However, it is safe to use
      * {@link java.util.stream.Collectors#summarizingLong(java.util.function.ToLongFunction)
    - * Collectors.toLongStatistics()} on a parallel stream, because the parallel
    + * Collectors.summarizingLong()} on a parallel stream, because the parallel
      * implementation of {@link java.util.stream.Stream#collect Stream.collect()}
      * provides the necessary partitioning, isolation, and merging of results for
      * safe and efficient parallel execution.
    diff --git a/jdk/src/share/classes/java/util/TimeZone.java b/jdk/src/share/classes/java/util/TimeZone.java
    index 96497939fad..356f33be3e1 100644
    --- a/jdk/src/share/classes/java/util/TimeZone.java
    +++ b/jdk/src/share/classes/java/util/TimeZone.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 1996, 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
    @@ -591,8 +591,7 @@ abstract public class TimeZone implements Serializable, Cloneable {
         /**
          * Gets the platform defined TimeZone ID.
          **/
    -    private static native String getSystemTimeZoneID(String javaHome,
    -                                                     String country);
    +    private static native String getSystemTimeZoneID(String javaHome);
     
         /**
          * Gets the custom time zone ID based on the GMT offset of the
    @@ -650,12 +649,10 @@ abstract public class TimeZone implements Serializable, Cloneable {
             // if the time zone ID is not set (yet), perform the
             // platform to Java time zone ID mapping.
             if (zoneID == null || zoneID.isEmpty()) {
    -            String country = AccessController.doPrivileged(
    -                    new GetPropertyAction("user.country"));
                 String javaHome = AccessController.doPrivileged(
                         new GetPropertyAction("java.home"));
                 try {
    -                zoneID = getSystemTimeZoneID(javaHome, country);
    +                zoneID = getSystemTimeZoneID(javaHome);
                     if (zoneID == null) {
                         zoneID = GMT_ID;
                     }
    diff --git a/jdk/src/share/classes/javax/accessibility/AccessibleContext.java b/jdk/src/share/classes/javax/accessibility/AccessibleContext.java
    index 15f0f7f3983..b7f584b95db 100644
    --- a/jdk/src/share/classes/javax/accessibility/AccessibleContext.java
    +++ b/jdk/src/share/classes/javax/accessibility/AccessibleContext.java
    @@ -25,6 +25,9 @@
     
     package javax.accessibility;
     
    +import sun.awt.AWTAccessor;
    +import sun.awt.AppContext;
    +
     import java.util.Locale;
     import java.beans.PropertyChangeListener;
     import java.beans.PropertyChangeSupport;
    @@ -79,6 +82,26 @@ import java.awt.IllegalComponentStateException;
      */
     public abstract class AccessibleContext {
     
    +    /**
    +     * The AppContext that should be used to dispatch events for this
    +     * AccessibleContext
    +     */
    +    private volatile AppContext targetAppContext;
    +
    +    static {
    +        AWTAccessor.setAccessibleContextAccessor(new AWTAccessor.AccessibleContextAccessor() {
    +            @Override
    +            public void setAppContext(AccessibleContext accessibleContext, AppContext appContext) {
    +                accessibleContext.targetAppContext = appContext;
    +            }
    +
    +            @Override
    +            public AppContext getAppContext(AccessibleContext accessibleContext) {
    +                return accessibleContext.targetAppContext;
    +            }
    +        });
    +    }
    +
        /**
         * Constant used to determine when the accessibleName property has
         * changed.  The old value in the PropertyChangeEvent will be the old
    diff --git a/jdk/src/share/classes/javax/crypto/JceSecurity.java b/jdk/src/share/classes/javax/crypto/JceSecurity.java
    index 7e062462211..fb7052d244d 100644
    --- a/jdk/src/share/classes/javax/crypto/JceSecurity.java
    +++ b/jdk/src/share/classes/javax/crypto/JceSecurity.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 1997, 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
    @@ -216,26 +216,28 @@ final class JceSecurity {
                 new WeakHashMap<>();
     
         /*
    -     * Retuns the CodeBase for the given class.
    +     * Returns the CodeBase for the given class.
          */
         static URL getCodeBase(final Class clazz) {
    -        URL url = codeBaseCacheRef.get(clazz);
    -        if (url == null) {
    -            url = AccessController.doPrivileged(new PrivilegedAction() {
    -                public URL run() {
    -                    ProtectionDomain pd = clazz.getProtectionDomain();
    -                    if (pd != null) {
    -                        CodeSource cs = pd.getCodeSource();
    -                        if (cs != null) {
    -                            return cs.getLocation();
    +        synchronized (codeBaseCacheRef) {
    +            URL url = codeBaseCacheRef.get(clazz);
    +            if (url == null) {
    +                url = AccessController.doPrivileged(new PrivilegedAction() {
    +                    public URL run() {
    +                        ProtectionDomain pd = clazz.getProtectionDomain();
    +                        if (pd != null) {
    +                            CodeSource cs = pd.getCodeSource();
    +                            if (cs != null) {
    +                                return cs.getLocation();
    +                            }
                             }
    +                        return NULL_URL;
                         }
    -                    return NULL_URL;
    -                }
    -            });
    -            codeBaseCacheRef.put(clazz, url);
    +                });
    +                codeBaseCacheRef.put(clazz, url);
    +            }
    +            return (url == NULL_URL) ? null : url;
             }
    -        return (url == NULL_URL) ? null : url;
         }
     
         private static void setupJurisdictionPolicies() throws Exception {
    diff --git a/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java b/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java
    index 7829a900bf2..cc476452126 100644
    --- a/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java
    +++ b/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 1999, 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
    @@ -35,7 +35,7 @@ import javax.sound.sampled.AudioInputStream;
     import javax.sound.sampled.UnsupportedAudioFileException;
     
     /**
    - * Provider for audio file reading services.  Classes providing concrete
    + * Provider for audio file reading services. Classes providing concrete
      * implementations can parse the format information from one or more types of
      * audio file, and can produce audio input streams from files of these types.
      *
    @@ -45,93 +45,106 @@ import javax.sound.sampled.UnsupportedAudioFileException;
     public abstract class AudioFileReader {
     
         /**
    -     * Obtains the audio file format of the input stream provided.  The stream must
    -     * point to valid audio file data.  In general, audio file readers may
    +     * Obtains the audio file format of the input stream provided. The stream
    +     * must point to valid audio file data. In general, audio file readers may
          * need to read some data from the stream before determining whether they
    -     * support it.  These parsers must
    -     * be able to mark the stream, read enough data to determine whether they
    -     * support the stream, and, if not, reset the stream's read pointer to its original
    -     * position.  If the input stream does not support this, this method may fail
    -     * with an IOException.
    -     * @param stream the input stream from which file format information should be
    -     * extracted
    -     * @return an AudioFileFormat object describing the audio file format
    -     * @throws UnsupportedAudioFileException if the stream does not point to valid audio
    -     * file data recognized by the system
    +     * support it. These parsers must be able to mark the stream, read enough
    +     * data to determine whether they support the stream, and, if not, reset the
    +     * stream's read pointer to its original position. If the input stream does
    +     * not support this, this method may fail with an {@code IOException}.
    +     *
    +     * @param  stream the input stream from which file format information should
    +     *         be extracted
    +     * @return an {@code AudioFileFormat} object describing the audio file
    +     *         format
    +     * @throws UnsupportedAudioFileException if the stream does not point to
    +     *         valid audio file data recognized by the system
          * @throws IOException if an I/O exception occurs
          * @see InputStream#markSupported
          * @see InputStream#mark
          */
    -    public abstract AudioFileFormat getAudioFileFormat(InputStream stream) throws UnsupportedAudioFileException, IOException;
    +    public abstract AudioFileFormat getAudioFileFormat(InputStream stream)
    +            throws UnsupportedAudioFileException, IOException;
     
         /**
    -     * Obtains the audio file format of the URL provided.  The URL must
    -     * point to valid audio file data.
    -     * @param url the URL from which file format information should be
    -     * extracted
    -     * @return an AudioFileFormat object describing the audio file format
    -     * @throws UnsupportedAudioFileException if the URL does not point to valid audio
    -     * file data recognized by the system
    +     * Obtains the audio file format of the URL provided. The URL must point to
    +     * valid audio file data.
    +     *
    +     * @param  url the URL from which file format information should be
    +     *         extracted
    +     * @return an {@code AudioFileFormat} object describing the audio file
    +     *         format
    +     * @throws UnsupportedAudioFileException if the URL does not point to valid
    +     *         audio file data recognized by the system
          * @throws IOException if an I/O exception occurs
          */
    -    public abstract AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException;
    +    public abstract AudioFileFormat getAudioFileFormat(URL url)
    +            throws UnsupportedAudioFileException, IOException;
     
         /**
    -     * Obtains the audio file format of the File provided.  The File must
    -     * point to valid audio file data.
    -     * @param file the File from which file format information should be
    -     * extracted
    -     * @return an AudioFileFormat object describing the audio file format
    -     * @throws UnsupportedAudioFileException if the File does not point to valid audio
    -     * file data recognized by the system
    +     * Obtains the audio file format of the {@code File} provided.
    +     * The {@code File} must point to valid audio file data.
    +     *
    +     * @param  file the {@code File} from which file format information
    +     *         should be extracted
    +     * @return an {@code AudioFileFormat} object describing the audio file
    +     *         format
    +     * @throws UnsupportedAudioFileException if the {@code File} does not point
    +     *         to valid audio file data recognized by the system
          * @throws IOException if an I/O exception occurs
          */
    -    public abstract AudioFileFormat getAudioFileFormat(File file) throws UnsupportedAudioFileException, IOException;
    +    public abstract AudioFileFormat getAudioFileFormat(File file)
    +            throws UnsupportedAudioFileException, IOException;
     
         /**
    -     * Obtains an audio input stream from the input stream provided.  The stream must
    -     * point to valid audio file data.  In general, audio file readers may
    +     * Obtains an audio input stream from the input stream provided. The stream
    +     * must point to valid audio file data. In general, audio file readers may
          * need to read some data from the stream before determining whether they
    -     * support it.  These parsers must
    -     * be able to mark the stream, read enough data to determine whether they
    -     * support the stream, and, if not, reset the stream's read pointer to its original
    -     * position.  If the input stream does not support this, this method may fail
    -     * with an IOException.
    -     * @param stream the input stream from which the AudioInputStream should be
    -     * constructed
    -     * @return an AudioInputStream object based on the audio file data contained
    -     * in the input stream.
    -     * @throws UnsupportedAudioFileException if the stream does not point to valid audio
    -     * file data recognized by the system
    +     * support it. These parsers must be able to mark the stream, read enough
    +     * data to determine whether they support the stream, and, if not, reset the
    +     * stream's read pointer to its original position. If the input stream does
    +     * not support this, this method may fail with an {@code IOException}.
    +     *
    +     * @param  stream the input stream from which the {@code AudioInputStream}
    +     *         should be constructed
    +     * @return an {@code AudioInputStream} object based on the audio file data
    +     *         contained in the input stream.
    +     * @throws UnsupportedAudioFileException if the stream does not point to
    +     *         valid audio file data recognized by the system
          * @throws IOException if an I/O exception occurs
          * @see InputStream#markSupported
          * @see InputStream#mark
          */
    -    public abstract AudioInputStream getAudioInputStream(InputStream stream) throws UnsupportedAudioFileException, IOException;
    +    public abstract AudioInputStream getAudioInputStream(InputStream stream)
    +            throws UnsupportedAudioFileException, IOException;
     
         /**
    -     * Obtains an audio input stream from the URL provided.  The URL must
    -     * point to valid audio file data.
    -     * @param url the URL for which the AudioInputStream should be
    -     * constructed
    -     * @return an AudioInputStream object based on the audio file data pointed
    -     * to by the URL
    -     * @throws UnsupportedAudioFileException if the URL does not point to valid audio
    -     * file data recognized by the system
    +     * Obtains an audio input stream from the URL provided. The URL must point
    +     * to valid audio file data.
    +     *
    +     * @param  url the URL for which the {@code AudioInputStream} should be
    +     *         constructed
    +     * @return an {@code AudioInputStream} object based on the audio file data
    +     *         pointed to by the URL
    +     * @throws UnsupportedAudioFileException if the URL does not point to valid
    +     *         audio file data recognized by the system
          * @throws IOException if an I/O exception occurs
          */
    -    public abstract AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException;
    +    public abstract AudioInputStream getAudioInputStream(URL url)
    +            throws UnsupportedAudioFileException, IOException;
     
         /**
    -     * Obtains an audio input stream from the File provided.  The File must
    -     * point to valid audio file data.
    -     * @param file the File for which the AudioInputStream should be
    -     * constructed
    -     * @return an AudioInputStream object based on the audio file data pointed
    -     * to by the File
    -     * @throws UnsupportedAudioFileException if the File does not point to valid audio
    -     * file data recognized by the system
    +     * Obtains an audio input stream from the {@code File} provided.
    +     * The {@code File} must point to valid audio file data.
    +     *
    +     * @param  file the {@code File} for which the {@code AudioInputStream}
    +     *         should be constructed
    +     * @return an {@code AudioInputStream} object based on the audio file data
    +     *         pointed to by the File
    +     * @throws UnsupportedAudioFileException if the {@code File} does not point
    +     *         to valid audio file data recognized by the system
          * @throws IOException if an I/O exception occurs
          */
    -    public abstract AudioInputStream getAudioInputStream(File file) throws UnsupportedAudioFileException, IOException;
    +    public abstract AudioInputStream getAudioInputStream(File file)
    +            throws UnsupportedAudioFileException, IOException;
     }
    diff --git a/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileWriter.java b/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileWriter.java
    index 0207a3b7124..a4cc31bdf18 100644
    --- a/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileWriter.java
    +++ b/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileWriter.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 1999, 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
    @@ -26,16 +26,15 @@
     package javax.sound.sampled.spi;
     
     import java.io.File;
    -import java.io.InputStream;
     import java.io.IOException;
     import java.io.OutputStream;
     
    -import javax.sound.sampled.AudioFileFormat;
     import javax.sound.sampled.AudioInputStream;
     
    +import static javax.sound.sampled.AudioFileFormat.Type;
     
     /**
    - * Provider for audio file writing services.  Classes providing concrete
    + * Provider for audio file writing services. Classes providing concrete
      * implementations can write one or more types of audio file from an audio
      * stream.
      *
    @@ -47,22 +46,23 @@ public abstract class AudioFileWriter {
         /**
          * Obtains the file types for which file writing support is provided by this
          * audio file writer.
    -     * @return array of file types.  If no file types are supported,
    -     * an array of length 0 is returned.
    +     *
    +     * @return array of file types. If no file types are supported, an array of
    +     *         length 0 is returned.
          */
    -    public abstract AudioFileFormat.Type[] getAudioFileTypes();
    -
    +    public abstract Type[] getAudioFileTypes();
     
         /**
    -     * Indicates whether file writing support for the specified file type is provided
    -     * by this audio file writer.
    -     * @param fileType the file type for which write capabilities are queried
    -     * @return true if the file type is supported,
    -     * otherwise false
    +     * Indicates whether file writing support for the specified file type is
    +     * provided by this audio file writer.
    +     *
    +     * @param  fileType the file type for which write capabilities are queried
    +     * @return {@code true} if the file type is supported, otherwise
    +     *         {@code false}
          */
    -    public boolean isFileTypeSupported(AudioFileFormat.Type fileType) {
    +    public boolean isFileTypeSupported(Type fileType) {
     
    -        AudioFileFormat.Type types[] = getAudioFileTypes();
    +        Type types[] = getAudioFileTypes();
     
             for(int i=0; itrue if the file type is supported for this audio input stream,
    -     * otherwise false
    +     * Indicates whether an audio file of the type specified can be written from
    +     * the audio input stream indicated.
    +     *
    +     * @param  fileType file type for which write capabilities are queried
    +     * @param  stream for which file writing support is queried
    +     * @return {@code true} if the file type is supported for this audio input
    +     *         stream, otherwise {@code false}
          */
    -    public boolean isFileTypeSupported(AudioFileFormat.Type fileType, AudioInputStream stream) {
    +    public boolean isFileTypeSupported(Type fileType, AudioInputStream stream) {
     
    -        AudioFileFormat.Type types[] = getAudioFileTypes( stream );
    +        Type types[] = getAudioFileTypes( stream );
     
             for(int i=0; i
    - * The source format represents the format of the incoming
    - * audio data, which will be converted.
    + * The source format represents the format of the incoming audio data, which
    + * will be converted.
      * 

    - * The target format represents the format of the processed, converted - * audio data. This is the format of the data that can be read from - * the stream returned by one of the getAudioInputStream methods. + * The target format represents the format of the processed, converted audio + * data. This is the format of the data that can be read from the stream + * returned by one of the {@code getAudioInputStream} methods. * * @author Kara Kytle * @since 1.3 */ public abstract class FormatConversionProvider { - - // NEW METHODS - /** - * Obtains the set of source format encodings from which format - * conversion services are provided by this provider. + * Obtains the set of source format encodings from which format conversion + * services are provided by this provider. + * * @return array of source format encodings. If for some reason provider - * does not provide any conversion services, an array of length 0 is - * returned. + * does not provide any conversion services, an array of length 0 is + * returned. */ - public abstract AudioFormat.Encoding[] getSourceEncodings(); - + public abstract Encoding[] getSourceEncodings(); /** - * Obtains the set of target format encodings to which format - * conversion services are provided by this provider. + * Obtains the set of target format encodings to which format conversion + * services are provided by this provider. + * * @return array of target format encodings. If for some reason provider - * does not provide any conversion services, an array of length 0 is - * returned. + * does not provide any conversion services, an array of length 0 is + * returned. */ - public abstract AudioFormat.Encoding[] getTargetEncodings(); - + public abstract Encoding[] getTargetEncodings(); /** * Indicates whether the format converter supports conversion from the * specified source format encoding. - * @param sourceEncoding the source format encoding for which support is queried - * @return true if the encoding is supported, otherwise false + * + * @param sourceEncoding the source format encoding for which support is + * queried + * @return {@code true} if the encoding is supported, otherwise + * {@code false} */ - public boolean isSourceEncodingSupported(AudioFormat.Encoding sourceEncoding){ + public boolean isSourceEncodingSupported(Encoding sourceEncoding) { - AudioFormat.Encoding sourceEncodings[] = getSourceEncodings(); + Encoding sourceEncodings[] = getSourceEncodings(); for(int i=0; itrue if the encoding is supported, otherwise false + * + * @param targetEncoding the target format encoding for which support is + * queried + * @return {@code true} if the encoding is supported, otherwise + * {@code false} */ - public boolean isTargetEncodingSupported(AudioFormat.Encoding targetEncoding){ + public boolean isTargetEncodingSupported(Encoding targetEncoding) { - AudioFormat.Encoding targetEncodings[] = getTargetEncodings(); + Encoding targetEncodings[] = getTargetEncodings(); for(int i=0; itrue if the conversion is supported, otherwise false + * Indicates whether the format converter supports conversion to a + * particular encoding from a particular format. + * + * @param targetEncoding desired encoding of the outgoing data + * @param sourceFormat format of the incoming data + * @return {@code true} if the conversion is supported, otherwise + * {@code false} */ - public boolean isConversionSupported(AudioFormat.Encoding targetEncoding, AudioFormat sourceFormat){ + public boolean isConversionSupported(Encoding targetEncoding, + AudioFormat sourceFormat) { - AudioFormat.Encoding targetEncodings[] = getTargetEncodings(sourceFormat); + Encoding targetEncodings[] = getTargetEncodings(sourceFormat); for(int i=0; itrue if the conversion is supported, otherwise false + * + * @param targetFormat desired format of outgoing data + * @param sourceFormat format of the incoming data + * @return {@code true} if the conversion is supported, otherwise + * {@code false} */ - public boolean isConversionSupported(AudioFormat targetFormat, AudioFormat sourceFormat){ + public boolean isConversionSupported(AudioFormat targetFormat, + AudioFormat sourceFormat) { AudioFormat targetFormats[] = getTargetFormats( targetFormat.getEncoding(), sourceFormat ); @@ -173,28 +177,33 @@ public abstract class FormatConversionProvider { return false; } + /** + * Obtains an audio input stream with the specified encoding from the given + * audio input stream. + * + * @param targetEncoding desired encoding of the stream after processing + * @param sourceStream stream from which data to be processed should be + * read + * @return stream from which processed data with the specified target + * encoding may be read + * @throws IllegalArgumentException if the format combination supplied is + * not supported. + */ + public abstract AudioInputStream getAudioInputStream( + Encoding targetEncoding, AudioInputStream sourceStream); /** - * Obtains an audio input stream with the specified encoding from the given audio - * input stream. - * @param targetEncoding desired encoding of the stream after processing - * @param sourceStream stream from which data to be processed should be read - * @return stream from which processed data with the specified target encoding may be read + * Obtains an audio input stream with the specified format from the given + * audio input stream. + * + * @param targetFormat desired data format of the stream after processing + * @param sourceStream stream from which data to be processed should be + * read + * @return stream from which processed data with the specified format may be + * read * @throws IllegalArgumentException if the format combination supplied is - * not supported. + * not supported. */ - public abstract AudioInputStream getAudioInputStream(AudioFormat.Encoding targetEncoding, AudioInputStream sourceStream); - - - /** - * Obtains an audio input stream with the specified format from the given audio - * input stream. - * @param targetFormat desired data format of the stream after processing - * @param sourceStream stream from which data to be processed should be read - * @return stream from which processed data with the specified format may be read - * @throws IllegalArgumentException if the format combination supplied is - * not supported. - */ - public abstract AudioInputStream getAudioInputStream(AudioFormat targetFormat, AudioInputStream sourceStream); - + public abstract AudioInputStream getAudioInputStream( + AudioFormat targetFormat, AudioInputStream sourceStream); } diff --git a/jdk/src/share/classes/javax/sound/sampled/spi/MixerProvider.java b/jdk/src/share/classes/javax/sound/sampled/spi/MixerProvider.java index d1167c0b8a6..638de86b320 100644 --- a/jdk/src/share/classes/javax/sound/sampled/spi/MixerProvider.java +++ b/jdk/src/share/classes/javax/sound/sampled/spi/MixerProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -28,28 +28,27 @@ package javax.sound.sampled.spi; import javax.sound.sampled.Mixer; /** - * A provider or factory for a particular mixer type. - * This mechanism allows the implementation to determine - * how resources are managed in creation / management of - * a mixer. + * A provider or factory for a particular mixer type. This mechanism allows the + * implementation to determine how resources are managed in creation / + * management of a mixer. * * @author Kara Kytle * @since 1.3 */ public abstract class MixerProvider { - /** * Indicates whether the mixer provider supports the mixer represented by * the specified mixer info object. *

    - * The full set of mixer info objects that represent the mixers supported - * by this {@code MixerProvider} may be obtained - * through the {@code getMixerInfo} method. + * The full set of mixer info objects that represent the mixers supported by + * this {@code MixerProvider} may be obtained through the + * {@code getMixerInfo} method. * - * @param info an info object that describes the mixer for which support is queried - * @return {@code true} if the specified mixer is supported, - * otherwise {@code false} + * @param info an info object that describes the mixer for which support is + * queried + * @return {@code true} if the specified mixer is supported, otherwise + * {@code false} * @see #getMixerInfo() */ public boolean isMixerSupported(Mixer.Info info) { @@ -64,38 +63,34 @@ public abstract class MixerProvider { return false; } - /** - * Obtains the set of info objects representing the mixer - * or mixers provided by this MixerProvider. + * Obtains the set of info objects representing the mixer or mixers provided + * by this MixerProvider. *

    - * The {@code isMixerSupported} method returns {@code true} - * for all the info objects returned by this method. - * The corresponding mixer instances for the info objects - * are returned by the {@code getMixer} method. + * The {@code isMixerSupported} method returns {@code true} for all the info + * objects returned by this method. The corresponding mixer instances for + * the info objects are returned by the {@code getMixer} method. * * @return a set of mixer info objects - * @see #getMixer(javax.sound.sampled.Mixer.Info) getMixer(Mixer.Info) - * @see #isMixerSupported(javax.sound.sampled.Mixer.Info) isMixerSupported(Mixer.Info) + * @see #getMixer(Mixer.Info) + * @see #isMixerSupported(Mixer.Info) */ public abstract Mixer.Info[] getMixerInfo(); - /** * Obtains an instance of the mixer represented by the info object. *

    * The full set of the mixer info objects that represent the mixers - * supported by this {@code MixerProvider} may be obtained - * through the {@code getMixerInfo} method. - * Use the {@code isMixerSupported} method to test whether - * this {@code MixerProvider} supports a particular mixer. + * supported by this {@code MixerProvider} may be obtained through the + * {@code getMixerInfo} method. Use the {@code isMixerSupported} method to + * test whether this {@code MixerProvider} supports a particular mixer. * - * @param info an info object that describes the desired mixer + * @param info an info object that describes the desired mixer * @return mixer instance * @throws IllegalArgumentException if the info object specified does not - * match the info object for a mixer supported by this MixerProvider. + * match the info object for a mixer supported by this MixerProvider * @see #getMixerInfo() - * @see #isMixerSupported(javax.sound.sampled.Mixer.Info) isMixerSupported(Mixer.Info) + * @see #isMixerSupported(Mixer.Info) */ public abstract Mixer getMixer(Mixer.Info info); } diff --git a/jdk/src/share/classes/javax/swing/JComponent.java b/jdk/src/share/classes/javax/swing/JComponent.java index 98c4d7fb5dd..2d2745957e7 100644 --- a/jdk/src/share/classes/javax/swing/JComponent.java +++ b/jdk/src/share/classes/javax/swing/JComponent.java @@ -3986,7 +3986,18 @@ public abstract class JComponent extends Container implements Serializable, * @see AccessibleKeyBinding * @since 1.4 */ - public AccessibleKeyBinding getAccessibleKeyBinding() { + public AccessibleKeyBinding getAccessibleKeyBinding(){ + // Try to get the linked label's mnemonic if it exists + Object o = getClientProperty(JLabel.LABELED_BY_PROPERTY); + if (o instanceof Accessible){ + AccessibleContext ac = ((Accessible) o).getAccessibleContext(); + if (ac != null){ + AccessibleComponent comp = ac.getAccessibleComponent(); + if (! (comp instanceof AccessibleExtendedComponent)) + return null; + return ((AccessibleExtendedComponent)comp).getAccessibleKeyBinding(); + } + } return null; } } // inner class AccessibleJComponent diff --git a/jdk/src/share/classes/javax/swing/border/BevelBorder.java b/jdk/src/share/classes/javax/swing/border/BevelBorder.java index dd18a88245d..0c023fa6e63 100644 --- a/jdk/src/share/classes/javax/swing/border/BevelBorder.java +++ b/jdk/src/share/classes/javax/swing/border/BevelBorder.java @@ -134,7 +134,9 @@ public class BevelBorder extends AbstractBorder * when rendered on the specified component. If no highlight * color was specified at instantiation, the highlight color * is derived from the specified component's background color. + * * @param c the component for which the highlight may be derived + * @return the outer highlight {@code Color} * @since 1.3 */ public Color getHighlightOuterColor(Component c) { @@ -148,7 +150,9 @@ public class BevelBorder extends AbstractBorder * when rendered on the specified component. If no highlight * color was specified at instantiation, the highlight color * is derived from the specified component's background color. + * * @param c the component for which the highlight may be derived + * @return the inner highlight {@code Color} * @since 1.3 */ public Color getHighlightInnerColor(Component c) { @@ -162,7 +166,9 @@ public class BevelBorder extends AbstractBorder * when rendered on the specified component. If no shadow * color was specified at instantiation, the shadow color * is derived from the specified component's background color. + * * @param c the component for which the shadow may be derived + * @return the inner shadow {@code Color} * @since 1.3 */ public Color getShadowInnerColor(Component c) { @@ -176,7 +182,9 @@ public class BevelBorder extends AbstractBorder * when rendered on the specified component. If no shadow * color was specified at instantiation, the shadow color * is derived from the specified component's background color. + * * @param c the component for which the shadow may be derived + * @return the outer shadow {@code Color} * @since 1.3 */ public Color getShadowOuterColor(Component c) { @@ -189,6 +197,9 @@ public class BevelBorder extends AbstractBorder * Returns the outer highlight color of the bevel border. * Will return null if no highlight color was specified * at instantiation. + * + * @return the outer highlight {@code Color} or {@code null} if no highlight + * color was specified * @since 1.3 */ public Color getHighlightOuterColor() { @@ -199,6 +210,9 @@ public class BevelBorder extends AbstractBorder * Returns the inner highlight color of the bevel border. * Will return null if no highlight color was specified * at instantiation. + * + * @return the inner highlight {@code Color} or {@code null} if no highlight + * color was specified * @since 1.3 */ public Color getHighlightInnerColor() { @@ -209,6 +223,9 @@ public class BevelBorder extends AbstractBorder * Returns the inner shadow color of the bevel border. * Will return null if no shadow color was specified * at instantiation. + * + * @return the inner shadow {@code Color} or {@code null} if no shadow color + * was specified * @since 1.3 */ public Color getShadowInnerColor() { @@ -219,6 +236,9 @@ public class BevelBorder extends AbstractBorder * Returns the outer shadow color of the bevel border. * Will return null if no shadow color was specified * at instantiation. + * + * @return the outer shadow {@code Color} or {@code null} if no shadow color + * was specified * @since 1.3 */ public Color getShadowOuterColor() { @@ -227,13 +247,18 @@ public class BevelBorder extends AbstractBorder /** * Returns the type of the bevel border. + * + * @return the bevel border type, either {@code RAISED} or {@code LOWERED} */ public int getBevelType() { return bevelType; } /** - * Returns whether or not the border is opaque. + * Returns whether or not the border is opaque. This implementation + * returns {@code true}. + * + * @return true */ public boolean isBorderOpaque() { return true; } diff --git a/jdk/src/share/classes/javax/swing/border/Border.java b/jdk/src/share/classes/javax/swing/border/Border.java index ca58d0d7327..cbc0f6b6546 100644 --- a/jdk/src/share/classes/javax/swing/border/Border.java +++ b/jdk/src/share/classes/javax/swing/border/Border.java @@ -66,6 +66,7 @@ public interface Border /** * Paints the border for the specified component with the specified * position and size. + * * @param c the component for which this border is being painted * @param g the paint graphics * @param x the x position of the painted border @@ -77,7 +78,10 @@ public interface Border /** * Returns the insets of the border. + * * @param c the component for which this border insets value applies + * @return an {@code Insets} object containing the insets from top, left, + * bottom and right of this {@code Border} */ Insets getBorderInsets(Component c); @@ -85,6 +89,8 @@ public interface Border * Returns whether or not the border is opaque. If the border * is opaque, it is responsible for filling in it's own * background when painting. + * + * @return true if this {@code Border} is opaque */ boolean isBorderOpaque(); } diff --git a/jdk/src/share/classes/javax/swing/border/CompoundBorder.java b/jdk/src/share/classes/javax/swing/border/CompoundBorder.java index b62ecc9965b..162b30fc94c 100644 --- a/jdk/src/share/classes/javax/swing/border/CompoundBorder.java +++ b/jdk/src/share/classes/javax/swing/border/CompoundBorder.java @@ -155,6 +155,8 @@ public class CompoundBorder extends AbstractBorder { /** * Returns the outside border object. + * + * @return the outside {@code Border} object */ public Border getOutsideBorder() { return outsideBorder; @@ -162,6 +164,8 @@ public class CompoundBorder extends AbstractBorder { /** * Returns the inside border object. + * + * @return the inside {@code Border} object */ public Border getInsideBorder() { return insideBorder; diff --git a/jdk/src/share/classes/javax/swing/border/EmptyBorder.java b/jdk/src/share/classes/javax/swing/border/EmptyBorder.java index 1875ee354f0..82d2599611a 100644 --- a/jdk/src/share/classes/javax/swing/border/EmptyBorder.java +++ b/jdk/src/share/classes/javax/swing/border/EmptyBorder.java @@ -98,6 +98,9 @@ public class EmptyBorder extends AbstractBorder implements Serializable /** * Returns the insets of the border. + * + * @return an {@code Insets} object containing the insets from top, left, + * bottom and right * @since 1.3 */ public Insets getBorderInsets() { diff --git a/jdk/src/share/classes/javax/swing/border/EtchedBorder.java b/jdk/src/share/classes/javax/swing/border/EtchedBorder.java index 2850b60db7b..59ea6bb414e 100644 --- a/jdk/src/share/classes/javax/swing/border/EtchedBorder.java +++ b/jdk/src/share/classes/javax/swing/border/EtchedBorder.java @@ -77,6 +77,7 @@ public class EtchedBorder extends AbstractBorder * whose colors will be derived * from the background color of the component passed into * the paintBorder method. + * * @param etchType the type of etch to be drawn by the border */ public EtchedBorder(int etchType) { @@ -86,6 +87,7 @@ public class EtchedBorder extends AbstractBorder /** * Creates a lowered etched border with the specified highlight and * shadow colors. + * * @param highlight the color to use for the etched highlight * @param shadow the color to use for the etched shadow */ @@ -96,6 +98,7 @@ public class EtchedBorder extends AbstractBorder /** * Creates an etched border with the specified etch-type, * highlight and shadow colors. + * * @param etchType the type of etch to be drawn by the border * @param highlight the color to use for the etched highlight * @param shadow the color to use for the etched shadow @@ -110,6 +113,7 @@ public class EtchedBorder extends AbstractBorder /** * Paints the border for the specified component with the * specified position and size. + * * @param c the component for which this border is being painted * @param g the paint graphics * @param x the x position of the painted border @@ -138,6 +142,7 @@ public class EtchedBorder extends AbstractBorder /** * Reinitialize the insets parameter with this Border's current Insets. + * * @param c the component for which this border insets value applies * @param insets the object to be reinitialized */ @@ -148,11 +153,16 @@ public class EtchedBorder extends AbstractBorder /** * Returns whether or not the border is opaque. + * This implementation returns true. + * + * @return true */ public boolean isBorderOpaque() { return true; } /** * Returns which etch-type is set on the etched border. + * + * @return the etched border type, either {@code RAISED} or {@code LOWERED} */ public int getEtchType() { return etchType; @@ -163,7 +173,9 @@ public class EtchedBorder extends AbstractBorder * when rendered on the specified component. If no highlight * color was specified at instantiation, the highlight color * is derived from the specified component's background color. + * * @param c the component for which the highlight may be derived + * @return the highlight {@code Color} of this {@code EtchedBorder} * @since 1.3 */ public Color getHighlightColor(Component c) { @@ -175,6 +187,9 @@ public class EtchedBorder extends AbstractBorder * Returns the highlight color of the etched border. * Will return null if no highlight color was specified * at instantiation. + * + * @return the highlight {@code Color} of this {@code EtchedBorder} or null + * if none was specified * @since 1.3 */ public Color getHighlightColor() { @@ -186,7 +201,9 @@ public class EtchedBorder extends AbstractBorder * when rendered on the specified component. If no shadow * color was specified at instantiation, the shadow color * is derived from the specified component's background color. + * * @param c the component for which the shadow may be derived + * @return the shadow {@code Color} of this {@code EtchedBorder} * @since 1.3 */ public Color getShadowColor(Component c) { @@ -197,6 +214,9 @@ public class EtchedBorder extends AbstractBorder * Returns the shadow color of the etched border. * Will return null if no shadow color was specified * at instantiation. + * + * @return the shadow {@code Color} of this {@code EtchedBorder} or null + * if none was specified * @since 1.3 */ public Color getShadowColor() { diff --git a/jdk/src/share/classes/javax/swing/border/LineBorder.java b/jdk/src/share/classes/javax/swing/border/LineBorder.java index 1e083c1164f..3ddb1ccda5f 100644 --- a/jdk/src/share/classes/javax/swing/border/LineBorder.java +++ b/jdk/src/share/classes/javax/swing/border/LineBorder.java @@ -60,8 +60,11 @@ public class LineBorder extends AbstractBorder protected Color lineColor; protected boolean roundedCorners; - /** Convenience method for getting the Color.black LineBorder of thickness 1. - */ + /** + * Convenience method for getting the Color.black LineBorder of thickness 1. + * + * @return a {@code LineBorder} with {@code Color.black} and thickness of 1 + */ public static Border createBlackLineBorder() { if (blackLine == null) { blackLine = new LineBorder(Color.black, 1); @@ -69,8 +72,11 @@ public class LineBorder extends AbstractBorder return blackLine; } - /** Convenience method for getting the Color.gray LineBorder of thickness 1. - */ + /** + * Convenience method for getting the Color.gray LineBorder of thickness 1. + * + * @return a {@code LineBorder} with {@code Color.gray} and thickness of 1 + */ public static Border createGrayLineBorder() { if (grayLine == null) { grayLine = new LineBorder(Color.gray, 1); @@ -81,6 +87,7 @@ public class LineBorder extends AbstractBorder /** * Creates a line border with the specified color and a * thickness = 1. + * * @param color the color for the border */ public LineBorder(Color color) { @@ -89,6 +96,7 @@ public class LineBorder extends AbstractBorder /** * Creates a line border with the specified color and thickness. + * * @param color the color of the border * @param thickness the thickness of the border */ @@ -99,6 +107,7 @@ public class LineBorder extends AbstractBorder /** * Creates a line border with the specified color, thickness, * and corner shape. + * * @param color the color of the border * @param thickness the thickness of the border * @param roundedCorners whether or not border corners should be round @@ -114,6 +123,7 @@ public class LineBorder extends AbstractBorder /** * Paints the border for the specified component with the * specified position and size. + * * @param c the component for which this border is being painted * @param g the paint graphics * @param x the x position of the painted border @@ -134,8 +144,8 @@ public class LineBorder extends AbstractBorder int offs = this.thickness; int size = offs + offs; if (this.roundedCorners) { - int arc = offs + size; - outer = new RoundRectangle2D.Float(x, y, width, height, arc, arc); + float arc = .2f * offs; + outer = new RoundRectangle2D.Float(x, y, width, height, offs, offs); inner = new RoundRectangle2D.Float(x + offs, y + offs, width - size, height - size, arc, arc); } else { @@ -152,6 +162,7 @@ public class LineBorder extends AbstractBorder /** * Reinitialize the insets parameter with this Border's current Insets. + * * @param c the component for which this border insets value applies * @param insets the object to be reinitialized */ @@ -162,6 +173,8 @@ public class LineBorder extends AbstractBorder /** * Returns the color of the border. + * + * @return a {@code Color} object representing the color of this object */ public Color getLineColor() { return lineColor; @@ -169,6 +182,8 @@ public class LineBorder extends AbstractBorder /** * Returns the thickness of the border. + * + * @return the thickness of this border */ public int getThickness() { return thickness; @@ -176,6 +191,8 @@ public class LineBorder extends AbstractBorder /** * Returns whether this border will be drawn with rounded corners. + * + * @return {@code true} if this border should have rounded corners * @since 1.3 */ public boolean getRoundedCorners() { @@ -184,6 +201,8 @@ public class LineBorder extends AbstractBorder /** * Returns whether or not the border is opaque. + * + * @return {@code true} if the border is opaque, {@code false} otherwise */ public boolean isBorderOpaque() { return !roundedCorners; diff --git a/jdk/src/share/classes/javax/swing/border/MatteBorder.java b/jdk/src/share/classes/javax/swing/border/MatteBorder.java index e8491f59850..b1501ff932f 100644 --- a/jdk/src/share/classes/javax/swing/border/MatteBorder.java +++ b/jdk/src/share/classes/javax/swing/border/MatteBorder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -196,6 +196,9 @@ public class MatteBorder extends EmptyBorder /** * Returns the color used for tiling the border or null * if a tile icon is being used. + * + * @return the {@code Color} object used to render the border or {@code null} + * if a tile icon is used * @since 1.3 */ public Color getMatteColor() { @@ -205,6 +208,9 @@ public class MatteBorder extends EmptyBorder /** * Returns the icon used for tiling the border or null * if a solid color is being used. + * + * @return the {@code Icon} used to tile the border or {@code null} if a + * solid color is used to fill the border * @since 1.3 */ public Icon getTileIcon() { @@ -213,6 +219,8 @@ public class MatteBorder extends EmptyBorder /** * Returns whether or not the border is opaque. + * + * @return {@code true} if the border is opaque, {@code false} otherwise */ public boolean isBorderOpaque() { // If a tileIcon is set, then it may contain transparent bits diff --git a/jdk/src/share/classes/javax/swing/colorchooser/AbstractColorChooserPanel.java b/jdk/src/share/classes/javax/swing/colorchooser/AbstractColorChooserPanel.java index c75d08b89ff..5568fd6161a 100644 --- a/jdk/src/share/classes/javax/swing/colorchooser/AbstractColorChooserPanel.java +++ b/jdk/src/share/classes/javax/swing/colorchooser/AbstractColorChooserPanel.java @@ -145,7 +145,8 @@ public abstract class AbstractColorChooserPanel extends JPanel { /** * Invoked when the panel is added to the chooser. * If you override this, be sure to call super. - * @param enclosingChooser the panel to be added + * + * @param enclosingChooser the chooser to which the panel is to be added * @exception RuntimeException if the chooser panel has already been * installed */ @@ -163,6 +164,8 @@ public abstract class AbstractColorChooserPanel extends JPanel { /** * Invoked when the panel is removed from the chooser. * If override this, be sure to call super. + * + * @param enclosingChooser the chooser from which the panel is to be removed */ public void uninstallChooserPanel(JColorChooser enclosingChooser) { chooser.removePropertyChangeListener("enabled", enabledListener); diff --git a/jdk/src/share/classes/javax/swing/filechooser/FileFilter.java b/jdk/src/share/classes/javax/swing/filechooser/FileFilter.java index 1bdc9d4d8e7..170e4c8b891 100644 --- a/jdk/src/share/classes/javax/swing/filechooser/FileFilter.java +++ b/jdk/src/share/classes/javax/swing/filechooser/FileFilter.java @@ -51,11 +51,16 @@ import java.io.File; public abstract class FileFilter { /** * Whether the given file is accepted by this filter. + * + * @param f the File to test + * @return true if the file is to be accepted */ public abstract boolean accept(File f); /** * The description of this filter. For example: "JPG and GIF Images" + * + * @return the description of this filter * @see FileView#getName */ public abstract String getDescription(); diff --git a/jdk/src/share/classes/javax/swing/filechooser/FileSystemView.java b/jdk/src/share/classes/javax/swing/filechooser/FileSystemView.java index 4ab5dea5cac..26f09eac229 100644 --- a/jdk/src/share/classes/javax/swing/filechooser/FileSystemView.java +++ b/jdk/src/share/classes/javax/swing/filechooser/FileSystemView.java @@ -324,11 +324,18 @@ public abstract class FileSystemView { /** * Creates a new folder with a default folder name. + * + * @param containingDir a {@code File} object denoting directory to contain the new folder + * @return a {@code File} object denoting the newly created folder + * @throws IOException if new folder could not be created */ public abstract File createNewFolder(File containingDir) throws IOException; /** * Returns whether a file is hidden or not. + * + * @param f a {@code File} object + * @return true if the given {@code File} denotes a hidden file */ public boolean isHiddenFile(File f) { return f.isHidden(); @@ -395,6 +402,9 @@ public abstract class FileSystemView { * Returns all root partitions on this system. For example, on * Windows, this would be the "Desktop" folder, while on DOS this * would be the A: through Z: drives. + * + * @return an array of {@code File} objects representing all root partitions + * on this system */ public File[] getRoots() { // Don't cache this array, because filesystem might change @@ -435,6 +445,10 @@ public abstract class FileSystemView { /** * Returns a File object constructed in dir from the given filename. + * + * @param dir an abstract pathname denoting a directory + * @param filename a {@code String} representation of a pathname + * @return a {@code File} object created from {@code dir} and {@code filename} */ public File createFileObject(File dir, String filename) { if(dir == null) { @@ -446,6 +460,9 @@ public abstract class FileSystemView { /** * Returns a File object constructed from the given path string. + * + * @param path {@code String} representation of path + * @return a {@code File} object created from the given {@code path} */ public File createFileObject(String path) { File f = new File(path); @@ -458,6 +475,12 @@ public abstract class FileSystemView { /** * Gets the list of shown (i.e. not hidden) files. + * + * @param dir the root directory of files to be returned + * @param useFileHiding determine if hidden files are returned + * @return an array of {@code File} objects representing files and + * directories in the given {@code dir}. It includes hidden + * files if {@code useFileHiding} is false. */ public File[] getFiles(File dir, boolean useFileHiding) { List files = new ArrayList(); diff --git a/jdk/src/share/classes/javax/swing/filechooser/FileView.java b/jdk/src/share/classes/javax/swing/filechooser/FileView.java index 5e04ca4c69e..b628d5dbc51 100644 --- a/jdk/src/share/classes/javax/swing/filechooser/FileView.java +++ b/jdk/src/share/classes/javax/swing/filechooser/FileView.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -69,6 +69,9 @@ public abstract class FileView { /** * The name of the file. Normally this would be simply * f.getName(). + * + * @param f a {@code File} object + * @return a {@code String} representing the name of the file */ public String getName(File f) { return null; @@ -78,6 +81,11 @@ public abstract class FileView { * A human readable description of the file. For example, * a file named jag.jpg might have a description that read: * "A JPEG image file of James Gosling's face". + * + * @param f a {@code File} object + * @return a {@code String} containing a description of the file or + * {@code null} if it is not available. + * */ public String getDescription(File f) { return null; @@ -87,6 +95,10 @@ public abstract class FileView { * A human readable description of the type of the file. For * example, a jpg file might have a type description of: * "A JPEG Compressed Image File" + * + * @param f a {@code File} object + * @return a {@code String} containing a description of the type of the file + * or {@code null} if it is not available . */ public String getTypeDescription(File f) { return null; @@ -94,6 +106,10 @@ public abstract class FileView { /** * The icon that represents this file in the JFileChooser. + * + * @param f a {@code File} object + * @return an {@code Icon} which represents the specified {@code File} or + * {@code null} if it is not available. */ public Icon getIcon(File f) { return null; @@ -103,6 +119,12 @@ public abstract class FileView { * Whether the directory is traversable or not. This might be * useful, for example, if you want a directory to represent * a compound document and don't want the user to descend into it. + * + * @param f a {@code File} object representing a directory + * @return {@code true} if the directory is traversable, + * {@code false} if it is not, and {@code null} if the + * file system should be checked. + * @see FileSystemView#isTraversable */ public Boolean isTraversable(File f) { return null; diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java index 6a64676673b..b1aea28c79f 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java @@ -2271,6 +2271,7 @@ public class MetalLookAndFeel extends BasicLookAndFeel // From the JLF Design Guidelines: // http://www.oracle.com/technetwork/java/jlf-135985.html + @SuppressWarnings("fallthrough") private static class MetalLayoutStyle extends DefaultLayoutStyle { private static MetalLayoutStyle INSTANCE = new MetalLayoutStyle(); @@ -2407,4 +2408,4 @@ public class MetalLookAndFeel extends BasicLookAndFeel return 0; } } -} \ No newline at end of file +} diff --git a/jdk/src/share/classes/javax/swing/plaf/nimbus/skin.laf b/jdk/src/share/classes/javax/swing/plaf/nimbus/skin.laf index 39010042190..394721e1c41 100644 --- a/jdk/src/share/classes/javax/swing/plaf/nimbus/skin.laf +++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/skin.laf @@ -1,7 +1,7 @@ + + + + + Unsigned applet can retrieve the dragged information before drop action occurs + + + +

    DragInterceptorAppletTest
    Bug ID: 6887703

    + +

    This is an AUTOMATIC test, simply wait for completion

    + + + + diff --git a/jdk/test/java/awt/dnd/DragInterceptorAppletTest/DragInterceptorAppletTest.java b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/DragInterceptorAppletTest.java new file mode 100644 index 00000000000..5f70e2de35b --- /dev/null +++ b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/DragInterceptorAppletTest.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2007, 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 6887703 + @summary Unsigned applet can retrieve the dragged information before drop action occurs + @author : area=dnd + @run applet DragInterceptorAppletTest.html +*/ + +/** + * DragInterceptorAppletTest.java + * + * summary: Unsigned applet can retrieve the dragged information before drop action occurs + */ + +import static java.lang.Thread.sleep; + +import test.java.awt.regtesthelpers.process.ProcessCommunicator; +import test.java.awt.regtesthelpers.process.ProcessResults; +import test.java.awt.regtesthelpers.Util; +import java.applet.Applet; +import java.awt.*; +import java.awt.event.InputEvent; + +public class DragInterceptorAppletTest extends Applet { + + public void init() { + setLayout(new BorderLayout()); + }//End init() + + public void start() { + + SourceFrame sourceFrame = new SourceFrame(); + + Util.waitForIdle(null); + + String [] args = new String [] { + String.valueOf(sourceFrame.getNextLocationX()), + String.valueOf(sourceFrame.getNextLocationY()), + String.valueOf(sourceFrame.getDragSourcePointX()), + String.valueOf(sourceFrame.getDragSourcePointY()), + }; + String classpath = System.getProperty("java.class.path"); + ProcessResults processResults = + ProcessCommunicator.executeChildProcess(this.getClass(),classpath,args); + + verifyTestResults(processResults); + + }// start() + + private static void verifyTestResults(ProcessResults processResults) { + + switch (processResults.getExitValue()) { + case InterprocessMessages.DATA_WAS_INTERCEPTED_AND_EXCEPTION_HANDLER_WAS_NOT_TRIGGERED: + processResults.printProcessErrorOutput(System.err); + throw new RuntimeException("TEST IS FAILED: Target applet can intercept data " + + "without a clipboard permission and an exception handler was not triggered."); + //Unreachable... + + case InterprocessMessages.DATA_WAS_INTERCEPTED: + processResults.printProcessErrorOutput(System.err); + throw new RuntimeException("TEST IS FAILED: Target applet can intercept data " + + "without a clipboard permission"); + //Unreachable... + + case InterprocessMessages.EXCEPTION_HANDLER_WAS_NOT_TRIGGERED: + processResults.printProcessErrorOutput(System.err); + throw new RuntimeException("TEST IS FAILED: An exception handler was not triggered."); + //Unreachable... + + } + + // The child process throws an exception. do not look at the stderr. + processResults.verifyStdErr(System.err); + processResults.verifyProcessExitValue(System.err); + processResults.printProcessStandartOutput(System.out); + } + + //We cannot make an instance of the applet without the default constructor + public DragInterceptorAppletTest() { + super(); + } + + //We need in this constructor to pass frame position between JVMs + public DragInterceptorAppletTest(Point targetFrameLocation, Point dragSourcePoint) + throws InterruptedException + { + DragInterceptorFrame targetFrame = new DragInterceptorFrame(targetFrameLocation); + + Util.waitForIdle(null); + + final Robot robot = Util.createRobot(); + + robot.mouseMove((int)dragSourcePoint.getX(),(int)dragSourcePoint.getY()); + sleep(100); + robot.mousePress(InputEvent.BUTTON1_MASK); + sleep(100); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + sleep(100); + + Util.drag(robot, dragSourcePoint, targetFrame.getDropTargetPoint(), + InputEvent.BUTTON1_MASK); + + sleep(2000); + ProcessCommunicator.destroyProcess(); + } + + enum InterprocessArguments { + TARGET_FRAME_X_POSITION_ARGUMENT, + TARGET_FRAME_Y_POSITION_ARGUMENT, + DRAG_SOURCE_POINT_X_ARGUMENT, + DRAG_SOURCE_POINT_Y_ARGUMENT; + + int extract (String [] args) { + return Integer.parseInt(args[this.ordinal()]); + } + } + + public static void main (String [] args) { + Point dragSourcePoint = new Point(InterprocessArguments.DRAG_SOURCE_POINT_X_ARGUMENT.extract(args), + InterprocessArguments.DRAG_SOURCE_POINT_Y_ARGUMENT.extract(args)); + Point targetFrameLocation = new Point(InterprocessArguments.TARGET_FRAME_X_POSITION_ARGUMENT.extract(args), + InterprocessArguments.TARGET_FRAME_Y_POSITION_ARGUMENT.extract(args)); + try { + new DragInterceptorAppletTest(targetFrameLocation, dragSourcePoint); + } catch (InterruptedException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + +}// class DragInterceptorAppletTest diff --git a/jdk/test/java/awt/dnd/DragInterceptorAppletTest/DragInterceptorFrame.java b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/DragInterceptorFrame.java new file mode 100644 index 00000000000..69d4a014ba9 --- /dev/null +++ b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/DragInterceptorFrame.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2007, 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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.*; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.dnd.*; +import java.io.IOException; +import java.security.Permission; +import java.security.AccessControlException; + +class DragInterceptorFrame extends Frame implements DropTargetListener { + + private static int exitMessage = InterprocessMessages.TEST_PASSED; + private static boolean dataIsAccessible = false; + private static boolean exceptionHasBeenThrown = false; + + DragInterceptorFrame(Point location) { + System.setSecurityManager(new ClipboardDefender()); + initGUI(location); + setDropTarget(new DropTarget(this, DnDConstants.ACTION_COPY, + this)); + } + + private void initGUI(Point location) { + this.setLocation(location); + this.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + DragInterceptorFrame.this.dispose(); + } + }); + setSize (200, 200); + this.setVisible(true); + } + + public void dragEnter(DropTargetDragEvent dtde) { + // We want to set the exception handler on EDT + Thread.currentThread().setUncaughtExceptionHandler ( + new Thread.UncaughtExceptionHandler() { + public void uncaughtException(Thread t, Throwable e) { + exceptionHasBeenThrown = true; + } + } + ); + examineTransferable(dtde); + } + + public void dragOver(DropTargetDragEvent dtde) { + examineTransferable(dtde); + } + + public void dropActionChanged(DropTargetDragEvent dtde) { + examineTransferable(dtde); + } + + public void dragExit(DropTargetEvent dte) {} + + public void drop(DropTargetDropEvent dtde) { + + if (dataIsAccessible && !exceptionHasBeenThrown) { + exitMessage = InterprocessMessages.DATA_WAS_INTERCEPTED_AND_EXCEPTION_HANDLER_WAS_NOT_TRIGGERED; + } else if (dataIsAccessible) { + exitMessage = InterprocessMessages.DATA_WAS_INTERCEPTED; + } else if (!exceptionHasBeenThrown) { + exitMessage = InterprocessMessages.EXCEPTION_HANDLER_WAS_NOT_TRIGGERED; + } + + // This returns the diagnostic code from the child VM + System.exit(exitMessage); + } + + Point getDropTargetPoint() { + return new Point((int)getLocationOnScreen().getX()+(getWidth()/2), + (int)getLocationOnScreen().getY()+(getHeight()/2)); + } + + private void examineTransferable(DropTargetDragEvent dtde) { + if (dtde.getCurrentDataFlavorsAsList().contains(DataFlavor.stringFlavor)) { + dtde.acceptDrag(DnDConstants.ACTION_COPY); + try{ + if (null != dtde.getTransferable().getTransferData(DataFlavor.stringFlavor)) { + dataIsAccessible = true; + } + } catch (IOException e) { + e.printStackTrace(); + exitMessage = InterprocessMessages.UNEXPECTED_IO_EXCEPTION; + } catch (UnsupportedFlavorException e) { + e.printStackTrace(); + exitMessage = InterprocessMessages.UNEXPECTED_UNSUPPORTED_FLAVOR_EXCEPTION; + } + } + } + + static class ClipboardDefender extends SecurityManager { + public void checkPermission(Permission p) { + if (p instanceof java.awt.AWTPermission && + p.getName().equals("accessClipboard")) { + throw new AccessControlException("access denied "); + } + } + } + + public static void main(String[] args) { + new DragInterceptorFrame(new Point(200,200)); + } +} diff --git a/jdk/test/java/awt/dnd/DragInterceptorAppletTest/InterprocessMessages.java b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/InterprocessMessages.java new file mode 100644 index 00000000000..6506565cd05 --- /dev/null +++ b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/InterprocessMessages.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2007, 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +public interface InterprocessMessages { + final static int TEST_PASSED = 0; + final static int DATA_WAS_INTERCEPTED = 212; + final static int EXCEPTION_HANDLER_WAS_NOT_TRIGGERED = 213; + final static int DATA_WAS_INTERCEPTED_AND_EXCEPTION_HANDLER_WAS_NOT_TRIGGERED = 214; + + final static int UNEXPECTED_IO_EXCEPTION = 400; + final static int UNEXPECTED_UNSUPPORTED_FLAVOR_EXCEPTION = 401; +} diff --git a/jdk/test/java/awt/dnd/DragInterceptorAppletTest/SourceFrame.java b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/SourceFrame.java new file mode 100644 index 00000000000..7a7c833b91a --- /dev/null +++ b/jdk/test/java/awt/dnd/DragInterceptorAppletTest/SourceFrame.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2007, 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 test.java.awt.regtesthelpers.Util; + +import java.awt.*; +import java.awt.datatransfer.StringSelection; +import java.awt.dnd.DragGestureListener; +import java.awt.dnd.DragSource; +import java.awt.dnd.DnDConstants; +import java.awt.dnd.DragGestureEvent; + +class SourceFrame extends Frame implements DragGestureListener { + + SourceFrame() { + super("Source File List Frame"); + initGUI(); + new DragSource().createDefaultDragGestureRecognizer(this, + DnDConstants.ACTION_COPY,this); + } + + private void initGUI() { + this.addWindowListener(Util.getClosingWindowAdapter()); + this.setLocation(300,250); + this.setSize(200,200); + this.setVisible(true); + } + + int getNextLocationX() { + return getX()+getWidth(); + } + + int getNextLocationY() { + return getY(); + } + + int getDragSourcePointX() { + return (int)getLocationOnScreen().getX()+(getWidth()/2); + } + + int getDragSourcePointY() { + return (int)getLocationOnScreen().getY()+ (getHeight()/2); + } + + public void dragGestureRecognized(DragGestureEvent dge) { + dge.startDrag(null, new StringSelection("A TEXT")); + } +} diff --git a/jdk/test/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.html b/jdk/test/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.html new file mode 100644 index 00000000000..2b3aa7aa60c --- /dev/null +++ b/jdk/test/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.html @@ -0,0 +1,43 @@ + + + + + + + + + +

    InterJVMGetDropSuccessTest
    Bug ID: 4658741

    + +

    This is an AUTOMATIC test, simply wait for completion

    + + + + diff --git a/jdk/test/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.java b/jdk/test/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.java new file mode 100644 index 00000000000..9307fa26df5 --- /dev/null +++ b/jdk/test/java/awt/dnd/InterJVMGetDropSuccessTest/InterJVMGetDropSuccessTest.java @@ -0,0 +1,499 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 4658741 + @summary verifies that getDropSuccess() returns correct value for inter-JVM DnD + @author das@sparc.spb.su area=dnd + @run applet InterJVMGetDropSuccessTest.html +*/ + +// Note there is no @ in front of test above. This is so that the +// harness will not mistake this file as a test file. It should +// only see the html file as a test file. (the harness runs all +// valid test files, so it would run this test twice if this file +// were valid as well as the html file.) +// Also, note the area= after Your Name in the author tag. Here, you +// should put which functional area the test falls in. See the +// AWT-core home page -> test areas and/or -> AWT team for a list of +// areas. +// Note also the 'InterJVMGetDropSuccessTest.html' in the run tag. This should +// be changed to the name of the test. + + +/** + * InterJVMGetDropSuccessTest.java + * + * summary: verifies that getDropSuccess() returns correct value for inter-JVM DnD + */ + +import java.applet.Applet; +import java.awt.*; +import java.awt.datatransfer.*; +import java.awt.dnd.*; +import java.awt.event.*; +import java.io.*; +import javax.swing.*; + + +//Automated tests should run as applet tests if possible because they +// get their environments cleaned up, including AWT threads, any +// test created threads, and any system resources used by the test +// such as file descriptors. (This is normally not a problem as +// main tests usually run in a separate VM, however on some platforms +// such as the Mac, separate VMs are not possible and non-applet +// tests will cause problems). Also, you don't have to worry about +// synchronisation stuff in Applet tests they way you do in main +// tests... + + +public class InterJVMGetDropSuccessTest extends Applet { + + private int returnCode = Util.CODE_NOT_RETURNED; + private boolean successCodes[] = { true, false }; + private int dropCount = 0; + + final Frame frame = new Frame("Target Frame"); + + final DropTargetListener dropTargetListener = new DropTargetAdapter() { + public void drop(DropTargetDropEvent dtde) { + dtde.acceptDrop(DnDConstants.ACTION_COPY); + dtde.dropComplete(successCodes[dropCount]); + dropCount++; + } + }; + final DropTarget dropTarget = new DropTarget(frame, dropTargetListener); + + public void init() { + //Create instructions for the user here, as well as set up + // the environment -- set the layout manager, add buttons, + // etc. + + String[] instructions = + { + "This is an AUTOMATIC test", + "simply wait until it is done" + }; + Sysout.createDialog( ); + Sysout.printInstructions( instructions ); + + frame.setTitle("Test frame"); + frame.setBounds(100, 100, 150, 150); + } // init() + + public void start() { + + frame.setVisible(true); + + try { + Thread.sleep(Util.FRAME_ACTIVATION_TIMEOUT); + + Point p = frame.getLocationOnScreen(); + Dimension d = frame.getSize(); + + String javaPath = System.getProperty("java.home", ""); + String command = javaPath + File.separator + "bin" + + File.separator + "java -cp " + System.getProperty("test.classes", ".") + + " Child " + + p.x + " " + p.y + " " + d.width + " " + d.height; + + Process process = Runtime.getRuntime().exec(command); + returnCode = process.waitFor(); + + InputStream errorStream = process.getErrorStream(); + int count = errorStream.available(); + if (count > 0) { + byte[] b = new byte[count]; + errorStream.read(b); + System.err.println("========= Child VM System.err ========"); + System.err.print(new String(b)); + System.err.println("======================================"); + } + + InputStream outputStream = process.getInputStream(); + count = outputStream.available(); + if (count > 0) { + byte[] b = new byte[count]; + outputStream.read(b); + System.err.println("========= Child VM System.out ========"); + System.err.print(new String(b)); + System.err.println("======================================"); + } + } catch (Throwable e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + switch (returnCode) { + case Util.CODE_NOT_RETURNED: + throw new RuntimeException("Child VM: failed to start"); + case Util.CODE_FAILURE: + throw new RuntimeException("Child VM: abnormal termination"); + default: + if (dropCount == 2) { + int expectedRetCode = 0; + if (successCodes[0]) { + expectedRetCode |= Util.CODE_FIRST_SUCCESS; + } + if (successCodes[1]) { + expectedRetCode |= Util.CODE_SECOND_SUCCESS; + } + if (expectedRetCode != returnCode) { + throw new RuntimeException("The test failed. Expected:" + + expectedRetCode + ". Returned:" + + returnCode); + } + } + break; + } + } // start() +} // class InterJVMGetDropSuccessTest + +final class Util implements AWTEventListener { + public static final int CODE_NOT_RETURNED = -1; + public static final int CODE_FIRST_SUCCESS = 0x2; + public static final int CODE_SECOND_SUCCESS = 0x2; + public static final int CODE_FAILURE = 0x1; + + public static final int FRAME_ACTIVATION_TIMEOUT = 3000; + + static final Object SYNC_LOCK = new Object(); + static final int MOUSE_RELEASE_TIMEOUT = 1000; + + static final Util theInstance = new Util(); + + static { + Toolkit.getDefaultToolkit().addAWTEventListener(theInstance, AWTEvent.MOUSE_EVENT_MASK); + } + + public static Point getCenterLocationOnScreen(Component c) { + Point p = c.getLocationOnScreen(); + Dimension d = c.getSize(); + p.translate(d.width / 2, d.height / 2); + return p; + } + + public static int sign(int n) { + return n < 0 ? -1 : n == 0 ? 0 : 1; + } + + private Component clickedComponent = null; + + private void reset() { + clickedComponent = null; + } + + public void eventDispatched(AWTEvent e) { + if (e.getID() == MouseEvent.MOUSE_RELEASED) { + clickedComponent = (Component)e.getSource(); + synchronized (SYNC_LOCK) { + SYNC_LOCK.notifyAll(); + } + } + } + + public static boolean pointInComponent(Robot robot, Point p, Component comp) + throws InterruptedException { + return theInstance.pointInComponentImpl(robot, p, comp); + } + + private boolean pointInComponentImpl(Robot robot, Point p, Component comp) + throws InterruptedException { + robot.waitForIdle(); + reset(); + robot.mouseMove(p.x, p.y); + robot.mousePress(InputEvent.BUTTON1_MASK); + synchronized (SYNC_LOCK) { + robot.mouseRelease(InputEvent.BUTTON1_MASK); + SYNC_LOCK.wait(MOUSE_RELEASE_TIMEOUT); + } + + Component c = clickedComponent; + + while (c != null && c != comp) { + c = c.getParent(); + } + + return c == comp; + } +} + +class Child { + static class DragSourceDropListener extends DragSourceAdapter { + private boolean finished = false; + private boolean dropSuccess = false; + + public void reset() { + finished = false; + dropSuccess = false; + } + + public boolean isDropFinished() { + return finished; + } + + public boolean getDropSuccess() { + return dropSuccess; + } + + public void dragDropEnd(DragSourceDropEvent dsde) { + finished = true; + dropSuccess = dsde.getDropSuccess(); + synchronized (Util.SYNC_LOCK) { + Util.SYNC_LOCK.notifyAll(); + } + } + } + + final Frame frame = new Frame("Source Frame"); + final DragSource dragSource = DragSource.getDefaultDragSource(); + final DragSourceDropListener dragSourceListener = new DragSourceDropListener(); + final Transferable transferable = new StringSelection("TEXT"); + final DragGestureListener dragGestureListener = new DragGestureListener() { + public void dragGestureRecognized(DragGestureEvent dge) { + dge.startDrag(null, transferable, dragSourceListener); + } + }; + final DragGestureRecognizer dragGestureRecognizer = + dragSource.createDefaultDragGestureRecognizer(frame, DnDConstants.ACTION_COPY, + dragGestureListener); + + public static void main(String[] args) { + Child child = new Child(); + child.run(args); + } + + public void run(String[] args) { + try { + if (args.length != 4) { + throw new RuntimeException("Incorrect command line arguments."); + } + + int x = Integer.parseInt(args[0]); + int y = Integer.parseInt(args[1]); + int w = Integer.parseInt(args[2]); + int h = Integer.parseInt(args[3]); + + frame.setBounds(300, 200, 150, 150); + frame.setVisible(true); + + Thread.sleep(Util.FRAME_ACTIVATION_TIMEOUT); + + Point sourcePoint = Util.getCenterLocationOnScreen(frame); + + Point targetPoint = new Point(x + w / 2, y + h / 2); + + Robot robot = new Robot(); + robot.mouseMove(sourcePoint.x, sourcePoint.y); + robot.mousePress(InputEvent.BUTTON1_MASK); + for (Point p = new Point(sourcePoint); !p.equals(targetPoint); + p.translate(Util.sign(targetPoint.x - p.x), + Util.sign(targetPoint.y - p.y))) { + robot.mouseMove(p.x, p.y); + Thread.sleep(50); + } + + synchronized (Util.SYNC_LOCK) { + robot.mouseRelease(InputEvent.BUTTON1_MASK); + Util.SYNC_LOCK.wait(Util.FRAME_ACTIVATION_TIMEOUT); + } + + if (!dragSourceListener.isDropFinished()) { + throw new RuntimeException("Drop not finished"); + } + + boolean success1 = dragSourceListener.getDropSuccess(); + + dragSourceListener.reset(); + robot.mouseMove(sourcePoint.x, sourcePoint.y); + robot.mousePress(InputEvent.BUTTON1_MASK); + for (Point p = new Point(sourcePoint); !p.equals(targetPoint); + p.translate(Util.sign(targetPoint.x - p.x), + Util.sign(targetPoint.y - p.y))) { + robot.mouseMove(p.x, p.y); + Thread.sleep(50); + } + + synchronized (Util.SYNC_LOCK) { + robot.mouseRelease(InputEvent.BUTTON1_MASK); + Util.SYNC_LOCK.wait(Util.FRAME_ACTIVATION_TIMEOUT); + } + + if (!dragSourceListener.isDropFinished()) { + throw new RuntimeException("Drop not finished"); + } + + boolean success2 = dragSourceListener.getDropSuccess(); + int retCode = 0; + + if (success1) { + retCode |= Util.CODE_FIRST_SUCCESS; + } + if (success2) { + retCode |= Util.CODE_SECOND_SUCCESS; + } + // This returns the diagnostic code from the child VM + System.exit(retCode); + } catch (Throwable e) { + e.printStackTrace(); + // This returns the diagnostic code from the child VM + System.exit(Util.CODE_FAILURE); + } + } // run() +} // class child + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout + { + private static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.show(); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.show(); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + dialog.displayMessage( messageIn ); + } + + }// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog + { + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("South", messageText); + + pack(); + + show(); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + } + + }// TestDialog class diff --git a/jdk/test/java/awt/dnd/NoFormatsCrashTest/NoFormatsCrashTest.html b/jdk/test/java/awt/dnd/NoFormatsCrashTest/NoFormatsCrashTest.html new file mode 100644 index 00000000000..c19a0a02354 --- /dev/null +++ b/jdk/test/java/awt/dnd/NoFormatsCrashTest/NoFormatsCrashTest.html @@ -0,0 +1,45 @@ + + + + + + + + + +

    NoFormatsCrashTest
    Bug ID: 4870762

    + +

    This is an AUTOMATIC test, simply wait for completion

    + + + + + diff --git a/jdk/test/java/awt/dnd/NoFormatsCrashTest/NoFormatsCrashTest.java b/jdk/test/java/awt/dnd/NoFormatsCrashTest/NoFormatsCrashTest.java new file mode 100644 index 00000000000..3be0adc666e --- /dev/null +++ b/jdk/test/java/awt/dnd/NoFormatsCrashTest/NoFormatsCrashTest.java @@ -0,0 +1,488 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 4870762 + @summary tests that a drop target JVM doesn't crash if the source doesn't export + data in native formats. + @author das@sparc.spb.su area=dnd + @compile NoFormatsCrashTest.java + @run applet NoFormatsCrashTest.html +*/ + +// Note there is no @ in front of test above. This is so that the +// harness will not mistake this file as a test file. It should +// only see the html file as a test file. (the harness runs all +// valid test files, so it would run this test twice if this file +// were valid as well as the html file.) +// Also, note the area= after Your Name in the author tag. Here, you +// should put which functional area the test falls in. See the +// AWT-core home page -> test areas and/or -> AWT team for a list of +// areas. +// Note also the 'NoFormatsCrashTest.html' in the run tag. This should +// be changed to the name of the test. + + +/** + * NoFormatsCrashTest.java + * + * summary: tests that a drop target JVM doesn't crash if the source doesn't export + * data in native formats. + */ + +import java.applet.Applet; +import java.awt.*; +import java.awt.datatransfer.*; +import java.awt.dnd.*; +import java.awt.event.*; +import java.io.*; + + +//Automated tests should run as applet tests if possible because they +// get their environments cleaned up, including AWT threads, any +// test created threads, and any system resources used by the test +// such as file descriptors. (This is normally not a problem as +// main tests usually run in a separate VM, however on some platforms +// such as the Mac, separate VMs are not possible and non-applet +// tests will cause problems). Also, you don't have to worry about +// synchronisation stuff in Applet tests they way you do in main +// tests... + + +public class NoFormatsCrashTest extends Applet { + + final Frame frame = new Frame(); + private volatile Process process; + + static final int FRAME_ACTIVATION_TIMEOUT = 2000; + + public static void main(String[] args) { + NoFormatsCrashTest test = new NoFormatsCrashTest(); + test.run(args); + } + + public void run(String[] args) { + try { + if (args.length != 4) { + throw new RuntimeException("Incorrect command line arguments."); + } + + int x = Integer.parseInt(args[0]); + int y = Integer.parseInt(args[1]); + int w = Integer.parseInt(args[2]); + int h = Integer.parseInt(args[3]); + + Panel panel = new DragSourcePanel(); + + frame.setTitle("Drag source frame"); + frame.setLocation(500, 200); + frame.add(panel); + frame.pack(); + frame.setVisible(true); + + Thread.sleep(FRAME_ACTIVATION_TIMEOUT); + + Point sourcePoint = panel.getLocationOnScreen(); + Dimension d = panel.getSize(); + sourcePoint.translate(d.width / 2, d.height / 2); + + Point targetPoint = new Point(x + w / 2, y + h / 2); + + Robot robot = new Robot(); + robot.mouseMove(sourcePoint.x, sourcePoint.y); + robot.keyPress(KeyEvent.VK_CONTROL); + robot.mousePress(InputEvent.BUTTON1_MASK); + for (; !sourcePoint.equals(targetPoint); + sourcePoint.translate(sign(targetPoint.x - sourcePoint.x), + sign(targetPoint.y - sourcePoint.y))) { + robot.mouseMove(sourcePoint.x, sourcePoint.y); + Thread.sleep(50); + } + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.keyRelease(KeyEvent.VK_CONTROL); + + Thread.sleep(FRAME_ACTIVATION_TIMEOUT); + + if (process.isAlive()) { + process.destroy(); + } + } catch (Throwable e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } // run() + + public void init() { + //Create instructions for the user here, as well as set up + // the environment -- set the layout manager, add buttons, + // etc. + + String[] instructions = + { + "This is an AUTOMATIC test", + "simply wait until it is done" + }; + Sysout.createDialog( ); + Sysout.printInstructions( instructions ); + + frame.setTitle("Drop target frame"); + frame.setLocation(200, 200); + + } // init() + + public void start() { + DropTargetPanel panel = new DropTargetPanel(); + frame.add(panel); + frame.pack(); + frame.setVisible(true); + + try { + Thread.sleep(FRAME_ACTIVATION_TIMEOUT); + + Point p = frame.getLocationOnScreen(); + Dimension d = frame.getSize(); + + String javaPath = System.getProperty("java.home", ""); + String command = javaPath + File.separator + "bin" + + File.separator + "java -cp " + System.getProperty("test.classes", ".") + + " NoFormatsCrashTest " + + p.x + " " + p.y + " " + d.width + " " + d.height; + + process = Runtime.getRuntime().exec(command); + ProcessResults pres = ProcessResults.doWaitFor(process); + System.err.println("Child VM return code: " + pres.exitValue); + + if (pres.stderr != null && pres.stderr.length() > 0) { + System.err.println("========= Child VM System.err ========"); + System.err.print(pres.stderr); + System.err.println("======================================"); + } + + if (pres.stdout != null && pres.stdout.length() > 0) { + System.err.println("========= Child VM System.out ========"); + System.err.print(pres.stdout); + System.err.println("======================================"); + } + + } catch (Throwable e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + + if (panel.isTestFailed()) { + throw new RuntimeException(); + } + } // start() + + public static int sign(int n) { + return n < 0 ? -1 : n > 0 ? 1 : 0; + } +} // class NoFormatsCrashTest + +class TestTransferable implements Transferable { + + public static DataFlavor dataFlavor = null; + static final Object data = new Object(); + + static { + DataFlavor df = null; + try { + df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + + "; class=java.lang.Object"); + } catch (ClassNotFoundException e) { + throw new ExceptionInInitializerError(e); + } + dataFlavor = df; + } + + public DataFlavor[] getTransferDataFlavors() { + return new DataFlavor[] { dataFlavor }; + } + + public boolean isDataFlavorSupported(DataFlavor df) { + return dataFlavor.equals(df); + } + + public Object getTransferData(DataFlavor df) + throws UnsupportedFlavorException, IOException { + if (!isDataFlavorSupported(df)) { + throw new UnsupportedFlavorException(df); + } + return data; + } +} + +class DragSourcePanel extends Panel { + public DragSourcePanel() { + final Transferable t = new TestTransferable(); + final DragSourceListener dsl = new DragSourceAdapter() { + public void dragDropEnd(DragSourceDropEvent dtde) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // This finishes child VM + System.exit(0); + } + }; + final DragGestureListener dgl = new DragGestureListener() { + public void dragGestureRecognized(DragGestureEvent dge) { + dge.startDrag(null, t, dsl); + } + }; + final DragSource ds = DragSource.getDefaultDragSource(); + final DragGestureRecognizer dgr = + ds.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY, + dgl); + } + + public Dimension getPreferredSize() { + return new Dimension(100, 100); + } +} + +class DropTargetPanel extends Panel { + private boolean testFailed = false; + public DropTargetPanel() { + final DropTargetListener dtl = new DropTargetAdapter() { + public void dragOver(DropTargetDragEvent dtde) { + try { + dtde.getCurrentDataFlavorsAsList(); + } catch (Exception e) { + testFailed = true; + e.printStackTrace(); + } + } + public void drop(DropTargetDropEvent dtde) { + dtde.rejectDrop(); + } + }; + final DropTarget dt = new DropTarget(this, dtl); + } + + public boolean isTestFailed() { + return testFailed; + } + + public Dimension getPreferredSize() { + return new Dimension(100, 100); + } +} + +class ProcessResults { + public int exitValue; + public String stdout; + public String stderr; + + public ProcessResults() { + exitValue = -1; + stdout = ""; + stderr = ""; + } + + /** + * Method to perform a "wait" for a process and return its exit value. + * This is a workaround for Process.waitFor() never returning. + */ + public static ProcessResults doWaitFor(Process p) { + ProcessResults pres = new ProcessResults(); + + InputStream in = null; + InputStream err = null; + + try { + in = p.getInputStream(); + err = p.getErrorStream(); + + boolean finished = false; + + while (!finished) { + try { + while (in.available() > 0) { + pres.stdout += (char)in.read(); + } + while (err.available() > 0) { + pres.stderr += (char)err.read(); + } + // Ask the process for its exitValue. If the process + // is not finished, an IllegalThreadStateException + // is thrown. If it is finished, we fall through and + // the variable finished is set to true. + pres.exitValue = p.exitValue(); + finished = true; + } + catch (IllegalThreadStateException e) { + // Process is not finished yet; + // Sleep a little to save on CPU cycles + Thread.currentThread().sleep(500); + } + } + if (in != null) in.close(); + if (err != null) err.close(); + } + catch (Throwable e) { + System.err.println("doWaitFor(): unexpected exception"); + e.printStackTrace(); + throw new RuntimeException(e); + } + return pres; + } +} + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout + { + private static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.show(); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.show(); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + dialog.displayMessage( messageIn ); + } + + }// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog + { + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("South", messageText); + + pack(); + + show(); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + } + + }// TestDialog class diff --git a/jdk/test/java/awt/regtesthelpers/process/ProcessCommunicator.java b/jdk/test/java/awt/regtesthelpers/process/ProcessCommunicator.java index 8c0e6db916a..8177a2d2ab3 100644 --- a/jdk/test/java/awt/regtesthelpers/process/ProcessCommunicator.java +++ b/jdk/test/java/awt/regtesthelpers/process/ProcessCommunicator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -25,21 +25,22 @@ package test.java.awt.regtesthelpers.process; import java.io.*; -/** This class is created to solve interprocess communication problems. +/** + * This class is created to solve interprocess communication problems. * When you need to write a regression test which should verify inter jvm * behavior such as DnD data transfer, Clipboard data transfer, focus * transfer etc., you could use the next scenario: * * 1. Write an implementation for the parent JVM, using applet test. - * 2. Write an implimentation for the child JVM or native application, using + * 2. Write an implementation for the child JVM or native application, using * main() function. * 3. Execute child process using ProcessCommunicator.executeChildProcess() * method. - * 4. You can decide whetherthe test is passed on the basis of + * 4. You can decide whether the test is passed on the basis of * ProcessResults class data. * - * Note: The class is not thread safe. You should access its methods only from the same - * thread. + * Note: The class is not thread safe. You should access its methods only from + * the same thread. */ public class ProcessCommunicator { @@ -48,31 +49,34 @@ public class ProcessCommunicator { private static final String javaPath = javaHome + File.separator + "bin" + File.separator + "java "; private static String command = ""; + private static volatile Process process; private ProcessCommunicator() {} - /** The same as {#link #executeChildProcess(Class,String)} except - * the {@code classPathArgument} parameter. The class path - * parameter is for the debug purposes + /** + * The same as {#link #executeChildProcess(Class,String)} except + * the {@code classPathArgument} parameter. The class path + * parameter is for the debug purposes * - * @param classToExecute is passed to the child JVM - * @param classPathArguments class path for the child JVM - * @param args arguments that will be passed to the executed class - * @return results of the executed {@code Process} + * @param classToExecute is passed to the child JVM + * @param classPathArguments class path for the child JVM + * @param args arguments that will be passed to the executed class + * @return results of the executed {@code Process} */ public static ProcessResults executeChildProcess(final Class classToExecute, final String classPathArguments, final String [] args) { try { String command = buildCommand(classToExecute, classPathArguments, args); - Process process = Runtime.getRuntime().exec(command); + process = Runtime.getRuntime().exec(command); return doWaitFor(process); } catch (IOException e) { throw new RuntimeException(e); } } - /** Executes child {code Process} + /** + * Executes child {code Process} * * @param classToExecute class to be executed as a child java process * @param args args to be passed in to the child process @@ -86,11 +90,11 @@ public class ProcessCommunicator { /** * Waits for a process and return its results. - * This is a workaround for Process.waitFor() never returning. + * This is a workaround for {@code Process.waitFor()} never returning. * * @return results of the executed {@code Process} */ - private static ProcessResults doWaitFor(final Process p) { + public static ProcessResults doWaitFor(final Process p) { ProcessResults pres = new ProcessResults(); final InputStream in; @@ -133,13 +137,14 @@ public class ProcessCommunicator { return pres; } - /** Builds command on the basis of the passed class name, - * class path and arguments. + /** + * Builds command on the basis of the passed class name, + * class path and arguments. * * @param classToExecute with class will be executed in the new JVM * @param classPathArguments java class path (only for test purposes) * @param args arguments for the new application. This could be used - * to pass some information from the parnent to child JVM. + * to pass some information from the parent to child JVM. * @return command to execute the {@code Process} */ private static String buildCommand(final Class classToExecute, @@ -162,11 +167,24 @@ public class ProcessCommunicator { return command; } - /** Could be used for the debug purposes. + /** + * Could be used for the debug purposes. * - * @return command that was build to execute the child process + * @return command that was build to execute the child process */ public static String getExecutionCommand () { return command; } + + /** + * Terminates the process created by {@code executeChildProcess} methods. + */ + public static void destroyProcess() { + if (process != null) { + if (process.isAlive()) { + process.destroy(); + } + process = null; + } + } } diff --git a/jdk/test/java/awt/security/WarningWindowDisposeTest/WarningWindowDisposeCrashTest.java b/jdk/test/java/awt/security/WarningWindowDisposeTest/WarningWindowDisposeCrashTest.java new file mode 100644 index 00000000000..298059054d9 --- /dev/null +++ b/jdk/test/java/awt/security/WarningWindowDisposeTest/WarningWindowDisposeCrashTest.java @@ -0,0 +1,54 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8041490 + @summary tests that the WarningWindow's surface is invalidated on dispose + @author Petr Pchelko + @run main/othervm WarningWindowDisposeCrashTest +*/ + + +import sun.applet.AppletSecurity; +import sun.awt.SunToolkit; + +import java.awt.*; + +public class WarningWindowDisposeCrashTest { + public static void main(String[] args) throws Exception { + System.setSecurityManager(new AppletSecurity() { + @Override + public void checkPackageAccess (String s){ + } + }); + + Frame f = new Frame(); + f.setVisible(true); + ((SunToolkit) Toolkit.getDefaultToolkit()).realSync(); + Thread.sleep(1000); + f.dispose(); + // If the bug is present VM could crash after this call + for (int i = 0; i < 1000; i++) Toolkit.getDefaultToolkit().sync(); + } +} diff --git a/jdk/test/java/beans/Introspector/Test8040656.java b/jdk/test/java/beans/Introspector/Test8040656.java new file mode 100644 index 00000000000..73e80ac377f --- /dev/null +++ b/jdk/test/java/beans/Introspector/Test8040656.java @@ -0,0 +1,311 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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.beans.Introspector; +import java.beans.MethodDescriptor; + +/* + * @test + * @bug 8040656 + * @summary Tests that a normal method is preferred to a synthetic one + * @author Sergey Malenkov + */ + +public class Test8040656 { + public static void main(String[] args) throws Exception { + test(String.class, C.class); + test(String.class, C1.class); + test(String.class, C2.class); + test(String.class, C3.class); + test(String.class, C4.class); + test(String.class, C5.class); + test(String.class, C6.class); + test(String.class, C7.class); + test(String.class, C8.class); + test(String.class, C9.class); + } + + private static void test(Class type, Class bean) throws Exception { + for (MethodDescriptor md : Introspector.getBeanInfo(bean).getMethodDescriptors()) { + if (md.getName().equals("getFoo")) { + if (type != md.getMethod().getReturnType()) { + throw new Error("unexpected type"); + } + } + } + } + + public interface A { + public Object getFoo(); + } + + public class C implements A { + @Override + public String getFoo() { + return null; + } + } + + public class C1 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + } + + public class C2 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + } + + public class C3 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + + public String getFoo3() { + return null; + } + } + + public class C4 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + + public String getFoo3() { + return null; + } + + public String getFoo4() { + return null; + } + } + + public class C5 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + + public String getFoo3() { + return null; + } + + public String getFoo4() { + return null; + } + + public String getFoo5() { + return null; + } + } + + public class C6 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + + public String getFoo3() { + return null; + } + + public String getFoo4() { + return null; + } + + public String getFoo5() { + return null; + } + + public String getFoo6() { + return null; + } + } + + public class C7 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + + public String getFoo3() { + return null; + } + + public String getFoo4() { + return null; + } + + public String getFoo5() { + return null; + } + + public String getFoo6() { + return null; + } + + public String getFoo7() { + return null; + } + } + + public class C8 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + + public String getFoo3() { + return null; + } + + public String getFoo4() { + return null; + } + + public String getFoo5() { + return null; + } + + public String getFoo6() { + return null; + } + + public String getFoo7() { + return null; + } + + public String getFoo8() { + return null; + } + } + + public class C9 implements A { + @Override + public String getFoo() { + return null; + } + + public String getFoo1() { + return null; + } + + public String getFoo2() { + return null; + } + + public String getFoo3() { + return null; + } + + public String getFoo4() { + return null; + } + + public String getFoo5() { + return null; + } + + public String getFoo6() { + return null; + } + + public String getFoo7() { + return null; + } + + public String getFoo8() { + return null; + } + + public String getFoo9() { + return null; + } + } +} diff --git a/jdk/test/java/lang/ProcessBuilder/Basic.java b/jdk/test/java/lang/ProcessBuilder/Basic.java index ce0bad7772f..039feb16404 100644 --- a/jdk/test/java/lang/ProcessBuilder/Basic.java +++ b/jdk/test/java/lang/ProcessBuilder/Basic.java @@ -26,7 +26,7 @@ * @bug 4199068 4738465 4937983 4930681 4926230 4931433 4932663 4986689 * 5026830 5023243 5070673 4052517 4811767 6192449 6397034 6413313 * 6464154 6523983 6206031 4960438 6631352 6631966 6850957 6850958 - * 4947220 7018606 7034570 4244896 5049299 + * 4947220 7018606 7034570 4244896 5049299 8003488 * @summary Basic tests for Process and Environment Variable code * @run main/othervm/timeout=300 Basic * @run main/othervm/timeout=300 -Djdk.lang.Process.launchMechanism=fork Basic @@ -1136,6 +1136,53 @@ public class Basic { } } + static void checkProcessPid() { + long actualPid = 0; + long expectedPid = -1; + if (Windows.is()) { + String[] argsTasklist = {"tasklist.exe", "/NH", "/FI", "\"IMAGENAME eq tasklist.exe\""}; + ProcessBuilder pb = new ProcessBuilder(argsTasklist); + try { + Process proc = pb.start(); + expectedPid = proc.getPid(); + + String output = commandOutput(proc); + String[] splits = output.split("\\s+"); + actualPid = Integer.valueOf(splits[2]); + } catch (Throwable t) { + unexpected(t); + } + } else if (Unix.is() || MacOSX.is()) { + String[] shArgs = {"sh", "-c", "echo $$"}; + ProcessBuilder pb = new ProcessBuilder(shArgs); + try { + Process proc = pb.start(); + expectedPid = proc.getPid(); + + String output = commandOutput(proc); + String[] splits = output.split("\\s+"); + actualPid = Integer.valueOf(splits[0]); + } catch (Throwable t) { + unexpected(t); + } + } else { + fail("No test for checkProcessPid on platform: " + System.getProperty("os.name")); + return; + } + + equal(actualPid, expectedPid); + + // Test the default implementation of Process.getPid + try { + DelegatingProcess p = new DelegatingProcess(null); + p.getPid(); + fail("non-overridden Process.getPid method should throw UOE"); + } catch (UnsupportedOperationException uoe) { + // correct + } + + } + private static void realMain(String[] args) throws Throwable { if (Windows.is()) System.out.println("This appears to be a Windows system."); @@ -1147,6 +1194,11 @@ public class Basic { try { testIORedirection(); } catch (Throwable t) { unexpected(t); } + //---------------------------------------------------------------- + // Basic tests for getPid() + //---------------------------------------------------------------- + checkProcessPid(); + //---------------------------------------------------------------- // Basic tests for setting, replacing and deleting envvars //---------------------------------------------------------------- diff --git a/jdk/test/java/lang/annotation/TypeVariableBounds.java b/jdk/test/java/lang/annotation/TypeVariableBounds.java new file mode 100644 index 00000000000..1a2e33ae396 --- /dev/null +++ b/jdk/test/java/lang/annotation/TypeVariableBounds.java @@ -0,0 +1,129 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8038994 + * @summary Test that getAnnotatedBounds().getType() match getBounds() + * @run testng TypeVariableBounds + */ + +import java.io.Serializable; +import java.lang.annotation.*; +import java.lang.reflect.*; +import java.util.concurrent.Callable; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import static org.testng.Assert.*; + +public class TypeVariableBounds { + @Test(dataProvider = "classData") + public void testClass(Class c) throws Exception { + assertNotEquals(c.getTypeParameters().length, 0); + + TypeVariable[] tv = c.getTypeParameters(); + + for(TypeVariable t : tv) + testTv(t); + + } + + @Test(dataProvider = "methodData") + public void testMethod(Classc) throws Exception { + Method m = c.getMethod("aMethod"); + TypeVariable[] tv = m.getTypeParameters(); + + for(TypeVariable t : tv) + testTv(t); + + } + + public void testTv(TypeVariable tv) { + Type[] t = tv.getBounds(); + AnnotatedType[] at = tv.getAnnotatedBounds(); + + assertEquals(t.length, at.length, Arrays.asList(t) + " and " + Arrays.asList(at) + " should be the same length"); + + for (int i = 0; i < t.length; i++) + assertSame(at[i].getType(), t[i], "T: " + t[i] + ", AT: " + at[i] + ", AT.getType(): " + at[i].getType() + "\n"); + } + + @DataProvider + public Object[][] classData() { return CLASS_TESTS; } + + @DataProvider + public Object[][] methodData() { return METHOD_TESTS; } + + public static final Object[][] CLASS_TESTS = { + { Case1.class, }, + { Case2.class, }, + { Case5.class, }, + { Case6.class, }, + }; + + public static final Object[][] METHOD_TESTS = { + { Case3.class, }, + { Case4.class, }, + { Case5.class, }, + { Case6.class, }, + }; + + // Class type var + public static class Case1 {} + public static class Case2 {} + + // Method type var + public static class Case3 { public void aMethod() {}} + public static class Case4 { public void aMethod() {}} + + // Both + public static class Case5 { + public + void aMethod() {}} + + public static class Case6 <@TA C6CT1, C6CT2 extends @TB Runnable> { + public <@TA C6MT1, + C6MT2 extends @TB AnnotatedElement, + C6MT3 extends @TB AnnotatedElement & @TB2 Type & Serializable, + C6MT4 extends @TB2 C6CT2> + void aMethod() {}} + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE_PARAMETER) + public @interface TA {} + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE_USE) + public @interface TB {} + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE_USE) + public @interface TB2 {} +} diff --git a/jdk/test/java/lang/instrument/DaemonThread/TestDaemonThread.java b/jdk/test/java/lang/instrument/DaemonThread/TestDaemonThread.java index 20c9077d02f..12246b1a676 100644 --- a/jdk/test/java/lang/instrument/DaemonThread/TestDaemonThread.java +++ b/jdk/test/java/lang/instrument/DaemonThread/TestDaemonThread.java @@ -26,7 +26,7 @@ * @summary Assert in java.lang.instrument agents during shutdown when classloading occurs after shutdown * @library /lib/testlibrary * - * @build DummyAgent DummyClass TestDaemonThreadLauncher TestDaemonThread + * @build jdk.testlibrary.* DummyAgent DummyClass TestDaemonThreadLauncher TestDaemonThread * @run shell ../MakeJAR3.sh DummyAgent * @run main TestDaemonThreadLauncher /timeout=240 * diff --git a/jdk/test/java/lang/invoke/LambdaFormTest.java b/jdk/test/java/lang/invoke/LambdaFormTest.java new file mode 100644 index 00000000000..f078189c5c0 --- /dev/null +++ b/jdk/test/java/lang/invoke/LambdaFormTest.java @@ -0,0 +1,78 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 + * @summary unit tests for java.lang.invoke.LambdaForm + * @run junit/othervm test.java.lang.invoke.LambdaFormTest + */ +package test.java.lang.invoke; + +import org.junit.Test; +import java.lang.reflect.Method; +import static org.junit.Assert.*; + +public class LambdaFormTest { + static final Method M_shortenSignature; + static { + try { + Class impl = Class.forName("java.lang.invoke.LambdaForm", false, null); + Method m = impl.getDeclaredMethod("shortenSignature", String.class); + m.setAccessible(true); + M_shortenSignature = m; + } catch(Exception e) { + throw new AssertionError(e); + } + } + + public static String shortenSignature(String signature) throws ReflectiveOperationException { + return (String)M_shortenSignature.invoke(null, signature); + } + + @Test + public void testShortenSignature() throws ReflectiveOperationException { + for (String s : new String[] { + // invariant strings: + "L", "LL", "ILL", "LIL", "LLI", "IILL", "ILIL", "ILLI", + // a few mappings: + "LLL=L3", "LLLL=L4", "LLLLLLLLLL=L10", + "IIIDDD=I3D3", "IDDD=ID3", "IIDDD=IID3", "IIID=I3D", "IIIDD=I3DD" + }) { + String s2 = s.substring(s.indexOf('=')+1); + String s1 = s.equals(s2) ? s : s.substring(0, s.length() - s2.length() - 1); + // mix the above cases with before and after reps of Z* + for (int k = -3; k <= 3; k++) { + String beg = (k < 0 ? "ZZZZ".substring(-k) : ""); + String end = (k > 0 ? "ZZZZ".substring(+k) : ""); + String ks1 = beg+s1+end; + String ks2 = shortenSignature(beg)+s2+shortenSignature(end); + String ks3 = shortenSignature(ks1); + assertEquals(ks2, ks3); + } + } + } + + public static void main(String[] args) throws ReflectiveOperationException { + LambdaFormTest test = new LambdaFormTest(); + test.testShortenSignature(); + } +} diff --git a/jdk/test/java/lang/invoke/lambda/LogGeneratedClassesTest.java b/jdk/test/java/lang/invoke/lambda/LogGeneratedClassesTest.java index dc34bba24b9..33acc50d667 100644 --- a/jdk/test/java/lang/invoke/lambda/LogGeneratedClassesTest.java +++ b/jdk/test/java/lang/invoke/lambda/LogGeneratedClassesTest.java @@ -33,11 +33,9 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.nio.file.Files; -import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.PosixFileAttributeView; -import java.util.stream.Stream; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -163,34 +161,66 @@ public class LogGeneratedClassesTest extends LUtils { tr.assertZero("Should still return 0"); } + private static boolean isWriteableDirectory(Path p) { + if (!Files.isDirectory(p)) { + return false; + } + Path test = p.resolve(Paths.get("test")); + try { + Files.createFile(test); + assertTrue(Files.exists(test)); + return true; + } catch (IOException e) { + assertFalse(Files.exists(test)); + return false; + } finally { + if (Files.exists(test)) { + try { + Files.delete(test); + } catch (IOException e) { + throw new Error(e); + } + } + } + } + @Test public void testDumpDirNotWritable() throws IOException { - if (! Files.getFileStore(Paths.get(".")) - .supportsFileAttributeView(PosixFileAttributeView.class)) { + if (!Files.getFileStore(Paths.get(".")) + .supportsFileAttributeView(PosixFileAttributeView.class)) { // No easy way to setup readonly directory without POSIX // We would like to skip the test with a cause with // throw new SkipException("Posix not supported"); // but jtreg will report failure so we just pass the test // which we can look at if jtreg changed its behavior + System.out.println("WARNING: POSIX is not supported. Skipping testDumpDirNotWritable test."); return; } Files.createDirectory(Paths.get("readOnly"), asFileAttribute(fromString("r-xr-xr-x"))); + try { + if (isWriteableDirectory(Paths.get("readOnly"))) { + // Skipping the test: it's allowed to write into read-only directory + // (e.g. current user is super user). + System.out.println("WARNING: readOnly directory is writeable. Skipping testDumpDirNotWritable test."); + return; + } - TestResult tr = doExec(JAVA_CMD.getAbsolutePath(), - "-cp", ".", - "-Djdk.internal.lambda.dumpProxyClasses=readOnly", - "-Djava.security.manager", - "com.example.TestLambda"); - assertEquals(tr.testOutput.stream() - .filter(s -> s.startsWith("WARNING")) - .peek(s -> assertTrue(s.contains("not writable"))) - .count(), - 1, "only show error once"); - tr.assertZero("Should still return 0"); - - TestUtil.removeAll(Paths.get("readOnly")); + TestResult tr = doExec(JAVA_CMD.getAbsolutePath(), + "-cp", ".", + "-Djdk.internal.lambda.dumpProxyClasses=readOnly", + "-Djava.security.manager", + "com.example.TestLambda"); + assertEquals(tr.testOutput.stream() + .filter(s -> s.startsWith("WARNING")) + .peek(s -> assertTrue(s.contains("not writable"))) + .count(), + 1, "only show error once"); + tr.assertZero("Should still return 0"); + } finally { + TestUtil.removeAll(Paths.get("readOnly")); + } } @Test diff --git a/jdk/test/java/lang/management/MemoryMXBean/ResetPeakMemoryUsage.java b/jdk/test/java/lang/management/MemoryMXBean/ResetPeakMemoryUsage.java index f15fd2b007d..c0d5ad57e46 100644 --- a/jdk/test/java/lang/management/MemoryMXBean/ResetPeakMemoryUsage.java +++ b/jdk/test/java/lang/management/MemoryMXBean/ResetPeakMemoryUsage.java @@ -33,7 +33,7 @@ * @author Mandy Chung * * @library /lib/testlibrary/ - * @build ResetPeakMemoryUsage MemoryUtil RunUtil + * @build jdk.testlibrary.* ResetPeakMemoryUsage MemoryUtil RunUtil * @run main ResetPeakMemoryUsage */ diff --git a/jdk/test/java/sql/util/BaseTest.java b/jdk/test/java/sql/util/BaseTest.java index 2668c4899c7..130dae8fb4e 100644 --- a/jdk/test/java/sql/util/BaseTest.java +++ b/jdk/test/java/sql/util/BaseTest.java @@ -61,29 +61,31 @@ public class BaseTest { public void tearDownMethod() throws Exception { } - /** + /* * Take some form of SQLException, serialize and deserialize it - * - * @param SQLException - * @param ex SQLException - * @return deserialized SQLException - * @throws IOException - * @throws ClassNotFoundException */ @SuppressWarnings("unchecked") protected T createSerializedException(T ex) throws IOException, ClassNotFoundException { - T ex1; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try (ObjectOutputStream oos = new ObjectOutputStream(baos) ) { - oos.writeObject(ex); - } - try (ObjectInputStream ois = - new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) { - ex1 = (T) ois.readObject(); - } - return ex1; + return (T) serializeDeserializeObject(ex); } + /* + * Utility method to serialize and deserialize an object + */ + @SuppressWarnings("unchecked") + protected T serializeDeserializeObject(T o) + throws IOException, ClassNotFoundException { + T o1; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { + oos.writeObject(o); + } + try (ObjectInputStream ois + = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) { + o1 = (T) ois.readObject(); + } + return o1; + } } diff --git a/jdk/test/java/util/BitSet/BSMethods.java b/jdk/test/java/util/BitSet/BSMethods.java index 9aa419ac9bf..86d7499a428 100644 --- a/jdk/test/java/util/BitSet/BSMethods.java +++ b/jdk/test/java/util/BitSet/BSMethods.java @@ -26,6 +26,7 @@ * 4979017 4979028 4979031 5030267 6222207 8040806 * @summary Test the operation of the methods of BitSet class * @author Mike McCloskey, Martin Buchholz + * @run main/othervm BSMethods */ import java.util.*; @@ -897,15 +898,20 @@ public class BSMethods { private static void testToString() { check(new BitSet().toString().equals("{}")); check(makeSet(2,3,42,43,234).toString().equals("{2, 3, 42, 43, 234}")); - try { - check(makeSet(Integer.MAX_VALUE-1).toString().equals( - "{" + (Integer.MAX_VALUE-1) + "}")); - check(makeSet(Integer.MAX_VALUE).toString().equals( - "{" + Integer.MAX_VALUE + "}")); - check(makeSet(0, 1, Integer.MAX_VALUE-1, Integer.MAX_VALUE).toString().equals( - "{0, 1, " + (Integer.MAX_VALUE-1) + ", " + Integer.MAX_VALUE + "}")); - } catch (IndexOutOfBoundsException exc) { - fail("toString() with indices near MAX_VALUE"); + + final long MB = 1024*1024; + if (Runtime.getRuntime().maxMemory() >= 512*MB) { + // only run it if we have enough memory + try { + check(makeSet(Integer.MAX_VALUE-1).toString().equals( + "{" + (Integer.MAX_VALUE-1) + "}")); + check(makeSet(Integer.MAX_VALUE).toString().equals( + "{" + Integer.MAX_VALUE + "}")); + check(makeSet(0, 1, Integer.MAX_VALUE-1, Integer.MAX_VALUE).toString().equals( + "{0, 1, " + (Integer.MAX_VALUE-1) + ", " + Integer.MAX_VALUE + "}")); + } catch (IndexOutOfBoundsException exc) { + fail("toString() with indices near MAX_VALUE"); + } } } diff --git a/jdk/test/java/util/Properties/LoadAndStoreXML.java b/jdk/test/java/util/Properties/LoadAndStoreXML.java index 5353c645b81..241a783053f 100644 --- a/jdk/test/java/util/Properties/LoadAndStoreXML.java +++ b/jdk/test/java/util/Properties/LoadAndStoreXML.java @@ -32,6 +32,7 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; @@ -47,6 +48,7 @@ import java.util.Properties; import java.util.PropertyPermission; public class LoadAndStoreXML { + static final String bomChar = "\uFEFF"; /** * Simple policy implementation that grants a set of permissions to @@ -125,13 +127,14 @@ public class LoadAndStoreXML { * Sanity test that properties saved with Properties#storeToXML can be * read with Properties#loadFromXML. */ - static void testLoadAndStore(String encoding) throws IOException { + static void testLoadAndStore(String encoding, boolean appendBOM) throws IOException { System.out.println("testLoadAndStore, encoding=" + encoding); Properties props = new Properties(); + props.put("k0", "\u6C34"); props.put("k1", "foo"); props.put("k2", "bar"); - props.put("k3", "\\u0020\\u0391\\u0392\\u0393\\u0394\\u0395\\u0396\\u0397"); + props.put("k3", "\u0020\u0391\u0392\u0393\u0394\u0395\u0396\u0397"); props.put("k4", "\u7532\u9aa8\u6587"); props.put("k5", "/lib/jaxp.properties"); @@ -141,7 +144,17 @@ public class LoadAndStoreXML { throw new RuntimeException("OutputStream closed by storeToXML"); Properties p = new Properties(); - TestInputStream in = new TestInputStream(out.toByteArray()); + TestInputStream in; + if (appendBOM) { + byte[] byteOrderMark = bomChar.getBytes(Charset.forName(encoding)); + byte[] outArray = out.toByteArray(); + byte[] inputArray = new byte[byteOrderMark.length + outArray.length]; + System.arraycopy(byteOrderMark, 0, inputArray, 0, byteOrderMark.length); + System.arraycopy(outArray, 0, inputArray, byteOrderMark.length, outArray.length); + in = new TestInputStream(inputArray); + } else { + in = new TestInputStream(out.toByteArray()); + } p.loadFromXML(in); if (in.isOpen()) throw new RuntimeException("InputStream not closed by loadFromXML"); @@ -231,8 +244,12 @@ public class LoadAndStoreXML { public static void main(String[] args) throws IOException { - testLoadAndStore("UTF-8"); - testLoadAndStore("UTF-16"); + testLoadAndStore("UTF-8", false); + testLoadAndStore("UTF-16", false); + testLoadAndStore("UTF-16BE", false); + testLoadAndStore("UTF-16LE", false); + testLoadAndStore("UTF-16BE", true); + testLoadAndStore("UTF-16LE", true); testLoadWithoutEncoding(); testLoadWithBadEncoding(); testStoreWithBadEncoding(); @@ -250,7 +267,7 @@ public class LoadAndStoreXML { Policy.setPolicy(p); System.setSecurityManager(new SecurityManager()); try { - testLoadAndStore("UTF-8"); + testLoadAndStore("UTF-8", false); } finally { // turn off security manager and restore policy System.setSecurityManager(null); diff --git a/jdk/test/javax/imageio/plugins/png/ReadMalformedPngTest.java b/jdk/test/javax/imageio/plugins/png/ReadMalformedPngTest.java new file mode 100644 index 00000000000..7aadebc627b --- /dev/null +++ b/jdk/test/javax/imageio/plugins/png/ReadMalformedPngTest.java @@ -0,0 +1,160 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 6945174 + * @summary Test verifies that PNG image readr throw correct exception + * if image contains a chunk with incorrect length. + * @run main ReadMalformedPngTest + */ + +import java.awt.Color; +import java.awt.GradientPaint; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import javax.imageio.IIOException; +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageTypeSpecifier; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.metadata.IIOMetadata; +import javax.imageio.metadata.IIOMetadataNode; +import javax.imageio.stream.ImageOutputStream; +import org.w3c.dom.Node; + +public class ReadMalformedPngTest { + + public static void main(String[] args) throws IOException { + ByteArrayInputStream bais = new ByteArrayInputStream(createTestPng()); + + IIOException expected = null; + try { + ImageIO.read(bais); + } catch (IIOException e) { + expected = e; + } catch (Throwable e) { + throw new RuntimeException("Test failed!", e); + } + + if (expected == null) { + throw new RuntimeException("Test failed."); + } + + System.out.println("Test passed."); + } + + private static byte[] createTestPng() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + BufferedImage img = createTestImage(); + + try { + ImageOutputStream ios = ImageIO.createImageOutputStream(baos); + + ImageWriter w = ImageIO.getImageWritersByFormatName("PNG").next(); + + w.setOutput(ios); + + ImageWriteParam p = w.getDefaultWriteParam(); + + ImageTypeSpecifier t = ImageTypeSpecifier.createFromRenderedImage(img); + + IIOMetadata m = w.getDefaultImageMetadata(t, p); + + String nativeMetadataFormat = m.getNativeMetadataFormatName(); + + Node root = m.getAsTree(nativeMetadataFormat); + + IIOMetadataNode textEntry = new IIOMetadataNode("tEXtEntry"); + textEntry.setAttribute("keyword", "comment"); + textEntry.setAttribute("value", "This is a test image for JDK-6945174"); + + IIOMetadataNode text = new IIOMetadataNode("tEXt"); + text.appendChild(textEntry); + + root.appendChild(text); + + m.mergeTree(nativeMetadataFormat, root); + + IIOImage iio_img = new IIOImage(img, null, m); + + w.write(iio_img); + + w.dispose(); + ios.flush(); + ios.close(); + } catch (IOException e) { + throw new RuntimeException("Test failed.", e); + } + + baos.flush(); + + byte[] data = baos.toByteArray(); + + adjustCommentLength(Integer.MAX_VALUE + 0x1000, data); + + return data; + } + + private static void adjustCommentLength(int v, byte[] data) { + final int pos = getCommentPos(data); + data[pos + 3] = (byte) (v & 0xFF); + v = v >> 8; + data[pos + 2] = (byte) (v & 0xFF); + v = v >> 8; + data[pos + 1] = (byte) (v & 0xFF); + v = v >> 8; + data[pos + 0] = (byte) (v & 0xFF); + } + + private static int getCommentPos(byte[] d) { + int p = 8; + while (p + 8 < d.length) { + if (d[p + 4] == (byte) 0x74 && d[p + 5] == (byte) 0x45 && + d[p + 6] == (byte) 0x58 && d[p + 7] == (byte) 0x74) + { + return p; + } + p++; + } + throw new RuntimeException("Test chunk was not found!"); + } + + private static BufferedImage createTestImage() { + final int w = 128; + final int h = 128; + + BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR); + Graphics2D g = img.createGraphics(); + g.setPaint(new GradientPaint(0, 0, Color.blue, + w, h, Color.red)); + g.fillRect(0, 0, w, h); + g.dispose(); + return img; + } +} diff --git a/jdk/test/javax/sql/testng/TEST.properties b/jdk/test/javax/sql/testng/TEST.properties new file mode 100644 index 00000000000..97d1bc3a5a0 --- /dev/null +++ b/jdk/test/javax/sql/testng/TEST.properties @@ -0,0 +1,2 @@ +# JDBC unit tests uses TestNG +TestNG.dirs= . \ No newline at end of file diff --git a/jdk/test/javax/sql/testng/test/rowset/serial/SerialArrayTests.java b/jdk/test/javax/sql/testng/test/rowset/serial/SerialArrayTests.java new file mode 100644 index 00000000000..077ce43da85 --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/serial/SerialArrayTests.java @@ -0,0 +1,236 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 test.rowset.serial; + +import java.sql.Array; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import javax.sql.rowset.serial.SerialArray; +import javax.sql.rowset.serial.SerialException; +import static org.testng.Assert.*; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import util.BaseTest; +import util.StubArray; + +public class SerialArrayTests extends BaseTest { + + private Object[] coffees; + private final String sqlType = "VARCHAR"; + private Array a; + private Map> map; + + @BeforeMethod + public void setUpMethod() throws Exception { + coffees = new Object[]{"Espresso", "Colombian", "French Roast", + "Cappuccino"}; + a = new StubArray(sqlType, coffees); + map = new HashMap<>(); + } + + /* + * Validate a SerialArray can be created from an Array + */ + @Test + public void test01() throws Exception { + SerialArray sa = new SerialArray(a); + } + + /* + * Validate a SQLException is thrown if the map is null + */ + @Test(expectedExceptions = SQLException.class) + public void test02() throws Exception { + SerialArray sa = new SerialArray(a, null); + } + + /* + * Validate a SerialException is thrown when getResultSet() is called + */ + @Test(expectedExceptions = SerialException.class) + public void test03() throws Exception { + SerialArray sa = new SerialArray(a); + sa.getResultSet(); + } + + /* + * Validate a SerialException is thrown when getResultSet() is called + */ + @Test(expectedExceptions = SerialException.class) + public void test04() throws Exception { + SerialArray sa = new SerialArray(a); + sa.getResultSet(null); + } + + /* + * Validate a SerialException is thrown when getResultSet() is called + */ + @Test(expectedExceptions = SerialException.class) + public void test05() throws Exception { + SerialArray sa = new SerialArray(a); + sa.getResultSet(1, 1); + } + + /* + * Validate a SerialException is thrown when getResultSet() is called + */ + @Test(expectedExceptions = SerialException.class) + public void test06() throws Exception { + SerialArray sa = new SerialArray(a); + sa.getResultSet(1, 1, null); + } + + /* + * Validate a SerialException is thrown when getArray() is invoked after + * free() is called + */ + @Test(expectedExceptions = SerialException.class) + public void test07() throws Exception { + SerialArray sa = new SerialArray(a); + sa.free(); + sa.getArray(); + } + + /* + * Validate a SerialException is thrown when getArray() is invoked after + * free() is called + */ + @Test(expectedExceptions = SerialException.class) + public void test08() throws Exception { + SerialArray sa = new SerialArray(a); + sa.free(); + sa.getArray(map); + } + + /* + * Validate a SerialException is thrown when getArray() is invoked after + * free() is called + */ + @Test(expectedExceptions = SerialException.class) + public void test09() throws Exception { + SerialArray sa = new SerialArray(a); + sa.free(); + sa.getArray(1, 1, map); + } + + /* + * Validate a SerialException is thrown when getArray() is invoked after + * free() is called + */ + @Test(expectedExceptions = SerialException.class) + public void test10() throws Exception { + SerialArray sa = new SerialArray(a); + sa.free(); + sa.getArray(1, 1); + } + + /* + * Validate a SerialException is thrown when getBaseType() is invoked after + * free() is called + */ + @Test(expectedExceptions = SerialException.class) + public void test11() throws Exception { + SerialArray sa = new SerialArray(a); + sa.free(); + sa.getBaseType(); + } + + /* + * Validate a SerialException is thrown when getBaseTypeName() is invoked after + * free() is called + */ + @Test(expectedExceptions = SerialException.class) + public void test12() throws Exception { + SerialArray sa = new SerialArray(a); + sa.free(); + sa.getBaseTypeName(); + } + + /* + * Validate getArray() returns the same Object[] used to create the + * SerialArray + */ + @Test + public void test13() throws Exception { + SerialArray sa = new SerialArray(a); + Object[] o = (Object[]) sa.getArray(); + assertTrue(Arrays.equals(o, coffees)); + } + + /* + * Validate getArray() returns the same Object[] used to create the + * SerialArray + */ + @Test + public void test14() throws Exception { + SerialArray sa = new SerialArray(a); + Object[] o = (Object[]) sa.getArray(map); + assertTrue(Arrays.equals(o, coffees)); + } + + /* + * Validate getArray() returns the same Object[] used to create the + * SerialArray + */ + @Test + public void test15() throws Exception { + SerialArray sa = new SerialArray(a); + Object[] o = (Object[]) sa.getArray(1, 2); + assertTrue(Arrays.equals(o, Arrays.copyOfRange(coffees, 1, 3))); + } + + /* + * Validate getArray() returns the same Object[] used to create the + * SerialArray + */ + @Test + public void test16() throws Exception { + SerialArray sa = new SerialArray(a); + Object[] o = (Object[]) sa.getArray(1, 2, map); + assertTrue(Arrays.equals(o, Arrays.copyOfRange(coffees, 1, 3))); + } + + /* + * clone() a SerialArray and check that it is equal to the + * object it was cloned from + */ + @Test + public void test17() throws Exception { + SerialArray sa = new SerialArray(a); + SerialArray sa1 = (SerialArray) sa.clone(); + assertTrue(sa.equals(sa1)); + } + + /* + * Validate that a SerialArray that is serialized & deserialized is equal to + * itself + */ + @Test + public void test18() throws Exception { + SerialArray sa = new SerialArray(a); + SerialArray sa1 = serializeDeserializeObject(sa);; + assertTrue(sa.equals(sa1)); + } +} diff --git a/jdk/test/javax/sql/testng/test/rowset/serial/SerialBlobTests.java b/jdk/test/javax/sql/testng/test/rowset/serial/SerialBlobTests.java new file mode 100644 index 00000000000..e080b1ca1b9 --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/serial/SerialBlobTests.java @@ -0,0 +1,399 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 test.rowset.serial; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; +import javax.sql.rowset.serial.SerialBlob; +import javax.sql.rowset.serial.SerialException; +import static org.testng.Assert.*; +import org.testng.annotations.Test; +import util.BaseTest; +import util.StubBlob; + +public class SerialBlobTests extends BaseTest { + + // byte[] used to populate SerialBlob + private byte[] bytes = new byte[]{1, 2, 3, 4, 5}; + + /* + * Validate calling free() does not throw an Exception + */ + @Test + public void test() throws Exception { + SerialBlob sb = new SerialBlob(new StubBlob()); + sb.free(); + } + + /* + * Validate calling getBinaryStream() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test01() throws Exception { + SerialBlob sb = new SerialBlob(new StubBlob()); + sb.free(); + sb.getBinaryStream(); + } + + /* + * Validate calling getBinaryStream() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test02() throws Exception { + SerialBlob sb = new SerialBlob(new StubBlob()); + sb.free(); + sb.getBinaryStream(1, 5); + } + + /* + * Validate calling getBytes() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test03() throws Exception { + SerialBlob sb = new SerialBlob(new StubBlob()); + sb.free(); + sb.getBytes(1, 1); + } + + /* + * Validate calling getLength() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test04() throws Exception { + SerialBlob sb = new SerialBlob(new StubBlob()); + sb.free(); + sb.length(); + } + + /* + * Validate calling position() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test05() throws Exception { + SerialBlob sb = new SerialBlob(new StubBlob()); + sb.free(); + sb.position(new byte[5], 1); + } + + /* + * Validate calling position() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test06() throws Exception { + SerialBlob sb = new SerialBlob(new StubBlob()); + sb.free(); + sb.position(new StubBlob(), 1); + } + + /* + * Validate calling free() after calling setBinaryStream() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test07() throws Exception { + SerialBlob sb = new SerialBlob(new StubBlob()); + sb.free(); + sb.setBinaryStream(5); + } + + /* + * Validate calling free() after calling setBytes() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test08() throws Exception { + SerialBlob sb = new SerialBlob(new StubBlob()); + sb.free(); + sb.setBytes(1, new byte[5]); + } + + /* + * Validate calling setBytes() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test09() throws Exception { + SerialBlob sb = new SerialBlob(new StubBlob()); + sb.free(); + sb.setBytes(1, new byte[10], 0, 5); + } + + /* + * Validate calling truncate() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test10() throws Exception { + SerialBlob sb = new SerialBlob(new StubBlob()); + sb.free(); + sb.truncate(1); + } + + /* + * Validate getBinaryStream returns the correct bytes + */ + @Test + public void test11() throws Exception { + byte[] expected = new byte[]{1, 2, 3}; + SerialBlob sb = new SerialBlob(bytes); + InputStream is = sb.getBinaryStream(1, 3); + for (byte b : expected) { + byte val = (byte) is.read(); + assertTrue(b == val, val + " does not match " + b); + } + } + + /* + * Validate a SerialException is thrown if pos < 0 for getBinaryStream + */ + @Test(expectedExceptions = SerialException.class) + public void test12() throws Exception { + SerialBlob sb = new SerialBlob(bytes); + InputStream is = sb.getBinaryStream(-1, 3); + } + + /* + * Validate a SerialException is thrown if pos = 0 for getBinaryStream + */ + @Test(expectedExceptions = SerialException.class) + public void test13() throws Exception { + SerialBlob sb = new SerialBlob(bytes); + InputStream is = sb.getBinaryStream(0, 3); + } + + /* + * Validate a SerialException is thrown if len > the length of the stream + * for getBinaryStream + */ + @Test(expectedExceptions = SerialException.class) + public void test14() throws Exception { + SerialBlob sb = new SerialBlob(bytes); + InputStream is = sb.getBinaryStream(0, 3); + } + + /* + * Validate a SerialException is thrown if length < 1 + */ + @Test(expectedExceptions = SerialException.class) + public void test15() throws Exception { + SerialBlob sb = new SerialBlob(bytes); + InputStream is = sb.getBinaryStream(1, 0); + } + + /* + * Validate a SerialException is thrown if length > byte array length + */ + @Test(expectedExceptions = SerialException.class) + public void test16() throws Exception { + SerialBlob sb = new SerialBlob(bytes); + InputStream is = sb.getBinaryStream(1, 6); + } + + /* + * Validate a SerialException is thrown if pos > byte array length + */ + @Test(expectedExceptions = SerialException.class) + public void test17() throws Exception { + SerialBlob sb = new SerialBlob(bytes); + InputStream is = sb.getBinaryStream(bytes.length + 2, 6); + } + + /* + * Validate that a cloned SerializedBlob bytes match the original + */ + @Test + public void test18() throws Exception { + SerialBlob sb = new SerialBlob(bytes); + SerialBlob sb2 = (SerialBlob) sb.clone(); + assertTrue( + Arrays.equals(sb.getBytes(1, (int) sb.length()), + sb2.getBytes(1, (int) sb2.length())), + "arrays do not match "); + } + + /* + * Test clone after free has been called that the clone is not accessible + */ + @Test(expectedExceptions = SerialException.class) + public void test19() throws Exception { + SerialBlob sb = new SerialBlob(bytes); + sb.free(); + SerialBlob sb2 = (SerialBlob) sb.clone(); + InputStream is = sb2.getBinaryStream(1, 3); + } + + /* + * Validate that a SerialBlob that is serialized & deserialized is equal to + * itself + */ + @Test + public void test20() throws Exception { + SerialBlob sb = new SerialBlob(bytes); + SerialBlob sb2 = serializeDeserializeObject(sb); + assertTrue(sb.equals(sb2), "SerialBlob not equal"); + } + + /* + * Validate a SerialException is thrown if byte[] is used to + * create the SeriablBlob and setBinaryStream is called + */ + @Test(expectedExceptions = SerialException.class) + public void test21() throws Exception { + SerialBlob sb = new SerialBlob(bytes); + sb.setBinaryStream(3); + } + + /* + * Validate that setBytes will properly write a set of bytes to the + * specified location in the SerialBlob and the correct count is returned + * for bytes written + */ + @Test + public void test22() throws Exception { + byte[] diff = new byte[]{7, 8, 9}; + byte[] expected = new byte[]{1, 7, 8, 9, 5}; + SerialBlob sb = new SerialBlob(bytes); + int written = sb.setBytes(2, diff); + assertEquals(written, diff.length); + assertTrue( + Arrays.equals(sb.getBytes(1, (int) sb.length()), + expected), + "arrays do not match "); + } + + /* + * Validate that setBytes will properly write a set of bytes to the + * specified location in the SerialBlob and the correct count is returned + * for bytes written + */ + @Test + public void test23() throws Exception { + int bytesToWrite = 3; + byte[] diff = new byte[]{7, 8, 9, 0}; + byte[] expected = new byte[]{1, 8, 9, 0, 5}; + SerialBlob sb = new SerialBlob(bytes); + int written = sb.setBytes(2, diff, 1, bytesToWrite); + assertEquals(written, bytesToWrite); + assertTrue( + Arrays.equals(sb.getBytes(1, (int) sb.length()), + expected), + "arrays do not match "); + } + + /* + * Validate that truncate reduces the length of the SerlizedBlob to the + * specified value + */ + @Test + public void test24() throws Exception { + SerialBlob sb = new SerialBlob(bytes); + sb.truncate(0); + assertTrue(sb.length() == 0); + sb = new SerialBlob(bytes); + sb.truncate(3); + assertTrue(sb.length() == 3); + } + + /* + * Validate getBinaryStream returns the correct bytes + */ + @Test + public void test25() throws Exception { + byte[] expected = bytes; + SerialBlob sb = new SerialBlob(bytes); + InputStream is = sb.getBinaryStream(); + for (byte b : expected) { + byte val = (byte) is.read(); + assertTrue(b == val, val + " does not match " + b); + } + } + + /* + * Validate setBinaryStream returns an OutputStream when passed a Blob + */ + @Test + public void test26() throws Exception { + SerialBlob sb = new SerialBlob(new StubBlob()); + OutputStream os = sb.setBinaryStream(0); + assertTrue(os != null); + } + + /* + * Validate that position returns the correct starting location for a + * pattern in the SerialBlob + */ + @Test + public void test27() throws Exception { + long expectedPos = 3; // starting offset is 1 vs 0 + byte[] pattern = new byte[]{3, 4}; + SerialBlob sb = new SerialBlob(bytes); + long pos = sb.position(pattern, 1); + assertEquals(pos, expectedPos); + } + + /* + * Validate that position returns the correct starting location for a + * pattern in the SerialBlob + */ + @Test + public void test28() throws Exception { + long expectedPos = 3; // starting offset is 1 vs 0 + byte[] pattern = new byte[]{3, 4, 5}; + SerialBlob sb = new SerialBlob(bytes); + long pos = sb.position(pattern, 2); + assertEquals(pos, expectedPos); + } + + /* + * Validate that position returns the correct starting location for a + * pattern in the SerialBlob + */ + @Test + public void test29() throws Exception { + long expectedPos = 2; // starting offset is 1 vs 0 + byte[] pattern = new byte[]{4, 6}; + SerialBlob sb = new SerialBlob(new StubBlob()); + long pos = sb.position(pattern, 1); + assertEquals(pos, expectedPos); + } + + /* + * Validate that position returns the correct starting location for a + * pattern in the SerialBlob + */ + @Test + public void test30() throws Exception { + long expectedPos = 3; // starting offset is 1 vs 0 + byte[] pattern = new byte[]{6, 8}; + SerialBlob sb = new SerialBlob(new StubBlob()); + long pos = sb.position(pattern, 2); + assertEquals(pos, expectedPos); + } +} diff --git a/jdk/test/javax/sql/testng/test/rowset/serial/SerialClobTests.java b/jdk/test/javax/sql/testng/test/rowset/serial/SerialClobTests.java new file mode 100644 index 00000000000..72f42674de0 --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/serial/SerialClobTests.java @@ -0,0 +1,499 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 test.rowset.serial; + +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; +import javax.sql.rowset.serial.SerialClob; +import javax.sql.rowset.serial.SerialException; +import static org.testng.Assert.*; +import org.testng.annotations.Test; +import util.BaseTest; +import util.StubClob; + +public class SerialClobTests extends BaseTest { + + // char[] used to populate SerialClob + private final char[] chars; + + public SerialClobTests() { + this.chars = new char[]{'h', 'e', 'l', 'l', 'o', ' ', 'w', + 'o', 'r', 'l', 'd'}; + } + + /* + * Validate calling free() does not throw an Exception + */ + @Test + public void test() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + sc.free(); + } + + /* + * Validate calling getCharacterStream() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test01() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + sc.free(); + sc.getCharacterStream(); + } + + /* + * Validate calling getCharacterStream() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test02() throws Exception { + SerialClob sc = new SerialClob(chars); + sc.free(); + sc.getCharacterStream(); + } + + /* + * Validate calling getCharacterStream() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test03() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + sc.free(); + sc.getCharacterStream(1, 5); + } + + /* + * Validate calling getSubString() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test04() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + sc.free(); + sc.getSubString(1, 1); + } + + /* + * Validate calling truncate() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test05() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + sc.free(); + sc.truncate(1); + } + + /* + * Validate calling getAsciiStream() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test06() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + sc.free(); + sc.getAsciiStream(); + } + + /* + * Validate calling length() after calling free() throws an SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test07() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + sc.free(); + sc.length(); + } + + /* + * Validate calling position() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test08() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + sc.free(); + sc.position("hello", 1); + } + + /* + * Validate calling position() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test09() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + sc.free(); + sc.position(new StubClob(), 1); + } + + /* + * Validate calling setAsciiStream() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test10() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + sc.free(); + sc.setAsciiStream(5); + } + + /* + * Validate calling setCharacterStream() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test11() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + sc.free(); + sc.setCharacterStream(5); + } + + /* + * Validate calling setString() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test12() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + sc.free(); + sc.setString(1, "hello"); + } + + /* + * Validate calling setString() after calling free() throws an + * SerialException + */ + @Test(expectedExceptions = SerialException.class) + public void test13() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + sc.free(); + sc.setString(1, "hello", 0, 5); + } + + /* + * Test that SerialException is thrown if pos < 0 on a call to + * getCharacterStream + */ + @Test(expectedExceptions = SerialException.class) + public void test14() throws Exception { + SerialClob sc = new SerialClob(chars); + sc.getCharacterStream(-1, 5); + } + + /* + * Test that SerialException is thrown if pos = 0 on a call to + * getCharacterStream + */ + @Test(expectedExceptions = SerialException.class) + public void test15() throws Exception { + SerialClob sc = new SerialClob(chars); + sc.getCharacterStream(0, 5); + } + + /* + * Test that SerialException is thrown if pos = 0 on a call to + * getCharacterStream + */ + @Test(expectedExceptions = SerialException.class) + public void test16() throws Exception { + SerialClob sc = new SerialClob(chars); + sc.getCharacterStream(1, 100); + } + + /* + * Test that SerialException is thrown if length = 0 on a call to + * getCharacterStream + */ + @Test(expectedExceptions = SerialException.class) + public void test17() throws Exception { + SerialClob sc = new SerialClob(chars); + sc.getCharacterStream(1, 0); + } + + /* + * Test that SerialException is thrown if pos > length on a call to + * getCharacterStream + */ + @Test(expectedExceptions = SerialException.class) + public void test18() throws Exception { + SerialClob sc = new SerialClob(chars); + sc.getCharacterStream(100, 5); + } + + /* + * Clone a SerialClob and check that it is equal to itself + */ + @Test + public void test19() throws Exception { + SerialClob sc = new SerialClob(chars); + SerialClob sc1 = (SerialClob) sc.clone(); + assertTrue(sc.equals(sc1), "SerialClobs not equal"); + } + + /* + * Validate that a getAsciiStream() returns an InputStream when a Clob is + * used to create the SerialClob + */ + @Test + public void test20() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + InputStream is = sc.getAsciiStream(); + assertTrue(is != null); + } + + /* + * Validate that a getCharacterStream() returns an Reader when a Clob is + * used to create the SerialClob + */ + @Test + public void test21() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + Reader is = sc.getCharacterStream(); + assertTrue(is != null); + } + + /* + * Validate that a getCharacterStream() returns an Reader when a char[] is + * used to create the SerialClob + */ + @Test + public void test22() throws Exception { + SerialClob sc = new SerialClob(chars); + Reader is = sc.getCharacterStream(); + assertTrue(is != null); + } + + /* + * Validate that a getSubString() returns the correct value when a char[] is + * used to create the SerialClob + */ + @Test + public void test23() throws Exception { + SerialClob sc = new SerialClob(chars); + String expected = "world"; + assertEquals(expected, sc.getSubString(7, 5)); + } + + /* + * Validate that a getSubString() returns the correct value when a Clob is + * used to create the SerialClob + */ + @Test + public void test24() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + String expected = "test string"; + assertEquals(expected, sc.getSubString(5, 11)); + } + + /* + * Validate that position() returns the correct value when a Clob is used to + * create the SerialClob + */ + @Test + public void test25() throws Exception { + long expectedPos = 5; + SerialClob sc = new SerialClob(new StubClob()); + String expected = "test string"; + long pos = sc.position(expected, 1); + assertEquals(expectedPos, pos); + } + + /* + * Validate that position returned is -1 when an the search string is not + * part of the SerialClob + */ + @Test + public void test26() throws Exception { + long expectedPos = -1; + SerialClob sc = new SerialClob(chars); + String expected = "test string"; + long pos = sc.position(expected, 1); + assertEquals(expectedPos, pos); + } + + /* + * Validate that position() returned is -1 when an the search string is not + * part of the SerialClob + */ + @Test + public void test27() throws Exception { + long expectedPos = -1; + SerialClob sc = new SerialClob(new StubClob()); + String expected = "I am Batman"; + long pos = sc.position(expected, 2); + assertEquals(expectedPos, pos); + } + + /* + * Validate that position() returns the correct value when a char[] is used + * to create the SerialClob + */ + @Test + public void test28() throws Exception { + long expectedPos = 2; + SerialClob sc = new SerialClob(chars); + String expected = "ello"; + long pos = sc.position(expected, 1); + assertEquals(expectedPos, pos); + } + + /* + * Validate that position() returns the correct value when a SerialClob is + * used for the search argument + */ + @Test + public void test29() throws Exception { + long expectedPos = 21; + String expected = "Batman"; + String buf = "I am Joker, not the Batman, hahaha"; + SerialClob sc = new SerialClob(expected.toCharArray()); + SerialClob sc1 = new SerialClob(buf.toCharArray()); + long pos = sc1.position(sc, 1); + assertEquals(expectedPos, pos); + } + + /* + * Validate that position() returns the correct value when a SerialClob is + * used for the search argument + */ + @Test + public void test30() throws Exception { + long expectedPos = 17; + String expected = "012"; + SerialClob sc = new SerialClob(expected.toCharArray()); + SerialClob sc1 = new SerialClob(new StubClob()); + long pos = sc1.position(sc, 1); + assertEquals(expectedPos, pos); + } + + /* + * Check that setString() updates the appropriate characters in the + * SerialClob + */ + @Test + public void test31() throws Exception { + String val = "Hello, I am Bruce Wayne"; + String val1 = "the Batman!"; + String expected = "Hello, I am the Batman!"; + SerialClob sc = new SerialClob(val.toCharArray()); + int written = sc.setString(13, val1); + assertEquals(val1.length(), written); + assertTrue(expected.equals(sc.getSubString(1, (int) sc.length()))); + } + + /* + * Check that setString() updates the appropriate characters in the + * SerialClob + */ + @Test(enabled = false) + public void test32() throws Exception { + int expectedWritten = 9; + String val = "Hi, I am Catwoman!!!!!!"; + String val1 = "Hahaha the Joker, who are you?!"; + String expected = "Hi, I am the Joker!"; + SerialClob sc = new SerialClob(val.toCharArray()); + int written = sc.setString(10, val1, 8, expectedWritten+1); + assertEquals(written, expectedWritten); + + } + + /* + * Check that setCharacterStream() returns a non-null Writer for an + * SerialClob created from a Clob + */ + @Test + public void test33() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + Writer w = sc.setCharacterStream(1); + assertTrue(w != null); + } + + /* + * Check that setAsciiStream() returns a non-null OutputStream for an SerialClob + * created from a Clob + */ + @Test + public void test34() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + OutputStream os = sc.setAsciiStream(1); + assertTrue(os != null); + } + + /* + * Check that truncate() truncates the length of the SerialClob to the + * specified size + */ + @Test + public void test35() throws Exception { + SerialClob sc = new SerialClob(new StubClob()); + sc.truncate(0); + assertTrue(sc.length() == 0); + sc = new SerialClob(chars); + sc.truncate(5); + assertTrue(sc.length() == 5); + } + + /* + * Check that getCharacterStream() returns a Reader and that the char[] that + * was specified to create the SerialClob can be returned via the Reader + */ + @Test + public void test36() throws Exception { + SerialClob sc = new SerialClob(chars); + Reader r = sc.getCharacterStream(); + for (char c : chars) { + char val = (char) r.read(); + assertTrue(c == val, val + " does not match " + c); + } + } + + /* + * Check that getCharacterStream() returns a Reader and that the char[] that + * was specified to create the SerialClob can be returned via the Reader + */ + @Test(enabled = false) + public void test37() throws Exception { + SerialClob sc = new SerialClob(chars); + String expected = "ello w"; + Reader r = sc.getCharacterStream(2, 6); + for (char c : expected.toCharArray()) { + char val = (char) r.read(); + assertTrue(c == val, val + " does not match " + c); + } + } + + /* + * Validate that a SerialClob that is serialized & deserialized is equal to + * itself + */ + @Test + public void test38() throws Exception { + SerialClob sc = new SerialClob(chars); + SerialClob sc2 = serializeDeserializeObject(sc); + assertTrue(sc.equals(sc2), "SerialClobs not equal"); + } +} diff --git a/jdk/test/javax/sql/testng/test/rowset/serial/SerialDataLinkTests.java b/jdk/test/javax/sql/testng/test/rowset/serial/SerialDataLinkTests.java new file mode 100644 index 00000000000..8e86d4a8f3d --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/serial/SerialDataLinkTests.java @@ -0,0 +1,110 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 test.rowset.serial; + +import java.net.URL; +import javax.sql.rowset.serial.SerialDatalink; +import javax.sql.rowset.serial.SerialException; +import static org.testng.Assert.*; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import util.BaseTest; + +public class SerialDataLinkTests extends BaseTest { + + private URL u; + private URL u1; + private SerialDatalink dl; + + @BeforeMethod + public void setUpMethod() throws Exception { + u = new URL("http://www.oracle.com/"); + u1 = new URL("http://www.usatoday.com/"); + dl = new SerialDatalink(u); + } + + /* + * Validate that a SerialException is thrown if the URL is null + */ + @Test(expectedExceptions = SerialException.class) + public void test() throws Exception { + SerialDatalink dl1 = new SerialDatalink(null); + } + + /* + * Validate that getDatalink() returns the same URL used to create the + * SerialDatalink object + */ + @Test + public void test01() throws Exception { + URL u2 = dl.getDatalink(); + assertTrue(u2.equals(u)); + assertTrue(u2.sameFile(u)); + } + + /* + * Validate that URL returned from getDatalink() differs from a URL that was + * not used to create the SerialDatalink + */ + @Test + public void test02() throws Exception { + URL u2 = dl.getDatalink(); + assertFalse(u2.equals(u1)); + assertFalse(u2.sameFile(u1)); + } + + /* + * Create a clone of a SerialDatalink and validate that it is equal to the + * SerialDatalink it was cloned from + */ + @Test + public void test03() throws Exception { + SerialDatalink dl2 = (SerialDatalink) dl.clone(); + assertTrue(dl.equals(dl2)); + SerialDatalink dl3 = new SerialDatalink(u1); + assertFalse(dl2.equals(dl3)); + } + + /* + * Validate that a SerialDatalink that is serialized & deserialized is + * equal to itself + */ + @Test + public void test04() throws Exception { + SerialDatalink dl2 = serializeDeserializeObject(dl); + SerialDatalink dl3 = new SerialDatalink(u); + assertTrue(dl.equals(dl2)); + assertTrue(dl3.equals(dl2)); + } + + /** + * Validate that a SerialDatalink that is serialized & deserialized is not equal + * to to a SerialDatalink created using a different URL + */ + @Test + public void test05() throws Exception { + SerialDatalink dl2 = serializeDeserializeObject(dl); + SerialDatalink d3 = new SerialDatalink(u1); + assertFalse(d3.equals(dl2)); + } +} diff --git a/jdk/test/javax/sql/testng/test/rowset/serial/SerialExceptionTests.java b/jdk/test/javax/sql/testng/test/rowset/serial/SerialExceptionTests.java new file mode 100644 index 00000000000..ff963ae7ba8 --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/serial/SerialExceptionTests.java @@ -0,0 +1,113 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 test.rowset.serial; + +import java.sql.SQLException; +import javax.sql.rowset.serial.SerialException; +import static org.testng.Assert.*; +import org.testng.annotations.Test; +import util.BaseTest; + +public class SerialExceptionTests extends BaseTest { + + /* + * Create SerialException with no-arg constructor + */ + @Test + public void test01() { + SerialException ex = new SerialException(); + assertTrue(ex.getMessage() == null + && ex.getSQLState() == null + && ex.getCause() == null + && ex.getErrorCode() == 0); + } + + /* + * Create SerialException with message + */ + @Test + public void test02() { + SerialException ex = new SerialException(reason); + assertTrue(ex.getMessage().equals(reason) + && ex.getSQLState() == null + && ex.getCause() == null + && ex.getErrorCode() == 0); + } + + /* + * Validate that the ordering of the returned Exceptions is correct using + * for-each loop + */ + @Test + public void test03() { + SerialException ex = new SerialException("Exception 1"); + ex.initCause(t1); + SerialException ex1 = new SerialException("Exception 2"); + SerialException ex2 = new SerialException("Exception 3"); + ex2.initCause(t2); + ex.setNextException(ex1); + ex.setNextException(ex2); + int num = 0; + for (Throwable e : ex) { + assertTrue(msgs[num++].equals(e.getMessage())); + } + } + + /* + * Validate that the ordering of the returned Exceptions is correct using + * traditional while loop + */ + @Test + public void test04() { + SQLException ex = new SerialException("Exception 1"); + ex.initCause(t1); + SerialException ex1 = new SerialException("Exception 2"); + SerialException ex2 = new SerialException("Exception 3"); + ex2.initCause(t2); + ex.setNextException(ex1); + ex.setNextException(ex2); + int num = 0; + while (ex != null) { + assertTrue(msgs[num++].equals(ex.getMessage())); + Throwable c = ex.getCause(); + while (c != null) { + assertTrue(msgs[num++].equals(c.getMessage())); + c = c.getCause(); + } + ex = ex.getNextException(); + } + } + + /* + * Serialize a SerialException and make sure you can read it back properly + */ + @Test + public void test05() throws Exception { + SerialException e = new SerialException(reason); + SerialException ex1 = createSerializedException(e); + assertTrue(ex1.getMessage().equals(reason) + && ex1.getSQLState() == null + && ex1.getCause() == null + && ex1.getErrorCode() == 0);; + } +} diff --git a/jdk/test/javax/sql/testng/test/rowset/serial/SerialJavaObjectTests.java b/jdk/test/javax/sql/testng/test/rowset/serial/SerialJavaObjectTests.java new file mode 100644 index 00000000000..cc2d184298d --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/serial/SerialJavaObjectTests.java @@ -0,0 +1,100 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 test.rowset.serial; + +import java.lang.reflect.Field; +import java.util.Arrays; +import javax.sql.rowset.RowSetMetaDataImpl; +import javax.sql.rowset.serial.SerialException; +import javax.sql.rowset.serial.SerialJavaObject; +import static org.testng.Assert.*; +import org.testng.annotations.Test; +import util.BaseTest; + +public class SerialJavaObjectTests extends BaseTest { + + /* + * Validate that an NPE is thrown when null is specified to create + * the SerialJavaObject + */ + @Test(expectedExceptions = NullPointerException.class) + public void test() throws Exception { + SerialJavaObject sjo = new SerialJavaObject(null); + } + + /* + * Validate that an SerialExcepion is thrown when the object specified + * contains public static fields + */ + @Test(expectedExceptions = SerialException.class, enabled = false) + public void test01() throws Exception { + SerialJavaObject sjo = new SerialJavaObject(new RowSetMetaDataImpl()); + } + + /* + * Validate that an getFields()s returns the same Field[] for the object + * used to create the SerialJavaObject + */ + @Test + public void test02() throws Exception { + SerialException e = new SerialException(); + SerialJavaObject sjo = new SerialJavaObject(e); + Field[] f = e.getClass().getFields(); + assertTrue(Arrays.equals(f, sjo.getFields())); + assertFalse(Arrays.equals("hello".getClass().getFields(), + sjo.getFields())); + } + + /* + * clone() a SerialJavaObject and check that it is equal to the + * object it was cloned from + */ + @Test + public void test03() throws Exception { + SerialJavaObject sjo = new SerialJavaObject("Hello"); + SerialJavaObject sjo2 = (SerialJavaObject) sjo.clone(); + assertTrue(sjo.equals(sjo2)); + } + + /** + * Validate that a SerialJavaObject that is serialized & deserialized is + * equal to itself + */ + @Test + public void test04() throws Exception { + SerialJavaObject sjo = new SerialJavaObject("Hello"); + SerialJavaObject sjo2 = serializeDeserializeObject(sjo); + assertTrue(sjo.equals(sjo2)); + } + + /* + * Validate that a getObject() returns an object used to create the + * SerialJavaObject + */ + @Test + public void test05() throws Exception { + String s = "Hello world"; + SerialJavaObject sjo = new SerialJavaObject(s); + assertTrue(s.equals(sjo.getObject())); + } +} diff --git a/jdk/test/javax/sql/testng/test/rowset/serial/SerialRefTests.java b/jdk/test/javax/sql/testng/test/rowset/serial/SerialRefTests.java new file mode 100644 index 00000000000..8f23de70aa6 --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/serial/SerialRefTests.java @@ -0,0 +1,131 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 test.rowset.serial; + +import java.sql.Ref; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; +import javax.sql.rowset.serial.SerialRef; +import static org.testng.Assert.*; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import util.BaseTest; +import util.StubRef; +import util.SuperHero; + +public class SerialRefTests extends BaseTest { + + private static Map> map = new HashMap<>(); + private Ref ref; + private final String sqlType = "SUPERHERO"; + private SuperHero hero; + + @BeforeMethod + public void setUpMethod() throws Exception { + map.put(sqlType, Class.forName("util.SuperHero")); + hero = new SuperHero(sqlType, "Bruce", "Wayne", 1939, "Batman"); + ref = new StubRef(sqlType, hero); + } + + /* + * Validate that a SQLException() is thrown if the Ref is null + */ + @Test(expectedExceptions = SQLException.class) + public void test01() throws Exception { + SerialRef sr = new SerialRef(null); + } + + /* + * Validate that a SQLException() is thrown if the typeName is null in the + * Ref used to create the SerialRef + */ + @Test(expectedExceptions = SQLException.class) + public void test02() throws Exception { + SerialRef sr = new SerialRef(new StubRef(null, hero)); + } + + /* + * Validate that getBaseTypeName() returns the same SQLType specified + * to create the Ref + */ + @Test + public void test03() throws Exception { + SerialRef sr = new SerialRef(ref); + assertEquals(sr.getBaseTypeName(), sqlType); + } + + /* + * Validate that getObject() returns the same object used to create the Ref + */ + @Test + public void test04() throws Exception { + SerialRef sr = new SerialRef(ref); + assertTrue(hero.equals(sr.getObject())); + } + + /* + * Validate that getObject() returns the same object used to create the Ref + */ + @Test(enabled = false) + public void test05() throws Exception { + SerialRef sr = new SerialRef(ref); + assertTrue(hero.equals(sr.getObject(map))); + } + + /* + * Validate that setObject() can be used to change the value of the object + * pointed to by the SerialRef + */ + @Test + public void test06() throws Exception { + SerialRef sr = new SerialRef(ref); + assertTrue(hero.equals(sr.getObject())); + SuperHero h = new SuperHero(sqlType, "Dick", "Grayson", 1940, "Robin"); + sr.setObject(h); + assertFalse(hero.equals(sr.getObject())); + } + + /* + * clone() a SerialRef and check that it is equal to the + * object it was cloned from + */ + @Test + public void test09() throws Exception { + SerialRef sr = new SerialRef(ref); + SerialRef sr1 = (SerialRef) sr.clone(); + assertTrue(sr.equals(sr1)); + } + + /** + * Validate that a SerialRef that is serialized & deserialized is equal to + * itself for the Object & baseTypeName + */ + @Test + public void test10() throws Exception { + SerialRef sr = new SerialRef(ref); + SerialRef sr1 = serializeDeserializeObject(sr); + assertTrue(sr1.getObject().equals(sr.getObject()) + && sr1.getBaseTypeName().equals(sr.getBaseTypeName())); + } +} diff --git a/jdk/test/javax/sql/testng/test/rowset/serial/SerialStructTests.java b/jdk/test/javax/sql/testng/test/rowset/serial/SerialStructTests.java new file mode 100644 index 00000000000..84a0ff2aaaf --- /dev/null +++ b/jdk/test/javax/sql/testng/test/rowset/serial/SerialStructTests.java @@ -0,0 +1,140 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 test.rowset.serial; + +import java.sql.Struct; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import javax.sql.rowset.serial.SerialStruct; +import static org.testng.Assert.*; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import util.BaseTest; +import util.StubStruct; +import util.SuperHero; + +public class SerialStructTests extends BaseTest { + + private static Map> map = new HashMap<>(); + private Object[] attributes; + private Struct struct; + private final String sqlType = "SUPERHERO"; + private SuperHero hero; + + @BeforeMethod + public void setUpMethod() throws Exception { + attributes = new Object[]{"Bruce", "Wayne", 1939, + "Batman"}; + map.put(sqlType, Class.forName("util.SuperHero")); + struct = new StubStruct(sqlType, attributes); + hero = new SuperHero(sqlType, "Bruce", "Wayne", 1939, "Batman"); + } + + /* + * Validate that getSQLTypeName() returns the same SQLType specified by + * the Struct used to create the object + */ + @Test + public void test01() throws Exception { + SerialStruct ss = new SerialStruct(struct, map); + assertEquals(ss.getSQLTypeName(), sqlType); + } + + /* + * Validate that getSQLTypeName() returns the same SQLType specified by + * the Struct used to create the object + */ + @Test + public void test02() throws Exception { + SerialStruct ss = new SerialStruct(hero, map); + assertEquals(ss.getSQLTypeName(), sqlType); + } + + /* + * Validate that getAttributes() returns the same attributes specified by + * the Struct used to create the object + */ + @Test + public void test03() throws Exception { + SerialStruct ss = new SerialStruct(struct, map); + assertTrue(Arrays.equals(attributes, + ss.getAttributes())); + } + + /* + * Validate that getAttributes() returns the same attributes specified by + * the Struct used to create the object + */ + @Test + public void test04() throws Exception { + SerialStruct ss = new SerialStruct(hero, map); + assertTrue(Arrays.equals(attributes, + ss.getAttributes())); + } + + /* + * Validate that getAttributes() returns the + same attributes specified by + * the Struct used to create the object + */ + @Test + public void test05() throws Exception { + SerialStruct ss = new SerialStruct(struct, map); + assertTrue(Arrays.equals(attributes, + ss.getAttributes(map))); + } + + /* + * Validate that getAttributes() returns the same attributes specified by + * the Struct used to create the object + */ + @Test + public void test06() throws Exception { + SerialStruct ss = new SerialStruct(hero, map); + assertTrue(Arrays.equals(attributes, + ss.getAttributes(map))); + } + + /* + * clone() a SerialStruct and check that it is equal to the + * object it was cloned from + */ + @Test + public void test07() throws Exception { + SerialStruct ss = new SerialStruct(struct, map); + SerialStruct ss1 = (SerialStruct) ss.clone(); + assertTrue(ss.equals(ss1)); + } + + /** + * Validate that a SerialStruct that is serialized & deserialized is equal + * to itself + */ + @Test + public void test08() throws Exception { + SerialStruct ss = new SerialStruct(struct, map); + SerialStruct ss1 = serializeDeserializeObject(ss);; + assertTrue(ss.equals(ss1)); + } +} diff --git a/jdk/test/javax/sql/testng/util/BaseTest.java b/jdk/test/javax/sql/testng/util/BaseTest.java new file mode 100644 index 00000000000..130dae8fb4e --- /dev/null +++ b/jdk/test/javax/sql/testng/util/BaseTest.java @@ -0,0 +1,91 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.sql.SQLException; +import org.testng.annotations.AfterClass; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; + +public class BaseTest { + + protected final String reason = "reason"; + protected final String state = "SQLState"; + protected final String cause = "java.lang.Throwable: cause"; + protected final Throwable t = new Throwable("cause"); + protected final Throwable t1 = new Throwable("cause 1"); + protected final Throwable t2 = new Throwable("cause 2"); + protected final int errorCode = 21; + protected final String[] msgs = {"Exception 1", "cause 1", "Exception 2", + "Exception 3", "cause 2"}; + + @BeforeClass + public static void setUpClass() throws Exception { + } + + @AfterClass + public static void tearDownClass() throws Exception { + } + + @BeforeMethod + public void setUpMethod() throws Exception { + } + + @AfterMethod + public void tearDownMethod() throws Exception { + } + + /* + * Take some form of SQLException, serialize and deserialize it + */ + @SuppressWarnings("unchecked") + protected T + createSerializedException(T ex) + throws IOException, ClassNotFoundException { + return (T) serializeDeserializeObject(ex); + } + + /* + * Utility method to serialize and deserialize an object + */ + @SuppressWarnings("unchecked") + protected T serializeDeserializeObject(T o) + throws IOException, ClassNotFoundException { + T o1; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { + oos.writeObject(o); + } + try (ObjectInputStream ois + = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) { + o1 = (T) ois.readObject(); + } + return o1; + } +} diff --git a/jdk/test/javax/sql/testng/util/StubArray.java b/jdk/test/javax/sql/testng/util/StubArray.java new file mode 100644 index 00000000000..1d2ef0e5b6f --- /dev/null +++ b/jdk/test/javax/sql/testng/util/StubArray.java @@ -0,0 +1,99 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 util; + +import java.sql.Array; +import java.sql.JDBCType; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.Map; + +public class StubArray implements Array { + + private String typeName; + Object[] elements; + + public StubArray(String name, Object[] values) { + typeName = name; + elements = Arrays.copyOf(values, values.length); + + } + + @Override + public String getBaseTypeName() throws SQLException { + return typeName; + } + + @Override + public int getBaseType() throws SQLException { + return JDBCType.valueOf(typeName).getVendorTypeNumber(); + } + + @Override + public Object getArray() throws SQLException { + return Arrays.copyOf(elements, elements.length); + } + + @Override + public Object getArray(Map> map) throws SQLException { + return getArray(); + } + + @Override + public Object getArray(long index, int count) throws SQLException { + return getArray(); + } + + @Override + public Object getArray(long index, int count, Map> map) throws SQLException { + return getArray(); + } + + @Override + public ResultSet getResultSet() throws SQLException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ResultSet getResultSet(Map> map) throws SQLException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ResultSet getResultSet(long index, int count) throws SQLException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ResultSet getResultSet(long index, int count, Map> map) throws SQLException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void free() throws SQLException { + elements = null; + typeName = null; + } + +} diff --git a/jdk/test/javax/sql/testng/util/StubBlob.java b/jdk/test/javax/sql/testng/util/StubBlob.java new file mode 100644 index 00000000000..727e8a926d5 --- /dev/null +++ b/jdk/test/javax/sql/testng/util/StubBlob.java @@ -0,0 +1,100 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 util; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.sql.Blob; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class StubBlob implements Blob { + + private byte[] bytes; + + public StubBlob() { + bytes = new byte[]{2, 4, 6, 8}; + } + + public long length() throws SQLException { + return bytes.length; + } + + public byte[] getBytes(long pos, int length) + throws SQLException { + return Arrays.copyOfRange(bytes, (int) pos - 1, length); + } + + public InputStream getBinaryStream() + throws SQLException { + return null; + } + + public long position(byte[] pattern, long start) + throws SQLException { + return 0; + } + + public long position(Blob pattern, long start) + throws SQLException { + return 0; + } + + public int setBytes(long pos, byte[] bytes) + throws SQLException { + return 0; + } + + public int setBytes(long pos, byte[] bytes, int offset, int len) + throws SQLException { + return 0; + } + + public OutputStream setBinaryStream(long pos) + throws SQLException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = null; + try { + oos = new ObjectOutputStream(baos); + } catch (IOException ex) { + Logger.getLogger(StubBlob.class.getName()).log(Level.SEVERE, null, ex); + } + return oos; + } + + public void truncate(long len) + throws SQLException { + } + + public void free() throws SQLException { + } + + public InputStream getBinaryStream(long pos, long length) throws SQLException { + return null; + } +} diff --git a/jdk/test/javax/sql/testng/util/StubClob.java b/jdk/test/javax/sql/testng/util/StubClob.java new file mode 100644 index 00000000000..cb1e0c0a62a --- /dev/null +++ b/jdk/test/javax/sql/testng/util/StubClob.java @@ -0,0 +1,113 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 util; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; +import java.sql.Clob; +import java.sql.SQLException; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class StubClob implements Clob { + + public String buf = "The test string 0123456789"; + + @Override + public String getSubString(long pos, int length) throws SQLException { + return buf; + } + + @Override + public long length() throws SQLException { + return buf.length(); + } + + @Override + public Reader getCharacterStream() throws SQLException { + return new StringReader(buf); + } + + @Override + public InputStream getAsciiStream() throws SQLException { + return new java.io.StringBufferInputStream(buf); + } + + @Override + public int setString(long pos, String str) throws SQLException { + return str.length(); + } + + @Override + public int setString(long pos, String str, int offset, int len) throws SQLException { + return len; + } + + @Override + public long position(String searchstr, long start) throws SQLException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public long position(Clob searchstr, long start) throws SQLException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public OutputStream setAsciiStream(long pos) throws SQLException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = null; + try { + oos = new ObjectOutputStream(baos); + } catch (IOException ex) { + Logger.getLogger(StubBlob.class.getName()).log(Level.SEVERE, null, ex); + } + return oos; + } + + @Override + public Writer setCharacterStream(long pos) throws SQLException { + return new StringWriter(); + } + + @Override + public void truncate(long len) throws SQLException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void free() throws SQLException { + } + + @Override + public Reader getCharacterStream(long pos, long length) throws SQLException { + throw new UnsupportedOperationException("Not supported yet."); + } +} diff --git a/jdk/test/javax/sql/testng/util/StubRef.java b/jdk/test/javax/sql/testng/util/StubRef.java new file mode 100644 index 00000000000..052bd92c740 --- /dev/null +++ b/jdk/test/javax/sql/testng/util/StubRef.java @@ -0,0 +1,60 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 util; + +import java.io.Serializable; +import java.sql.Ref; +import java.sql.SQLException; +import java.util.Map; + +public class StubRef implements Ref, Serializable { + + private final String baseTypeName; + private Object obj; + + public StubRef(String type, Object o) { + baseTypeName = type; + obj = o; + } + + @Override + public String getBaseTypeName() throws SQLException { + return baseTypeName; + } + + @Override + public Object getObject(Map> map) throws SQLException { + return obj; + } + + @Override + public Object getObject() throws SQLException { + return getObject(null); + } + + @Override + public void setObject(Object value) throws SQLException { + obj = value; + } + +} diff --git a/jdk/test/javax/sql/testng/util/StubStruct.java b/jdk/test/javax/sql/testng/util/StubStruct.java new file mode 100644 index 00000000000..1dee8028a2c --- /dev/null +++ b/jdk/test/javax/sql/testng/util/StubStruct.java @@ -0,0 +1,55 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 util; + +import java.sql.SQLException; +import java.sql.Struct; +import java.util.Arrays; +import java.util.Map; + +public class StubStruct implements Struct { + + private final String type; + private final Object[] attribs; + + public StubStruct(String type, Object[] o) { + this.type = type; + this.attribs = Arrays.copyOf(o, o.length); + } + + @Override + public String getSQLTypeName() throws SQLException { + return type; + } + + @Override + public Object[] getAttributes() throws SQLException { + return attribs; + } + + @Override + public Object[] getAttributes(Map> map) throws SQLException { + return attribs; + } + +} diff --git a/jdk/test/javax/sql/testng/util/SuperHero.java b/jdk/test/javax/sql/testng/util/SuperHero.java new file mode 100644 index 00000000000..8588f5006f1 --- /dev/null +++ b/jdk/test/javax/sql/testng/util/SuperHero.java @@ -0,0 +1,106 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 util; + +import java.io.Serializable; +import java.sql.SQLData; +import java.sql.SQLException; +import java.sql.SQLInput; +import java.sql.SQLOutput; + +public class SuperHero implements SQLData, Serializable { + + private String first; + private String last; + private final String type; + private Integer firstYear; + private String secretIdentity; + + public SuperHero(String sqlType, String fname, String lname, Integer year, + String identity) { + first = fname; + last = lname; + type = sqlType; + firstYear = year; + secretIdentity = identity; + } + + @Override + public String getSQLTypeName() throws SQLException { + return type; + } + + @Override + public void readSQL(SQLInput stream, String typeName) throws SQLException { + first = stream.readString(); + last = stream.readString(); + firstYear = stream.readInt(); + secretIdentity = stream.readString(); + } + + @Override + public void writeSQL(SQLOutput stream) throws SQLException { + stream.writeString(first); + stream.writeString(last); + stream.writeInt(firstYear); + stream.writeString(secretIdentity); + } + + @Override + public String toString() { + return "[ name =" + first + " " + last + " " + + firstYear + " " + secretIdentity + " ]"; + } + + public void setIdentity(String identity) { + secretIdentity = identity; + } + + public String getIdentity() { + return secretIdentity; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof SuperHero) { + SuperHero ss = (SuperHero) obj; + return first.equals(ss.first) && last.equals(ss.last) + && firstYear.equals(ss.firstYear) + && type.equals(ss.type) + && secretIdentity.equals(ss.secretIdentity); + } + return false; + } + + @Override + public int hashCode() { + return ((31 + first.hashCode()) * 31) * 31 + + ((31 + last.hashCode()) * 31) * 31 + + ((31 + firstYear.hashCode()) * 31) * 31 + + ((31 + type.hashCode()) * 31) * 31 + + secretIdentity.hashCode(); + } +} diff --git a/jdk/test/javax/swing/JMenuItem/8031573/bug8031573.java b/jdk/test/javax/swing/JMenuItem/8031573/bug8031573.java index 5cb1dc5047f..2d36db7a171 100644 --- a/jdk/test/javax/swing/JMenuItem/8031573/bug8031573.java +++ b/jdk/test/javax/swing/JMenuItem/8031573/bug8031573.java @@ -28,7 +28,7 @@ import javax.swing.JMenuBar; import javax.swing.SwingUtilities; /* @test - * @bug 8031573 + * @bug 8031573 8040279 * @summary [macosx] Checkmarks of JCheckBoxMenuItems aren't rendered * in high resolution on Retina * @author Alexander Scherbatiy diff --git a/jdk/test/javax/swing/JOptionPane/8024926/bug8024926.java b/jdk/test/javax/swing/JOptionPane/8024926/bug8024926.java index 42f976b03c0..185537f3b5b 100644 --- a/jdk/test/javax/swing/JOptionPane/8024926/bug8024926.java +++ b/jdk/test/javax/swing/JOptionPane/8024926/bug8024926.java @@ -31,7 +31,7 @@ import sun.awt.OSInfo; /** * @test - * @bug 8024926 + * @bug 8024926 8040279 * @summary [macosx] AquaIcon HiDPI support * @author Alexander Scherbatiy * @run applet/manual=yesno bug8024926.html diff --git a/jdk/test/javax/swing/JScrollBar/8039464/Test8039464.html b/jdk/test/javax/swing/JScrollBar/8039464/Test8039464.html new file mode 100644 index 00000000000..a473b819d1c --- /dev/null +++ b/jdk/test/javax/swing/JScrollBar/8039464/Test8039464.html @@ -0,0 +1,32 @@ + + + + +Choose the variable applet size and try to resize the applet. +The test passes the thumb is painted correctly. + + + + + diff --git a/jdk/test/javax/swing/JScrollBar/8039464/Test8039464.java b/jdk/test/javax/swing/JScrollBar/8039464/Test8039464.java new file mode 100644 index 00000000000..44bb33abd94 --- /dev/null +++ b/jdk/test/javax/swing/JScrollBar/8039464/Test8039464.java @@ -0,0 +1,92 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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.Container; +import java.awt.Dimension; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; + +import javax.swing.JApplet; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JScrollBar; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +/* + * @test + * @bug 8039464 + * @summary Tests enabling/disabling of titled border's caption + * @author Sergey Malenkov + * @run applet/manual=yesno Test8039464.html + */ + +public class Test8039464 extends JApplet { + static { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (Exception exception) { + throw new Error("unexpected", exception); + } + } + + @Override + public void init() { + init(this); + } + + private static void init(Container container) { + container.setLayout(new GridBagLayout()); + GridBagConstraints gbc = new GridBagConstraints(); + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.gridy = 1; + JLabel label = new JLabel(); + Dimension size = new Dimension(111, 0); + label.setPreferredSize(size); + label.setMinimumSize(size); + container.add(label, gbc); + gbc.gridx = 1; + gbc.weightx = 1; + container.add(new JScrollBar(JScrollBar.HORIZONTAL, 1, 111, 1, 1111), gbc); + gbc.gridx = 2; + gbc.gridy = 0; + gbc.weightx = 0; + gbc.weighty = 1; + container.add(new JScrollBar(JScrollBar.VERTICAL, 1, 111, 1, 1111), gbc); + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + JFrame frame = new JFrame("8039464"); + init(frame); + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + }); + } +} diff --git a/jdk/test/javax/swing/JTextField/8036819/bug8036819.java b/jdk/test/javax/swing/JTextField/8036819/bug8036819.java new file mode 100644 index 00000000000..558be4c9769 --- /dev/null +++ b/jdk/test/javax/swing/JTextField/8036819/bug8036819.java @@ -0,0 +1,132 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 + * @library ../../regtesthelpers + * @build Util + * @bug 8036819 + * @summary JAB: mnemonics not read for textboxes + * @author Vivi An + * @run main bug8036819 + */ + +import javax.swing.*; +import javax.swing.event.*; +import java.awt.event.*; +import java.awt.*; +import sun.awt.SunToolkit; +import javax.accessibility.*; + +public class bug8036819 { + + public static volatile Boolean passed = false; + + public static void main(String args[]) throws Throwable { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + createAndShowGUI(); + } + }); + + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + toolkit.realSync(); + + Robot robo = new Robot(); + robo.setAutoDelay(300); + + // Using mnemonic key to focus on the textfield + Util.hitMnemonics(robo, KeyEvent.VK_P); + toolkit.realSync(); + + if (!passed){ + throw new RuntimeException("Test failed."); + } + } + + private static void createAndShowGUI() { + JFrame mainFrame = new JFrame("bug 8036819"); + + JLabel usernameLabel = new JLabel("Username: "); + JTextField usernameField = new JTextField(20); + usernameLabel.setDisplayedMnemonic(KeyEvent.VK_U); + usernameLabel.setLabelFor(usernameField); + + JLabel pwdLabel = new JLabel("Password: "); + JTextField pwdField = new JTextField(20); + pwdLabel.setDisplayedMnemonic(KeyEvent.VK_P); + pwdLabel.setLabelFor(pwdField); + + pwdField.addKeyListener( + new KeyListener(){ + @Override + public void keyPressed(KeyEvent keyEvent) { + } + + @Override + public void keyTyped(KeyEvent keyEvent) { + } + + @Override + public void keyReleased(KeyEvent keyEvent){ + JComponent comp = (JComponent) pwdField; + AccessibleContext ac = comp.getAccessibleContext(); + AccessibleExtendedComponent aec = (AccessibleExtendedComponent)ac.getAccessibleComponent(); + AccessibleKeyBinding akb = aec.getAccessibleKeyBinding(); + if (akb != null){ + int count = akb.getAccessibleKeyBindingCount(); + if (count != 1){ + passed = false; + return; + } + + // there is 1 accessible key for the text field + System.out.println("Retrieved AccessibleKeyBinding for textfield " + count); + + // the key code is KeyEvent.VK_P + Object o = akb.getAccessibleKeyBinding(0); + if (o instanceof KeyStroke){ + javax.swing.KeyStroke key = (javax.swing.KeyStroke)o; + System.out.println("keystroke is " + key.getKeyCode()); + if (key.getKeyCode() == KeyEvent.VK_P) + passed = true; + } + } + } + } + ); + + mainFrame.getContentPane().add(usernameLabel); + mainFrame.getContentPane().add(usernameField); + mainFrame.getContentPane().add(pwdLabel); + mainFrame.getContentPane().add(pwdField); + + mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + mainFrame.setLayout(new FlowLayout(FlowLayout.LEFT)); + + mainFrame.setSize(200, 200); + mainFrame.setLocation(200, 200); + mainFrame.setVisible(true); + mainFrame.toFront(); + } + } diff --git a/jdk/test/javax/swing/border/Test4252164.java b/jdk/test/javax/swing/border/Test4252164.java index 007e732cf2a..923df715054 100644 --- a/jdk/test/javax/swing/border/Test4252164.java +++ b/jdk/test/javax/swing/border/Test4252164.java @@ -23,7 +23,7 @@ /* * @test - * @bug 4252164 + * @bug 4252164 8041917 * @summary Tests rounded LineBorder for components * @author Sergey Malenkov * @run applet/manual=yesno Test4252164.html diff --git a/jdk/test/javax/swing/plaf/nimbus/8041725/bug8041725.java b/jdk/test/javax/swing/plaf/nimbus/8041725/bug8041725.java new file mode 100644 index 00000000000..d668a3411de --- /dev/null +++ b/jdk/test/javax/swing/plaf/nimbus/8041725/bug8041725.java @@ -0,0 +1,82 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8041725 + @summary JList selection colors are not UIResource instances in Nimbus L&F + @author Anton Litvinov +*/ + +import java.awt.*; +import javax.swing.*; +import javax.swing.plaf.*; +import javax.swing.plaf.nimbus.*; + +public class bug8041725 { + public static void main(String[] args) throws Exception { + UIManager.setLookAndFeel(new NimbusLookAndFeel()); + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + JFrame frame = new JFrame("bug8041725"); + frame.setSize(200, 200); + JList list = new JList(new String[]{"Item1", "Item2", "Item3"}); + frame.getContentPane().add(list); + frame.pack(); + frame.setVisible(true); + + System.err.println("Test #1: No items are selected, list is enabled."); + testSelectionColors(list); + + System.err.println("Test #2: No items are selected, list is disabled."); + list.setEnabled(false); + testSelectionColors(list); + + System.err.println("Test #3: One item is selected, list is disabled."); + list.setSelectedIndex(0); + testSelectionColors(list); + + System.err.println("Test #4: One item is selected, list is enabled."); + list.setEnabled(true); + testSelectionColors(list); + + frame.dispose(); + } + }); + } + + private static void testSelectionColors(JList list) { + Color selBackColor = list.getSelectionBackground(); + if (!(selBackColor instanceof UIResource)) { + throw new RuntimeException(String.format( + "JList.getSelectionBackground() returned instance of '%s' instead of UIResource.", + selBackColor.getClass())); + } + Color selForeColor = list.getSelectionForeground(); + if (!(selForeColor instanceof UIResource)) { + throw new RuntimeException(String.format( + "JList.getSelectionForeground() returned instance of '%s' instead of UIResource.", + selForeColor.getClass())); + } + } +} diff --git a/jdk/test/javax/swing/text/StyledEditorKit/8016833/bug8016833.java b/jdk/test/javax/swing/text/StyledEditorKit/8016833/bug8016833.java index 601a31de688..1dec0972346 100644 --- a/jdk/test/javax/swing/text/StyledEditorKit/8016833/bug8016833.java +++ b/jdk/test/javax/swing/text/StyledEditorKit/8016833/bug8016833.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -190,9 +190,9 @@ public class bug8016833 { // not too wide assertTrue(out3.getWidth() * 0.8 < out2.getWidth()); // not too low - assertTrue(out3.getY() - (out1.getY() + out2.getHeight()) < 3); + assertTrue(out3.getY() - (out1.getY() + out2.getHeight() - 1) < 4); // not too high - assertTrue(out3.getY() - (out1.getY() + out2.getHeight()) > 0); + assertTrue(out3.getY() - (out1.getY() + out2.getHeight() - 1) > 0); } void testStrikthrough() { @@ -217,7 +217,7 @@ public class bug8016833 { // not too wide assertTrue(out3.getWidth() * 0.8 < out2.getWidth()); // not too low - assertTrue(out3.getY() - (out1.getY() + out2.getHeight()) < 0); + assertTrue(out3.getY() - (out1.getY() + out2.getHeight() - 1) < 0); // not too high assertTrue(out3.getY() - out1.getY() > 1); } diff --git a/jdk/test/javax/xml/ws/8043129/MailTest.java b/jdk/test/javax/xml/ws/8043129/MailTest.java new file mode 100644 index 00000000000..3d32a7d4dd8 --- /dev/null +++ b/jdk/test/javax/xml/ws/8043129/MailTest.java @@ -0,0 +1,148 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8043129 + * @summary JAF initialisation in SAAJ clashing with the one in javax.mail + * @author mkos + * @library javax.mail.jar + * @build MailTest + * @run main MailTest + */ + +import javax.activation.CommandMap; +import javax.activation.MailcapCommandMap; +import javax.mail.BodyPart; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.Multipart; +import javax.mail.Session; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; +import javax.xml.soap.AttachmentPart; +import javax.xml.soap.MessageFactory; +import javax.xml.soap.SOAPException; +import javax.xml.soap.SOAPMessage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Properties; + +public class MailTest { + + String host = null; + String user = ""; + String password = null; + String from = null; + String to = null; + + public static void main(String[] args) { + MailTest t = new MailTest(); + + t.user = "somebody@somewhere.com"; + t.from = "somebody@somewhere.com"; + t.to = "somebody@somewhere.com"; + + t.user = "somebody@somewhere.com"; + t.password = "somepassword"; + t.host = "somehost"; + + t.sendMail(); //this works + + t.addSoapAttachement(); + t.sendMail(); //after addAttachmentPart to soapmessage it do not work + + // workaroundJAFSetup(); + // t.sendMail(); //after workaround works again + } + + void addSoapAttachement() { + try { + MessageFactory messageFactory = MessageFactory.newInstance(); + SOAPMessage message = messageFactory.createMessage(); + AttachmentPart a = message.createAttachmentPart(); + a.setContentType("binary/octet-stream"); + message.addAttachmentPart(a); + } catch (SOAPException e) { + e.printStackTrace(); + } + } + + void sendMail() { + + try { + Properties props = new Properties(); + props.put("mail.smtp.host", host); + props.put("mail.smtp.auth", "true"); + + Session session = Session.getInstance(props); + session.setDebug(true); + + // Define message + MimeMessage message = new MimeMessage(session); + message.setFrom(new InternetAddress(from)); + message.addRecipients(Message.RecipientType.TO, to); + message.setSubject("this is a multipart test"); + + Multipart multipart = new MimeMultipart(); + + BodyPart messageBodyPart1 = new MimeBodyPart(); + messageBodyPart1.setText("please send also this Content\n ciao!"); + multipart.addBodyPart(messageBodyPart1); + + BodyPart messageBodyPart2 = new MimeBodyPart(); + messageBodyPart2.setContent("please send also this Content
    ciao!", "text/html; charset=UTF-8"); + multipart.addBodyPart(messageBodyPart2); + + message.setContent(multipart); + + /* + Transport tr = session.getTransport("smtp"); + tr.connect(host,user, password); + tr.sendMessage(message,InternetAddress.parse(to)); + tr.close(); + */ + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + message.writeTo(baos); + String output = baos.toString(); + System.out.println("output = " + output); + if (output.contains("also this Content")) { + System.out.println("Test PASSED."); + } else { + System.out.println("Test FAILED, missing content."); + throw new IllegalStateException("Test FAILED, missing content."); + } + } catch (MessagingException ignored) { + } catch (IOException ignored) { + } + } + + // this is how the error can be worked around ... + static void workaroundJAFSetup() { + MailcapCommandMap mailMap = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); + mailMap.addMailcap("multipart/mixed;;x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); + } +} diff --git a/jdk/test/javax/xml/ws/8043129/javax.mail.jar b/jdk/test/javax/xml/ws/8043129/javax.mail.jar new file mode 100644 index 00000000000..7da28712d88 Binary files /dev/null and b/jdk/test/javax/xml/ws/8043129/javax.mail.jar differ diff --git a/jdk/test/sun/awt/dnd/8024061/bug8024061.java b/jdk/test/sun/awt/dnd/8024061/bug8024061.java new file mode 100644 index 00000000000..07165c09a61 --- /dev/null +++ b/jdk/test/sun/awt/dnd/8024061/bug8024061.java @@ -0,0 +1,357 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8024061 + * @summary Checks that no exception is thrown if dragGestureRecognized + * takes a while to complete. + */ +import sun.awt.OSInfo; +import sun.awt.OSInfo.OSType; +import sun.awt.SunToolkit; + +import java.awt.*; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.dnd.DnDConstants; +import java.awt.dnd.DragGestureEvent; +import java.awt.dnd.DragGestureListener; +import java.awt.dnd.DragSource; +import java.awt.dnd.DragSourceDragEvent; +import java.awt.dnd.DragSourceDropEvent; +import java.awt.dnd.DragSourceEvent; +import java.awt.dnd.DragSourceListener; +import java.awt.dnd.DropTarget; +import java.awt.dnd.DropTargetDragEvent; +import java.awt.dnd.DropTargetDropEvent; +import java.awt.dnd.DropTargetEvent; +import java.awt.dnd.DropTargetListener; +import java.awt.event.InputEvent; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import javax.swing.*; + +/** + * If dragGestureRecognized() takes a while to complete and if user performs a drag quickly, + * an exception is thrown from DropTargetListener.dragEnter when it calls + * DropTargetDragEvent.getTransferable(). + *

    + * This class introduces a delay in dragGestureRecognized() to cause the exception. + */ +public class bug8024061 { + private static final DataFlavor DropObjectFlavor; + private static final int DELAY = 1000; + + private final DnDPanel panel1 = new DnDPanel(Color.yellow); + private final DnDPanel panel2 = new DnDPanel(Color.pink); + private final JFrame frame; + + private static final CountDownLatch lock = new CountDownLatch(1); + private static volatile Exception dragEnterException = null; + + static { + DataFlavor flavor = null; + try { + flavor = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + DropObjectFlavor = flavor; + } + + bug8024061() { + frame = new JFrame("DnDWithRobot"); + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + + Dimension d = new Dimension(100, 100); + + panel1.setPreferredSize(d); + panel2.setPreferredSize(d); + + Container content = frame.getContentPane(); + content.setLayout(new GridLayout(1, 2, 5, 5)); + content.add(panel1); + content.add(panel2); + + frame.pack(); + + DropObject drop = new DropObject(); + drop.place(panel1, new Point(10, 10)); + frame.setVisible(true); + } + + public static void main(String[] args) throws AWTException, InvocationTargetException, InterruptedException { + OSType type = OSInfo.getOSType(); + if (type != OSType.LINUX && type != OSType.SOLARIS) { + System.out.println("This test is for Linux and Solaris only... " + + "skipping!"); + return; + } + + final bug8024061[] dnd = {null}; + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + dnd[0] = new bug8024061(); + } + }); + final Robot robot = new Robot(); + robot.setAutoDelay(10); + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + toolkit.realSync(); + + JFrame frame = dnd[0].frame; + Point point = frame.getLocationOnScreen(); + Point here = new Point(point.x + 35, point.y + 45); + Point there = new Point(point.x + 120, point.y + 45); + here.x += 25; + robot.mouseMove(here.x, here.y); + robot.mousePress(InputEvent.BUTTON1_MASK); + while (here.x < there.x) { + here.x += 20; + robot.mouseMove(here.x, here.y); + System.out.println("x = " + here.x); + } + robot.mouseRelease(InputEvent.BUTTON1_MASK); + toolkit.realSync(); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + System.out.println("finished"); + + try { + if (lock.await(5, TimeUnit.SECONDS)) { + if (dragEnterException == null) { + System.out.println("Test passed."); + } else { + System.out.println("Test failed."); + dragEnterException.printStackTrace(); + throw new RuntimeException(dragEnterException); + } + } else { + System.out.println("Test failed. Timeout reached"); + throw new RuntimeException("Timed out waiting for dragEnter()"); + } + } finally { + frame.dispose(); + } + } + + class DropObject implements Transferable { + DnDPanel panel; + Color color = Color.CYAN; + int width = 50; + int height = 50; + int x; + int y; + + void draw(Graphics2D g) { + Color savedColor = g.getColor(); + g.setColor(color); + g.fillRect(x, y, width, height); + g.setColor(Color.lightGray); + g.drawRect(x, y, width, height); + g.setColor(savedColor); + } + + boolean contains(int x, int y) { + return (x > this.x && x < this.x + width) + && (y > this.y && y < this.y + height); + } + + @Override + public DataFlavor[] getTransferDataFlavors() { + return new DataFlavor[]{DropObjectFlavor}; + } + + void place(DnDPanel panel, Point location) { + if (panel != this.panel) { + x = location.x; + y = location.y; + if (this.panel != null) { + this.panel.setDropObject(null); + this.panel.repaint(); + } + this.panel = panel; + this.panel.setDropObject(this); + this.panel.repaint(); + } + } + + @Override + public boolean isDataFlavorSupported(DataFlavor flavor) { + return DropObjectFlavor.equals(flavor); + } + + @Override + public Object getTransferData(DataFlavor flavor) + throws UnsupportedFlavorException, IOException { + if (isDataFlavorSupported(flavor)) { + return this; + } else { + throw new UnsupportedFlavorException(flavor); + } + } + } + + class DnDPanel extends JPanel { + DropObject dropObject; + final DragSource dragSource; + final DropTarget dropTarget; + final Color color; + final DragGestureListener dgListener; + final DragSourceListener dsListener; + final DropTargetListener dtListener; + + DnDPanel(Color color) { + this.color = color; + this.dragSource = DragSource.getDefaultDragSource(); + dgListener = new DragGestureListener() { + @Override + public void dragGestureRecognized(DragGestureEvent dge) { + Point location = dge.getDragOrigin(); + if (dropObject != null && dropObject.contains(location.x, location.y)) { + dragSource.startDrag(dge, DragSource.DefaultCopyNoDrop, dropObject, dsListener); + try { + Thread.sleep(DELAY); + } catch (InterruptedException e) { + } + } + } + }; + + dsListener = new DragSourceListener() { + @Override + public void dragEnter(DragSourceDragEvent dsde) { + } + + @Override + public void dragOver(DragSourceDragEvent dsde) { + } + + @Override + public void dropActionChanged(DragSourceDragEvent dsde) { + } + + @Override + public void dragExit(DragSourceEvent dse) { + } + + @Override + public void dragDropEnd(DragSourceDropEvent dsde) { + } + }; + + dtListener = new DropTargetListener() { + @Override + public void dragEnter(DropTargetDragEvent dtde) { + if (dropObject != null) { + dtde.rejectDrag(); + return; + } + dtde.acceptDrag(DnDConstants.ACTION_MOVE); + try { + Transferable t = dtde.getTransferable(); + Object data = t.getTransferData(DropObjectFlavor); + if (data != null) { + throw new Exception("getTransferData returned non-null"); + } + } catch (Exception e) { + dragEnterException = e; + e.printStackTrace(); + } finally { + lock.countDown(); + } + } + + @Override + public void dragOver(DropTargetDragEvent dtde) { + if (dropObject != null) { + dtde.rejectDrag(); + return; + } + dtde.acceptDrag(DnDConstants.ACTION_MOVE); + } + + @Override + public void dropActionChanged(DropTargetDragEvent dtde) { + } + + @Override + public void dragExit(DropTargetEvent dte) { + } + + @Override + public void drop(DropTargetDropEvent dtde) { + if (dropObject != null) { + dtde.rejectDrop(); + return; + } + try { + dtde.acceptDrop(DnDConstants.ACTION_MOVE); + Transferable t = dtde.getTransferable(); + DropObject dropObject = (DropObject) t.getTransferData(DropObjectFlavor); + Point location = dtde.getLocation(); + dropObject.place(DnDPanel.this, location); + dtde.dropComplete(true); + } catch (Exception e) { + e.printStackTrace(); + } + + } + }; + + dragSource.createDefaultDragGestureRecognizer(this, + DnDConstants.ACTION_MOVE, dgListener); + + dropTarget = new DropTarget(this, DnDConstants.ACTION_MOVE, dtListener, true); + + } + + public void paintComponent(Graphics g) { + super.paintComponent(g); + Color savedColor = g.getColor(); + g.setColor(color); + g.fillRect(0, 0, getWidth(), getHeight()); + g.setColor(savedColor); + if (dropObject != null) { + dropObject.draw((Graphics2D) g); + } + } + + void setDropObject(DropObject dropObject) { + this.dropObject = dropObject; + } + + DropObject findDropObject(int x, int y) { + if (dropObject != null && dropObject.contains(x, y)) { + return dropObject; + } + return null; + } + } +} diff --git a/jdk/test/sun/management/jdp/JdpDefaultsTest.java b/jdk/test/sun/management/jdp/JdpDefaultsTest.java index 9067be7cc05..35a145fd330 100644 --- a/jdk/test/sun/management/jdp/JdpDefaultsTest.java +++ b/jdk/test/sun/management/jdp/JdpDefaultsTest.java @@ -28,7 +28,7 @@ * @test JdpDefaultsTest * @summary Assert that we can read JDP packets from a multicast socket connection, on default IP and port. * @library /lib/testlibrary - * @build ClientConnection JdpTestUtil JdpTestCase JdpOnTestCase DynamicLauncher + * @build jdk.testlibrary.* ClientConnection JdpTestUtil JdpTestCase JdpOnTestCase DynamicLauncher * @run main JdpDefaultsTest */ diff --git a/jdk/test/sun/management/jdp/JdpOffTest.java b/jdk/test/sun/management/jdp/JdpOffTest.java index 7810400abbe..15b082e01ef 100644 --- a/jdk/test/sun/management/jdp/JdpOffTest.java +++ b/jdk/test/sun/management/jdp/JdpOffTest.java @@ -29,7 +29,7 @@ * @test JdpOffTest.java * @summary Assert that no JDP packets are sent to the default address and port. * @library /lib/testlibrary - * @build ClientConnection JdpTestUtil JdpTestCase JdpOffTestCase DynamicLauncher + * @build jdk.testlibrary.* ClientConnection JdpTestUtil JdpTestCase JdpOffTestCase DynamicLauncher * @run main JdpOffTest */ diff --git a/jdk/test/sun/management/jdp/JdpSpecificAddressTest.java b/jdk/test/sun/management/jdp/JdpSpecificAddressTest.java index 8a791766d85..0b9d8e02328 100644 --- a/jdk/test/sun/management/jdp/JdpSpecificAddressTest.java +++ b/jdk/test/sun/management/jdp/JdpSpecificAddressTest.java @@ -28,7 +28,7 @@ * @test JdpSpecificAddressTest * @summary Assert that we can read JDP packets from a multicast socket connection, on specific IP and port. * @library /lib/testlibrary - * @build ClientConnection JdpTestUtil JdpTestCase JdpOnTestCase DynamicLauncher + * @build jdk.testlibrary.* ClientConnection JdpTestUtil JdpTestCase JdpOnTestCase DynamicLauncher * @run main JdpSpecificAddressTest */ diff --git a/jdk/test/sun/management/jmxremote/bootstrap/LocalManagementTest.java b/jdk/test/sun/management/jmxremote/bootstrap/LocalManagementTest.java index d02d43e68de..1828d867bfc 100644 --- a/jdk/test/sun/management/jmxremote/bootstrap/LocalManagementTest.java +++ b/jdk/test/sun/management/jmxremote/bootstrap/LocalManagementTest.java @@ -42,9 +42,7 @@ import java.util.concurrent.atomic.AtomicReference; * without connection or username/password details. * TestManager will attempt a connection to the address obtained from * both agent properties and jvmstat buffer. - * @build jdk.testlibrary.ProcessTools - * @build jdk.testlibrary.Utils - * @build TestManager TestApplication + * @build jdk.testlibrary.* TestManager TestApplication * @run main/othervm/timeout=300 -XX:+UsePerfData LocalManagementTest */ diff --git a/jdk/test/sun/management/jmxremote/bootstrap/PasswordFilePermissionTest.java b/jdk/test/sun/management/jmxremote/bootstrap/PasswordFilePermissionTest.java index cce5bc2c8a0..e53cbc9eaaf 100644 --- a/jdk/test/sun/management/jmxremote/bootstrap/PasswordFilePermissionTest.java +++ b/jdk/test/sun/management/jmxremote/bootstrap/PasswordFilePermissionTest.java @@ -28,11 +28,7 @@ import java.io.IOException; * @library /lib/testlibrary * @bug 6557093 * @summary Check SSL config file permission for out-of-the-box management - * @build jdk.testlibrary.Utils - * @build jdk.testlibrary.ProcessTools - * @build jdk.testlibrary.OutputAnalyzer - * @build AbstractFilePermissionTest - * @build Dummy + * @build jdk.testlibrary.* AbstractFilePermissionTest Dummy * @run main/timeout=300 PasswordFilePermissionTest * * @author Taras Ledkov diff --git a/jdk/test/sun/management/jmxremote/bootstrap/RmiBootstrapTest.sh b/jdk/test/sun/management/jmxremote/bootstrap/RmiBootstrapTest.sh index 50c4262e48b..10835558713 100644 --- a/jdk/test/sun/management/jmxremote/bootstrap/RmiBootstrapTest.sh +++ b/jdk/test/sun/management/jmxremote/bootstrap/RmiBootstrapTest.sh @@ -27,11 +27,7 @@ # @summary Test RMI Bootstrap # # @library /lib/testlibrary -# @library /lib/testlibrary -# @build jdk.testlibrary.Utils -# @build TestLogger -# @build Utils -# @build RmiBootstrapTest +# @build jdk.testlibrary.* TestLogger Utils RmiBootstrapTest # @run shell/timeout=300 RmiBootstrapTest.sh # Define the Java class test name diff --git a/jdk/test/sun/management/jmxremote/bootstrap/RmiRegistrySslTest.java b/jdk/test/sun/management/jmxremote/bootstrap/RmiRegistrySslTest.java index 3648ca6ad11..eaeaa392936 100644 --- a/jdk/test/sun/management/jmxremote/bootstrap/RmiRegistrySslTest.java +++ b/jdk/test/sun/management/jmxremote/bootstrap/RmiRegistrySslTest.java @@ -42,10 +42,7 @@ import java.util.regex.Pattern; * @library /lib/testlibrary * @bug 6228231 * @summary Test that RMI registry uses SSL. - * @build jdk.testlibrary.Utils - * @build jdk.testlibrary.ProcessTools - * @build jdk.testlibrary.OutputAnalyzer - * @build RmiRegistrySslTestApp + * @build jdk.testlibrary.* RmiRegistrySslTestApp * @run main/timeout=300 RmiRegistrySslTest * @author Luis-Miguel Alventosa, Taras Ledkov */ diff --git a/jdk/test/sun/management/jmxremote/bootstrap/RmiSslBootstrapTest.sh b/jdk/test/sun/management/jmxremote/bootstrap/RmiSslBootstrapTest.sh index 7a786a357ad..a74fdd63622 100644 --- a/jdk/test/sun/management/jmxremote/bootstrap/RmiSslBootstrapTest.sh +++ b/jdk/test/sun/management/jmxremote/bootstrap/RmiSslBootstrapTest.sh @@ -27,10 +27,7 @@ # @summary Test RMI Bootstrap with SSL # # @library /lib/testlibrary -# @build jdk.testlibrary.Utils -# @build TestLogger -# @build Utils -# @build RmiBootstrapTest +# @build jdk.testlibrary.* TestLogger Utils RmiBootstrapTest # @run shell/timeout=300 RmiSslBootstrapTest.sh # Define the Java class test name diff --git a/jdk/test/sun/management/jmxremote/bootstrap/SSLConfigFilePermissionTest.java b/jdk/test/sun/management/jmxremote/bootstrap/SSLConfigFilePermissionTest.java index 149e9c4ef38..cbe158c0858 100644 --- a/jdk/test/sun/management/jmxremote/bootstrap/SSLConfigFilePermissionTest.java +++ b/jdk/test/sun/management/jmxremote/bootstrap/SSLConfigFilePermissionTest.java @@ -27,12 +27,7 @@ import java.io.IOException; * @test * @library /lib/testlibrary * @bug 6557093 - * @bug 6557093 - * @build jdk.testlibrary.Utils - * @build jdk.testlibrary.ProcessTools - * @build jdk.testlibrary.OutputAnalyzer - * @build Dummy - * @build AbstractFilePermissionTest + * @build jdk.testlibrary.* Dummy AbstractFilePermissionTest * @summary Check SSL config file permission for out-of-the-box management * @run main/timeout=300 SSLConfigFilePermissionTest * diff --git a/jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.java b/jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.java index c6d539e5465..a1518b9cbe3 100644 --- a/jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.java +++ b/jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.java @@ -54,10 +54,7 @@ import jdk.testlibrary.JDKToolLauncher; * @test * @bug 7110104 * @library /lib/testlibrary - * @build jdk.testlibrary.ProcessTools - * @build jdk.testlibrary.JDKToolLauncher - * @build jdk.testlibrary.Utils - * @build JMXStartStopTest JMXStartStopDoSomething + * @build jdk.testlibrary.* JMXStartStopTest JMXStartStopDoSomething * @run main/othervm JMXStartStopTest * @summary Makes sure that enabling/disabling the management agent through * JCMD achieves the desired results diff --git a/jdk/test/sun/nio/ch/ServerSocketAdaptorTest.java b/jdk/test/sun/nio/ch/ServerSocketAdaptorTest.java new file mode 100644 index 00000000000..062fc784520 --- /dev/null +++ b/jdk/test/sun/nio/ch/ServerSocketAdaptorTest.java @@ -0,0 +1,64 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8024832 + */ + +import java.io.IOException; +import java.net.ServerSocket; +import java.net.SocketException; +import java.nio.channels.ServerSocketChannel; + +public class ServerSocketAdaptorTest { + + public static void main(String[] args) throws IOException { + + String message = null; + + try (ServerSocket s = new ServerSocket()) { + s.accept(); + throw new AssertionError(); + } catch (IOException e) { + message = e.getMessage(); + } + + try (ServerSocket ss = ServerSocketChannel.open().socket()) { + + assert !ss.isBound() : "the assumption !ss.isBound() doesn't hold"; + + try { + ss.accept(); + throw new AssertionError(); + } catch (Exception e) { + if (e instanceof SocketException && message.equals(e.getMessage())) { + return; + } else { + throw new AssertionError( + "Expected to throw SocketException with a particular message", e); + } + } + } + } +} diff --git a/jdk/test/sun/security/krb5/auto/KDC.java b/jdk/test/sun/security/krb5/auto/KDC.java index 356f84e9856..686e238579e 100644 --- a/jdk/test/sun/security/krb5/auto/KDC.java +++ b/jdk/test/sun/security/krb5/auto/KDC.java @@ -141,6 +141,8 @@ public class KDC { private BlockingQueue q = new ArrayBlockingQueue<>(100); // Options private Map options = new HashMap<>(); + // Realm-specific krb5.conf settings + private List conf = new ArrayList<>(); private Thread thread1, thread2, thread3; DatagramSocket u1 = null; @@ -243,7 +245,7 @@ public class KDC { /** * Sets an option * @param key the option name - * @param obj the value + * @param value the value */ public void setOption(Option key, Object value) { if (value == null) { @@ -372,6 +374,13 @@ public class KDC { return kdc; } + /** + * Add realm-specific krb5.conf setting + */ + public void addConf(String s) { + conf.add(s); + } + /** * Writes a krb5.conf for one or more KDC that includes KDC locations for * each realm and the default realm name. You can also add extra strings @@ -397,6 +406,7 @@ public class KDC { * [realms] * REALM.NAME = { * kdc = host:port_number + * # realm-specific settings * } *

    * @@ -444,10 +454,10 @@ public class KDC { } } sb.append("\n[realms]\n"); - sb.append(realmLineForKDC(kdc)); + sb.append(kdc.realmLine()); for (Object o: more) { if (o instanceof KDC) { - sb.append(realmLineForKDC((KDC)o)); + sb.append(((KDC)o).realmLine()); } } FileOutputStream fos = new FileOutputStream(f); @@ -1133,14 +1143,16 @@ public class KDC { /** * Generates a line for a KDC to put inside [realms] of krb5.conf - * @param kdc the KDC - * @return REALM.NAME = { kdc = host:port } + * @return REALM.NAME = { kdc = host:port etc } */ - private static String realmLineForKDC(KDC kdc) { - return String.format("%s = {\n kdc = %s:%d\n}\n", - kdc.realm, - kdc.kdc, - kdc.port); + private String realmLine() { + StringBuilder sb = new StringBuilder(); + sb.append(realm).append(" = {\n kdc = ") + .append(kdc).append(':').append(port).append('\n'); + for (String s: conf) { + sb.append(" ").append(s).append('\n'); + } + return sb.append("}\n").toString(); } /** diff --git a/jdk/test/sun/security/krb5/auto/ReplayCacheTestProc.java b/jdk/test/sun/security/krb5/auto/ReplayCacheTestProc.java index 1e69486fba7..5275b69b594 100644 --- a/jdk/test/sun/security/krb5/auto/ReplayCacheTestProc.java +++ b/jdk/test/sun/security/krb5/auto/ReplayCacheTestProc.java @@ -40,7 +40,6 @@ import java.nio.file.StandardOpenOption; import java.security.MessageDigest; import java.util.*; -import com.sun.security.auth.module.UnixSystem; import sun.security.jgss.GSSUtil; import sun.security.krb5.internal.APReq; import sun.security.krb5.internal.rcache.AuthTime; @@ -79,13 +78,7 @@ public class ReplayCacheTestProc { mode = -1; } - try { - UnixSystem us = new com.sun.security.auth.module.UnixSystem(); - uid = us.getUid(); - } catch (Throwable e) { - // Cannot be only Exception, might be UnsatisfiedLinkError - uid = -1; - } + uid = sun.misc.VM.geteuid(); KDC kdc = KDC.create(OneKDC.REALM, HOST, 0, true); for (int i=0; i>> KDCCommunication")) { - if (!line.contains(args[0])) { + if (!line.contains(args[0]) || !line.contains("timeout=10000")) { throw new Exception("No " + args[0] + " in: " + line); } } diff --git a/jdk/test/sun/security/pkcs11/PKCS11Test.java b/jdk/test/sun/security/pkcs11/PKCS11Test.java index 3699f880456..f1b179b00f5 100644 --- a/jdk/test/sun/security/pkcs11/PKCS11Test.java +++ b/jdk/test/sun/security/pkcs11/PKCS11Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -457,7 +457,7 @@ public abstract class PKCS11Test { osMap.put("SunOS-x86-32", new String[]{"/usr/lib/mps/"}); osMap.put("SunOS-amd64-64", new String[]{"/usr/lib/mps/64/"}); osMap.put("Linux-i386-32", new String[]{ - "/usr/lib/i386-linux-gnu/", "/usr/lib/"}); + "/usr/lib/i386-linux-gnu/", "/usr/lib32/", "/usr/lib/"}); osMap.put("Linux-amd64-64", new String[]{ "/usr/lib/x86_64-linux-gnu/", "/usr/lib/x86_64-linux-gnu/nss/", "/usr/lib64/"}); diff --git a/jdk/test/sun/security/tools/jarsigner/certpolicy.sh b/jdk/test/sun/security/tools/jarsigner/certpolicy.sh new file mode 100644 index 00000000000..20cf92b1618 --- /dev/null +++ b/jdk/test/sun/security/tools/jarsigner/certpolicy.sh @@ -0,0 +1,80 @@ +# +# 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. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please 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 8036709 +# @summary Java 7 jarsigner displays warning about cert policy tree +# +# @run shell certpolicy.sh +# + +if [ "${TESTJAVA}" = "" ] ; then + JAVAC_CMD=`which javac` + TESTJAVA=`dirname $JAVAC_CMD`/.. +fi + +KT="$TESTJAVA/bin/keytool $TESTTOOLVMOPTS \ + -keypass changeit -storepass changeit -keystore ks -keyalg rsa" +JS="$TESTJAVA/bin/jarsigner $TESTTOOLVMOPTS -storepass changeit -keystore ks" +JAR="$TESTJAVA/bin/jar $TESTTOOLVMOPTS" + +rm ks 2> /dev/null +$KT -genkeypair -alias ca -dname CN=CA -ext bc +$KT -genkeypair -alias int -dname CN=Int +$KT -genkeypair -alias ee -dname CN=EE + +# CertificatePolicies [[PolicyId: [1.2.3]], [PolicyId: [1.2.4]]] +# PolicyConstraints: [Require: 0; Inhibit: unspecified] +$KT -certreq -alias int | \ + $KT -gencert -rfc -alias ca \ + -ext 2.5.29.32="30 0C 30 04 06 02 2A 03 30 04 06 02 2A 04" \ + -ext "2.5.29.36=30 03 80 01 00" -ext bc | \ + $KT -import -alias int + +# CertificatePolicies [[PolicyId: [1.2.3]]] +$KT -certreq -alias ee | \ + $KT -gencert -rfc -alias int \ + -ext 2.5.29.32="30 06 30 04 06 02 2A 03" | \ + $KT -import -alias ee + +$KT -export -alias ee -rfc > cc +$KT -export -alias int -rfc >> cc +$KT -export -alias ca -rfc >> cc + +$KT -delete -alias int + +ERR='' +$JAR cvf a.jar cc + +# Make sure the certchain in the signed jar contains all 3 certs +$JS -strict -certchain cc a.jar ee -debug || ERR="sign" +$JS -strict -verify a.jar -debug || ERR="$ERR verify" + +if [ "$ERR" = "" ]; then + echo "Success" + exit 0 +else + echo "Failed: $ERR" + exit 1 +fi + diff --git a/jdk/test/sun/security/tools/keytool/autotest.sh b/jdk/test/sun/security/tools/keytool/autotest.sh index 90e0a66a268..8154af5939b 100644 --- a/jdk/test/sun/security/tools/keytool/autotest.sh +++ b/jdk/test/sun/security/tools/keytool/autotest.sh @@ -1,5 +1,5 @@ # -# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2006, 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 @@ -72,6 +72,8 @@ case "$OS" in Linux ) if [ $B32 = true ]; then LIBNAME=`find_one \ + "/usr/lib32/libsoftokn3.so" \ + "/usr/lib32/nss/libsoftokn3.so" \ "/usr/lib/libsoftokn3.so" \ "/usr/lib/i386-linux-gnu/nss/libsoftokn3.so" \ "/usr/lib/nss/libsoftokn3.so"` diff --git a/jdk/test/sun/text/resources/Format/Bug8037343.java b/jdk/test/sun/text/resources/Format/Bug8037343.java new file mode 100644 index 00000000000..80735f74236 --- /dev/null +++ b/jdk/test/sun/text/resources/Format/Bug8037343.java @@ -0,0 +1,71 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8037343 + * @summary updating dateformat for es_DO + */ + +import java.text.DateFormat; +import java.util.Calendar; +import java.util.Locale; + +public class Bug8037343 +{ + + public static void main(String[] arg) + { + final Locale esDO = new Locale("es", "DO"); + final String expectedShort = "31/03/12"; + final String expectedMedium = "31/03/2012"; + + int errors = 0; + DateFormat format; + String result; + + Calendar cal = Calendar.getInstance(esDO); + cal.set(Calendar.DAY_OF_MONTH, 31); + cal.set(Calendar.MONTH, Calendar.MARCH); + cal.set(Calendar.YEAR, 2012); + + format = DateFormat.getDateInstance(DateFormat.SHORT, esDO); + result = format.format(cal.getTime()); + if (!expectedShort.equals(result)) { + System.out.println(String.format("Short Date format for es_DO is not as expected. Expected: [%s] Actual: [%s]", expectedShort, result)); + errors++; + } + + format = DateFormat.getDateInstance(DateFormat.MEDIUM, esDO); + result = format.format(cal.getTime()); + if (!expectedMedium.equals(result)) { + System.out.println(String.format("Medium Date format for es_DO is not as expected. Expected: [%s] Actual: [%s]", expectedMedium, result)); + errors++; + } + + if (errors > 0) { + throw new RuntimeException(); + } + } + +} diff --git a/jdk/test/sun/text/resources/LocaleData b/jdk/test/sun/text/resources/LocaleData index fbea26741fd..6be5a4c1111 100644 --- a/jdk/test/sun/text/resources/LocaleData +++ b/jdk/test/sun/text/resources/LocaleData @@ -483,8 +483,8 @@ FormatData/es_DO/TimePatterns/2=hh:mm:ss a FormatData/es_DO/TimePatterns/3=hh:mm a FormatData/es_DO/DatePatterns/0=EEEE d' de 'MMMM' de 'yyyy FormatData/es_DO/DatePatterns/1=d' de 'MMMM' de 'yyyy -FormatData/es_DO/DatePatterns/2=MM/dd/yyyy -FormatData/es_DO/DatePatterns/3=MM/dd/yy +# FormatData/es_DO/DatePatterns/2=MM/dd/yyyy # Changed: see bug 8037343 +# FormatData/es_DO/DatePatterns/3=MM/dd/yy # Changed: see bug 8037343 FormatData/es_DO/DateTimePatterns/0={1} {0} FormatData/es_DO/NumberElements/0=. FormatData/es_DO/NumberElements/1=, @@ -7692,3 +7692,7 @@ FormatData/es_EC/TimePatterns/0=HH:mm:ss zzzz FormatData/es_EC/TimePatterns/1=H:mm:ss z FormatData/es_EC/TimePatterns/2=H:mm:ss FormatData/es_EC/TimePatterns/3=H:mm + +# bug 8037343 +FormatData/es_DO/DatePatterns/2=dd/MM/yyyy +FormatData/es_DO/DatePatterns/3=dd/MM/yy diff --git a/jdk/test/sun/text/resources/LocaleDataTest.java b/jdk/test/sun/text/resources/LocaleDataTest.java index 1c31cc9ad3b..9b44eec236b 100644 --- a/jdk/test/sun/text/resources/LocaleDataTest.java +++ b/jdk/test/sun/text/resources/LocaleDataTest.java @@ -36,6 +36,7 @@ * 6919624 6998391 7019267 7020960 7025837 7020583 7036905 7066203 7101495 * 7003124 7085757 7028073 7171028 7189611 8000983 7195759 8004489 8006509 * 7114053 7074882 7040556 8013836 8021121 6192407 6931564 8027695 8017142 + * 8037343 * @summary Verify locale data * */ diff --git a/jdk/test/sun/tools/jcmd/TestJcmdSanity.java b/jdk/test/sun/tools/jcmd/TestJcmdSanity.java index d32fb18d2c1..89152216010 100644 --- a/jdk/test/sun/tools/jcmd/TestJcmdSanity.java +++ b/jdk/test/sun/tools/jcmd/TestJcmdSanity.java @@ -41,7 +41,7 @@ import jdk.testlibrary.Utils; * @bug 7104647 7154822 * @library /lib/testlibrary * @build jdk.testlibrary.* - * @run main TestJcmdSanity + * @run main/othervm -XX:+UsePerfData TestJcmdSanity */ public class TestJcmdSanity { diff --git a/jdk/test/sun/tools/jstat/JStatInterval.java b/jdk/test/sun/tools/jstat/JStatInterval.java index 0d39df23e10..8c1203be4c8 100644 --- a/jdk/test/sun/tools/jstat/JStatInterval.java +++ b/jdk/test/sun/tools/jstat/JStatInterval.java @@ -28,8 +28,7 @@ * @summary Test checks case when target application finishes execution and jstat didn't complete work. jstat is started with interval = 100 (jstat -compiler 100) and monitored application finishes after 500ms. This shouldn't cause crash or hang in target application or in jstat. - * @build jdk.testlibrary.ProcessTools jdk.testlibrary.JDKToolLauncher - * @build JStatInterval + * @build jdk.testlibrary.* JStatInterval * @run main JStatInterval */ diff --git a/jdk/test/sun/tools/jstatd/TestJstatdDefaults.java b/jdk/test/sun/tools/jstatd/TestJstatdDefaults.java index d68f384c35c..c3973f824e9 100644 --- a/jdk/test/sun/tools/jstatd/TestJstatdDefaults.java +++ b/jdk/test/sun/tools/jstatd/TestJstatdDefaults.java @@ -25,7 +25,7 @@ * @test * @bug 4990825 * @library /lib/testlibrary - * @build JstatdTest JstatGCUtilParser + * @build jdk.testlibrary.* JstatdTest JstatGCUtilParser * @run main/timeout=60 TestJstatdDefaults */ public class TestJstatdDefaults { diff --git a/jdk/test/sun/tools/jstatd/TestJstatdExternalRegistry.java b/jdk/test/sun/tools/jstatd/TestJstatdExternalRegistry.java index da81db13bc9..fdf2e484c46 100644 --- a/jdk/test/sun/tools/jstatd/TestJstatdExternalRegistry.java +++ b/jdk/test/sun/tools/jstatd/TestJstatdExternalRegistry.java @@ -25,7 +25,7 @@ * @test * @bug 4990825 7092186 * @library /lib/testlibrary - * @build JstatdTest JstatGCUtilParser + * @build jdk.testlibrary.* JstatdTest JstatGCUtilParser * @run main/timeout=60 TestJstatdExternalRegistry */ public class TestJstatdExternalRegistry { diff --git a/jdk/test/sun/tools/jstatd/TestJstatdPort.java b/jdk/test/sun/tools/jstatd/TestJstatdPort.java index f2d479b6e30..bba8732bad9 100644 --- a/jdk/test/sun/tools/jstatd/TestJstatdPort.java +++ b/jdk/test/sun/tools/jstatd/TestJstatdPort.java @@ -25,7 +25,7 @@ * @test * @bug 4990825 * @library /lib/testlibrary - * @build JstatdTest JstatGCUtilParser + * @build jdk.testlibrary.* JstatdTest JstatGCUtilParser * @run main/timeout=60 TestJstatdPort */ public class TestJstatdPort { diff --git a/jdk/test/sun/tools/jstatd/TestJstatdPortAndServer.java b/jdk/test/sun/tools/jstatd/TestJstatdPortAndServer.java index e771561e99c..6b516f9140d 100644 --- a/jdk/test/sun/tools/jstatd/TestJstatdPortAndServer.java +++ b/jdk/test/sun/tools/jstatd/TestJstatdPortAndServer.java @@ -25,7 +25,7 @@ * @test * @bug 4990825 * @library /lib/testlibrary - * @build JstatdTest JstatGCUtilParser + * @build jdk.testlibrary.* JstatdTest JstatGCUtilParser * @run main/timeout=60 TestJstatdPortAndServer */ public class TestJstatdPortAndServer { diff --git a/jdk/test/sun/tools/jstatd/TestJstatdServer.java b/jdk/test/sun/tools/jstatd/TestJstatdServer.java index f8e87a668fc..fbf1c56026f 100644 --- a/jdk/test/sun/tools/jstatd/TestJstatdServer.java +++ b/jdk/test/sun/tools/jstatd/TestJstatdServer.java @@ -25,7 +25,7 @@ * @test * @bug 4990825 * @library /lib/testlibrary - * @build JstatdTest JstatGCUtilParser + * @build jdk.testlibrary.* JstatdTest JstatGCUtilParser * @run main/timeout=60 TestJstatdServer */ public class TestJstatdServer { diff --git a/jdk/test/sun/tools/jstatd/TestJstatdUsage.java b/jdk/test/sun/tools/jstatd/TestJstatdUsage.java index 3fd5efc19f3..abec798df6f 100644 --- a/jdk/test/sun/tools/jstatd/TestJstatdUsage.java +++ b/jdk/test/sun/tools/jstatd/TestJstatdUsage.java @@ -28,7 +28,7 @@ import jdk.testlibrary.OutputAnalyzer; * @test * @bug 4990825 * @library /lib/testlibrary - * @build jdk.testlibrary.JDKToolLauncher jdk.testlibrary.OutputAnalyzer + * @build jdk.testlibrary.* * @run main TestJstatdUsage */ public class TestJstatdUsage { diff --git a/langtools/.hgtags b/langtools/.hgtags index 7020c726d31..d963cacab98 100644 --- a/langtools/.hgtags +++ b/langtools/.hgtags @@ -256,3 +256,5 @@ ea02d24b3f1dd1417132d6587dd38b056cca0be2 jdk9-b08 f04fccfbd880c819affc3ef33e0083aab9556409 jdk9-b11 72efbe612e494f98b9c3ede1b4a3d02304e1e9cc jdk9-b12 2c8bb81b5d48161019218c7604fa88c67edc6105 jdk9-b13 +1df3f53b9d980b66739f05e14053381ffb0f38ee jdk9-b14 +8666a9611eb8ba711b001bf8d942282e3e2d8e3d jdk9-b15 diff --git a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java index a92956eccf3..13c6637fc98 100644 --- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java +++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java @@ -28,6 +28,8 @@ package com.sun.tools.doclets.formats.html; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import com.sun.javadoc.*; import com.sun.tools.doclets.formats.html.markup.*; @@ -139,42 +141,37 @@ public class HtmlDocletWriter extends HtmlDocWriter { if (index < 0) { return htmlstr; } - String lowerHtml = StringUtils.toLowerCase(htmlstr); - final String docroot = "{@docroot}"; - // Return index of first occurrence of {@docroot} - // Note: {@docRoot} is not case sensitive when passed in w/command line option - index = lowerHtml.indexOf(docroot, index); - if (index < 0) { + Matcher docrootMatcher = docrootPattern.matcher(htmlstr); + if (!docrootMatcher.find()) { return htmlstr; } StringBuilder buf = new StringBuilder(); - int previndex = 0; - while (true) { - // Search for lowercase version of {@docRoot} - index = lowerHtml.indexOf(docroot, previndex); - // If next {@docRoot} tag not found, append rest of htmlstr and exit loop - if (index < 0) { - buf.append(htmlstr.substring(previndex)); - break; - } - // If next {@docroot} tag found, append htmlstr up to start of tag - buf.append(htmlstr.substring(previndex, index)); - previndex = index + docroot.length(); - if (configuration.docrootparent.length() > 0 && htmlstr.startsWith("/..", previndex)) { + int prevEnd = 0; + do { + int match = docrootMatcher.start(); + // append htmlstr up to start of next {@docroot} + buf.append(htmlstr.substring(prevEnd, match)); + prevEnd = docrootMatcher.end(); + if (configuration.docrootparent.length() > 0 && htmlstr.startsWith("/..", prevEnd)) { // Insert the absolute link if {@docRoot} is followed by "/..". buf.append(configuration.docrootparent); - previndex += 3; + prevEnd += 3; } else { // Insert relative path where {@docRoot} was located buf.append(pathToRoot.isEmpty() ? "." : pathToRoot.getPath()); } // Append slash if next character is not a slash - if (previndex < htmlstr.length() && htmlstr.charAt(previndex) != '/') { + if (prevEnd < htmlstr.length() && htmlstr.charAt(prevEnd) != '/') { buf.append('/'); } - } + } while (docrootMatcher.find()); + buf.append(htmlstr.substring(prevEnd)); return buf.toString(); } + //where: + // Note: {@docRoot} is not case sensitive when passed in w/command line option: + private static final Pattern docrootPattern = + Pattern.compile(Pattern.quote("{@docroot}"), Pattern.CASE_INSENSITIVE); /** * Get the script to show or hide the All classes link. @@ -1690,13 +1687,13 @@ public class HtmlDocletWriter extends HtmlDocWriter { } //Redirect all relative links. - int end, begin = StringUtils.toLowerCase(text).indexOf("= 0){ StringBuilder textBuff = new StringBuilder(text); while(begin >=0){ if (textBuff.length() > begin + 2 && ! Character.isWhitespace(textBuff.charAt(begin+2))) { - begin = StringUtils.toLowerCase(textBuff.toString()).indexOf(""); - int end = lc.indexOf(""); - if(begin == -1 || end == -1 || end <= begin){ - return tag; - } else { - return tag.substring(begin + 6, end); - } - } - /** * {@inheritDoc} */ diff --git a/langtools/src/share/classes/com/sun/tools/javac/api/JavacTrees.java b/langtools/src/share/classes/com/sun/tools/javac/api/JavacTrees.java index eb4b43f3622..56296d458c6 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/api/JavacTrees.java +++ b/langtools/src/share/classes/com/sun/tools/javac/api/JavacTrees.java @@ -394,7 +394,7 @@ public class JavacTrees extends DocTrees { paramTypes = lb.toList(); } - ClassSymbol sym = (ClassSymbol) types.upperBound(tsym.type).tsym; + ClassSymbol sym = (ClassSymbol) types.cvarUpperBound(tsym.type).tsym; Symbol msym = (memberName == sym.name) ? findConstructor(sym, paramTypes) diff --git a/langtools/src/share/classes/com/sun/tools/javac/code/ClassFinder.java b/langtools/src/share/classes/com/sun/tools/javac/code/ClassFinder.java new file mode 100644 index 00000000000..4c19370386d --- /dev/null +++ b/langtools/src/share/classes/com/sun/tools/javac/code/ClassFinder.java @@ -0,0 +1,537 @@ +/* + * Copyright (c) 1999, 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 com.sun.tools.javac.code; + +import java.io.*; +import java.util.EnumSet; +import java.util.Set; +import javax.lang.model.SourceVersion; +import javax.tools.JavaFileObject; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileManager.Location; +import javax.tools.StandardJavaFileManager; + +import static javax.tools.StandardLocation.*; + +import com.sun.tools.javac.comp.Annotate; +import com.sun.tools.javac.code.Symbol.*; +import com.sun.tools.javac.jvm.ClassReader; +import com.sun.tools.javac.util.*; + +import static com.sun.tools.javac.code.Flags.*; +import static com.sun.tools.javac.code.Kinds.*; + +import static com.sun.tools.javac.main.Option.*; + +/** + * This class provides operations to locate class definitions + * from the source and class files on the paths provided to javac. + * + *

    This is NOT part of any supported API. + * If you write code that depends on this, you do so at your own risk. + * This code and its internal interfaces are subject to change or + * deletion without notice. + */ +public class ClassFinder { + /** The context key for the class finder. */ + protected static final Context.Key classFinderKey = new Context.Key<>(); + + ClassReader reader; + + Annotate annotate; + + /** Switch: verbose output. + */ + boolean verbose; + + /** + * Switch: cache completion failures unless -XDdev is used + */ + private boolean cacheCompletionFailure; + + /** + * Switch: prefer source files instead of newer when both source + * and class are available + **/ + protected boolean preferSource; + + /** + * Switch: Search classpath and sourcepath for classes before the + * bootclasspath + */ + protected boolean userPathsFirst; + + /** The log to use for verbose output + */ + final Log log; + + /** The symbol table. */ + Symtab syms; + + /** The name table. */ + final Names names; + + /** Force a completion failure on this name + */ + final Name completionFailureName; + + /** Access to files + */ + private final JavaFileManager fileManager; + + /** Factory for diagnostics + */ + JCDiagnostic.Factory diagFactory; + + /** Can be reassigned from outside: + * the completer to be used for ".java" files. If this remains unassigned + * ".java" files will not be loaded. + */ + public Completer sourceCompleter = null; + + /** The path name of the class file currently being read. + */ + protected JavaFileObject currentClassFile = null; + + /** The class or method currently being read. + */ + protected Symbol currentOwner = null; + + /** + * Completer that delegates to the complete-method of this class. + */ + private final Completer thisCompleter = new Completer() { + @Override + public void complete(Symbol sym) throws CompletionFailure { + ClassFinder.this.complete(sym); + } + }; + + public Completer getCompleter() { + return thisCompleter; + } + + /** Get the ClassFinder instance for this invocation. */ + public static ClassFinder instance(Context context) { + ClassFinder instance = context.get(classFinderKey); + if (instance == null) + instance = new ClassFinder(context); + return instance; + } + + /** Construct a new class reader. */ + protected ClassFinder(Context context) { + context.put(classFinderKey, this); + reader = ClassReader.instance(context); + names = Names.instance(context); + syms = Symtab.instance(context); + fileManager = context.get(JavaFileManager.class); + if (fileManager == null) + throw new AssertionError("FileManager initialization error"); + diagFactory = JCDiagnostic.Factory.instance(context); + + log = Log.instance(context); + annotate = Annotate.instance(context); + + Options options = Options.instance(context); + verbose = options.isSet(VERBOSE); + cacheCompletionFailure = options.isUnset("dev"); + preferSource = "source".equals(options.get("-Xprefer")); + userPathsFirst = options.isSet(XXUSERPATHSFIRST); + + + completionFailureName = + options.isSet("failcomplete") + ? names.fromString(options.get("failcomplete")) + : null; + } + +/************************************************************************ + * Loading Classes + ***********************************************************************/ + + /** Completion for classes to be loaded. Before a class is loaded + * we make sure its enclosing class (if any) is loaded. + */ + private void complete(Symbol sym) throws CompletionFailure { + if (sym.kind == TYP) { + ClassSymbol c = (ClassSymbol)sym; + c.members_field = new Scope.ErrorScope(c); // make sure it's always defined + annotate.enterStart(); + try { + completeOwners(c.owner); + completeEnclosing(c); + } finally { + // The flush needs to happen only after annotations + // are filled in. + annotate.enterDoneWithoutFlush(); + } + fillIn(c); + } else if (sym.kind == PCK) { + PackageSymbol p = (PackageSymbol)sym; + try { + fillIn(p); + } catch (IOException ex) { + throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex); + } + } + if (!reader.filling) + annotate.flush(); // finish attaching annotations + } + + /** complete up through the enclosing package. */ + private void completeOwners(Symbol o) { + if (o.kind != PCK) completeOwners(o.owner); + o.complete(); + } + + /** + * Tries to complete lexically enclosing classes if c looks like a + * nested class. This is similar to completeOwners but handles + * the situation when a nested class is accessed directly as it is + * possible with the Tree API or javax.lang.model.*. + */ + private void completeEnclosing(ClassSymbol c) { + if (c.owner.kind == PCK) { + Symbol owner = c.owner; + for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) { + Symbol encl = owner.members().lookup(name).sym; + if (encl == null) + encl = syms.classes.get(TypeSymbol.formFlatName(name, owner)); + if (encl != null) + encl.complete(); + } + } + } + + /** Fill in definition of class `c' from corresponding class or + * source file. + */ + private void fillIn(ClassSymbol c) { + if (completionFailureName == c.fullname) { + throw new CompletionFailure(c, "user-selected completion failure by class name"); + } + currentOwner = c; + JavaFileObject classfile = c.classfile; + if (classfile != null) { + JavaFileObject previousClassFile = currentClassFile; + try { + if (reader.filling) { + Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile); + } + currentClassFile = classfile; + if (verbose) { + log.printVerbose("loading", currentClassFile.toString()); + } + if (classfile.getKind() == JavaFileObject.Kind.CLASS) { + reader.readClassFile(c); + } else { + if (sourceCompleter != null) { + sourceCompleter.complete(c); + } else { + throw new IllegalStateException("Source completer required to read " + + classfile.toUri()); + } + } + return; + } finally { + currentClassFile = previousClassFile; + } + } else { + JCDiagnostic diag = + diagFactory.fragment("class.file.not.found", c.flatname); + throw + newCompletionFailure(c, diag); + } + } + // where + /** Static factory for CompletionFailure objects. + * In practice, only one can be used at a time, so we share one + * to reduce the expense of allocating new exception objects. + */ + private CompletionFailure newCompletionFailure(TypeSymbol c, + JCDiagnostic diag) { + if (!cacheCompletionFailure) { + // log.warning("proc.messager", + // Log.getLocalizedString("class.file.not.found", c.flatname)); + // c.debug.printStackTrace(); + return new CompletionFailure(c, diag); + } else { + CompletionFailure result = cachedCompletionFailure; + result.sym = c; + result.diag = diag; + return result; + } + } + private CompletionFailure cachedCompletionFailure = + new CompletionFailure(null, (JCDiagnostic) null); + { + cachedCompletionFailure.setStackTrace(new StackTraceElement[0]); + } + + + /** Load a toplevel class with given fully qualified name + * The class is entered into `classes' only if load was successful. + */ + public ClassSymbol loadClass(Name flatname) throws CompletionFailure { + boolean absent = syms.classes.get(flatname) == null; + ClassSymbol c = syms.enterClass(flatname); + if (c.members_field == null && c.completer != null) { + try { + c.complete(); + } catch (CompletionFailure ex) { + if (absent) syms.classes.remove(flatname); + throw ex; + } + } + return c; + } + +/************************************************************************ + * Loading Packages + ***********************************************************************/ + + /** Include class corresponding to given class file in package, + * unless (1) we already have one the same kind (.class or .java), or + * (2) we have one of the other kind, and the given class file + * is older. + */ + protected void includeClassFile(PackageSymbol p, JavaFileObject file) { + if ((p.flags_field & EXISTS) == 0) + for (Symbol q = p; q != null && q.kind == PCK; q = q.owner) + q.flags_field |= EXISTS; + JavaFileObject.Kind kind = file.getKind(); + int seen; + if (kind == JavaFileObject.Kind.CLASS) + seen = CLASS_SEEN; + else + seen = SOURCE_SEEN; + String binaryName = fileManager.inferBinaryName(currentLoc, file); + int lastDot = binaryName.lastIndexOf("."); + Name classname = names.fromString(binaryName.substring(lastDot + 1)); + boolean isPkgInfo = classname == names.package_info; + ClassSymbol c = isPkgInfo + ? p.package_info + : (ClassSymbol) p.members_field.lookup(classname).sym; + if (c == null) { + c = syms.enterClass(classname, p); + if (c.classfile == null) // only update the file if's it's newly created + c.classfile = file; + if (isPkgInfo) { + p.package_info = c; + } else { + if (c.owner == p) // it might be an inner class + p.members_field.enter(c); + } + } else if (!preferCurrent && c.classfile != null && (c.flags_field & seen) == 0) { + // if c.classfile == null, we are currently compiling this class + // and no further action is necessary. + // if (c.flags_field & seen) != 0, we have already encountered + // a file of the same kind; again no further action is necessary. + if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0) + c.classfile = preferredFileObject(file, c.classfile); + } + c.flags_field |= seen; + } + + /** Implement policy to choose to derive information from a source + * file or a class file when both are present. May be overridden + * by subclasses. + */ + protected JavaFileObject preferredFileObject(JavaFileObject a, + JavaFileObject b) { + + if (preferSource) + return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b; + else { + long adate = a.getLastModified(); + long bdate = b.getLastModified(); + // 6449326: policy for bad lastModifiedTime in ClassReader + //assert adate >= 0 && bdate >= 0; + return (adate > bdate) ? a : b; + } + } + + /** + * specifies types of files to be read when filling in a package symbol + */ + protected EnumSet getPackageFileKinds() { + return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE); + } + + /** + * this is used to support javadoc + */ + protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) { + } + + protected Location currentLoc; // FIXME + + private boolean verbosePath = true; + + // Set to true when the currently selected file should be kept + private boolean preferCurrent; + + /** Load directory of package into members scope. + */ + private void fillIn(PackageSymbol p) throws IOException { + if (p.members_field == null) + p.members_field = new Scope(p); + + preferCurrent = false; + if (userPathsFirst) { + scanUserPaths(p); + preferCurrent = true; + scanPlatformPath(p); + } else { + scanPlatformPath(p); + scanUserPaths(p); + } + verbosePath = false; + } + + /** + * Scans class path and source path for files in given package. + */ + private void scanUserPaths(PackageSymbol p) throws IOException { + Set kinds = getPackageFileKinds(); + + Set classKinds = EnumSet.copyOf(kinds); + classKinds.remove(JavaFileObject.Kind.SOURCE); + boolean wantClassFiles = !classKinds.isEmpty(); + + Set sourceKinds = EnumSet.copyOf(kinds); + sourceKinds.remove(JavaFileObject.Kind.CLASS); + boolean wantSourceFiles = !sourceKinds.isEmpty(); + + boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH); + + if (verbose && verbosePath) { + if (fileManager instanceof StandardJavaFileManager) { + StandardJavaFileManager fm = (StandardJavaFileManager)fileManager; + if (haveSourcePath && wantSourceFiles) { + List path = List.nil(); + for (File file : fm.getLocation(SOURCE_PATH)) { + path = path.prepend(file); + } + log.printVerbose("sourcepath", path.reverse().toString()); + } else if (wantSourceFiles) { + List path = List.nil(); + for (File file : fm.getLocation(CLASS_PATH)) { + path = path.prepend(file); + } + log.printVerbose("sourcepath", path.reverse().toString()); + } + if (wantClassFiles) { + List path = List.nil(); + for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) { + path = path.prepend(file); + } + for (File file : fm.getLocation(CLASS_PATH)) { + path = path.prepend(file); + } + log.printVerbose("classpath", path.reverse().toString()); + } + } + } + + String packageName = p.fullname.toString(); + if (wantSourceFiles && !haveSourcePath) { + fillIn(p, CLASS_PATH, + fileManager.list(CLASS_PATH, + packageName, + kinds, + false)); + } else { + if (wantClassFiles) + fillIn(p, CLASS_PATH, + fileManager.list(CLASS_PATH, + packageName, + classKinds, + false)); + if (wantSourceFiles) + fillIn(p, SOURCE_PATH, + fileManager.list(SOURCE_PATH, + packageName, + sourceKinds, + false)); + } + } + + /** + * Scans platform class path for files in given package. + */ + private void scanPlatformPath(PackageSymbol p) throws IOException { + fillIn(p, PLATFORM_CLASS_PATH, + fileManager.list(PLATFORM_CLASS_PATH, + p.fullname.toString(), + EnumSet.of(JavaFileObject.Kind.CLASS), + false)); + } + // where + private void fillIn(PackageSymbol p, + Location location, + Iterable files) + { + currentLoc = location; + for (JavaFileObject fo : files) { + switch (fo.getKind()) { + case CLASS: + case SOURCE: { + // TODO pass binaryName to includeClassFile + String binaryName = fileManager.inferBinaryName(currentLoc, fo); + String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1); + if (SourceVersion.isIdentifier(simpleName) || + simpleName.equals("package-info")) + includeClassFile(p, fo); + break; + } + default: + extraFileActions(p, fo); + } + } + } + + /** + * Used for bad class definition files, such as bad .class files or + * for .java files with unexpected package or class names. + */ + public static class BadClassFile extends CompletionFailure { + private static final long serialVersionUID = 0; + + public BadClassFile(TypeSymbol sym, JavaFileObject file, JCDiagnostic diag, + JCDiagnostic.Factory diagFactory) { + super(sym, createBadClassFileDiagnostic(file, diag, diagFactory)); + } + // where + private static JCDiagnostic createBadClassFileDiagnostic( + JavaFileObject file, JCDiagnostic diag, JCDiagnostic.Factory diagFactory) { + String key = (file.getKind() == JavaFileObject.Kind.SOURCE + ? "bad.source.file.header" : "bad.class.file.header"); + return diagFactory.fragment(key, file, diag); + } + } +} diff --git a/langtools/src/share/classes/com/sun/tools/javac/code/Symtab.java b/langtools/src/share/classes/com/sun/tools/javac/code/Symtab.java index 59e2e19d7d9..9ced8f07d83 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/code/Symtab.java +++ b/langtools/src/share/classes/com/sun/tools/javac/code/Symtab.java @@ -50,7 +50,6 @@ import com.sun.tools.javac.code.Type.JCVoidType; import com.sun.tools.javac.code.Type.MethodType; import com.sun.tools.javac.code.Type.UnknownType; import com.sun.tools.javac.jvm.ByteCodes; -import com.sun.tools.javac.jvm.ClassReader; import com.sun.tools.javac.jvm.Target; import com.sun.tools.javac.util.Assert; import com.sun.tools.javac.util.Context; @@ -470,8 +469,8 @@ public class Symtab { Scope scope = new Scope(predefClass); predefClass.members_field = scope; - // Get the initial completer for Symbols from the ClassReader - initialCompleter = ClassReader.instance(context).getCompleter(); + // Get the initial completer for Symbols from the ClassFinder + initialCompleter = ClassFinder.instance(context).getCompleter(); rootPackage.completer = initialCompleter; unnamedPackage.completer = initialCompleter; diff --git a/langtools/src/share/classes/com/sun/tools/javac/code/Types.java b/langtools/src/share/classes/com/sun/tools/javac/code/Types.java index 2184d0c1490..783f6282d10 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/code/Types.java +++ b/langtools/src/share/classes/com/sun/tools/javac/code/Types.java @@ -42,9 +42,8 @@ import com.sun.tools.javac.comp.AttrContext; import com.sun.tools.javac.comp.Check; import com.sun.tools.javac.comp.Enter; import com.sun.tools.javac.comp.Env; -import com.sun.tools.javac.jvm.ClassReader; -import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.util.*; + import static com.sun.tools.javac.code.BoundKind.*; import static com.sun.tools.javac.code.Flags.*; import static com.sun.tools.javac.code.Scope.*; @@ -84,7 +83,6 @@ public class Types { final boolean allowBoxing; final boolean allowCovariantReturns; final boolean allowObjectToPrimitiveCast; - final ClassReader reader; final Check chk; final Enter enter; JCDiagnostic.Factory diags; @@ -110,7 +108,6 @@ public class Types { allowBoxing = source.allowBoxing(); allowCovariantReturns = source.allowCovariantReturns(); allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast(); - reader = ClassReader.instance(context); chk = Check.instance(context); enter = Enter.instance(context); capturedName = names.fromString(""); @@ -121,37 +118,34 @@ public class Types { } // - // + // /** - * The "rvalue conversion".
    - * The upper bound of most types is the type - * itself. Wildcards, on the other hand have upper - * and lower bounds. - * @param t a type - * @return the upper bound of the given type + * Get a wildcard's upper bound, returning non-wildcards unchanged. + * @param t a type argument, either a wildcard or a type */ - public Type upperBound(Type t) { - return upperBound.visit(t); + public Type wildUpperBound(Type t) { + if (t.hasTag(WILDCARD)) { + WildcardType w = (WildcardType) t; + if (w.isSuperBound()) + return w.bound == null ? syms.objectType : w.bound.bound; + else + return wildUpperBound(w.type); + } + else return t; } - // where - private final MapVisitor upperBound = new MapVisitor() { - @Override - public Type visitWildcardType(WildcardType t, Void ignored) { - if (t.isSuperBound()) - return t.bound == null ? syms.objectType : t.bound.bound; - else - return visit(t.type); - } + /** + * Get a capture variable's upper bound, returning other types unchanged. + * @param t a type + */ + public Type cvarUpperBound(Type t) { + if (t.hasTag(TYPEVAR)) { + TypeVar v = (TypeVar) t; + return v.isCaptured() ? cvarUpperBound(v.bound) : v; + } + else return t; + } - @Override - public Type visitCapturedType(CapturedType t, Void ignored) { - return visit(t.bound); - } - }; - //
    - - // /** * Get a wildcard's lower bound, returning non-wildcards unchanged. * @param t a type argument, either a wildcard or a type @@ -163,9 +157,7 @@ public class Types { } else return t; } - // - // /** * Get a capture variable's lower bound, returning other types unchanged. * @param t a type @@ -897,7 +889,7 @@ public class Types { s.getAnnotationMirrors()); changed = true; } else if (s != orig) { - s = new WildcardType(upperBound(s), + s = new WildcardType(wildUpperBound(s), BoundKind.EXTENDS, syms.boundClass, s.getAnnotationMirrors()); @@ -1107,7 +1099,7 @@ public class Types { //check that u == t, where u has been set by Type.withTypeVar return s.isSuperBound() && !s.isExtendsBound() && - visit(t, upperBound(s)); + visit(t, wildUpperBound(s)); } } default: @@ -1134,7 +1126,7 @@ public class Types { return visit(s, t); if (s.isSuperBound() && !s.isExtendsBound()) - return visit(t, upperBound(s)) && visit(t, wildLowerBound(s)); + return visit(t, wildUpperBound(s)) && visit(t, wildLowerBound(s)); if (t.isCompound() && s.isCompound()) { if (!visit(supertype(t), supertype(s))) @@ -1301,7 +1293,7 @@ public class Types { switch(wt.kind) { case UNBOUND: //similar to ? extends Object case EXTENDS: { - Type bound = upperBound(s); + Type bound = wildUpperBound(s); undetvar.addBound(InferenceBound.UPPER, bound, this); break; } @@ -1362,28 +1354,6 @@ public class Types { // where private TypeRelation containsType = new TypeRelation() { - private Type U(Type t) { - while (t.hasTag(WILDCARD)) { - WildcardType w = (WildcardType)t; - if (w.isSuperBound()) - return w.bound == null ? syms.objectType : w.bound.bound; - else - t = w.type; - } - return t; - } - - private Type L(Type t) { - while (t.hasTag(WILDCARD)) { - WildcardType w = (WildcardType)t; - if (w.isExtendsBound()) - return syms.botType; - else - t = w.type; - } - return t; - } - public Boolean visitType(Type t, Type s) { if (s.isPartial()) return containedBy(s, t); @@ -1395,13 +1365,13 @@ public class Types { // System.err.println(); // System.err.format(" does %s contain %s?%n", t, s); // System.err.format(" %s U(%s) <: U(%s) %s = %s%n", -// upperBound(s), s, t, U(t), +// wildUpperBound(s), s, t, wildUpperBound(t), // t.isSuperBound() -// || isSubtypeNoCapture(upperBound(s), U(t))); +// || isSubtypeNoCapture(wildUpperBound(s), wildUpperBound(t))); // System.err.format(" %s L(%s) <: L(%s) %s = %s%n", -// L(t), t, s, wildLowerBound(s), +// wildLowerBound(t), t, s, wildLowerBound(s), // t.isExtendsBound() -// || isSubtypeNoCapture(L(t), wildLowerBound(s))); +// || isSubtypeNoCapture(wildLowerBound(t), wildLowerBound(s))); // System.err.println(); // } @@ -1413,8 +1383,9 @@ public class Types { // debugContainsType(t, s); return isSameWildcard(t, s) || isCaptureOf(s, t) - || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), wildLowerBound(s))) && - (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t)))); + || ((t.isExtendsBound() || isSubtypeNoCapture(wildLowerBound(t), wildLowerBound(s))) && + // TODO: JDK-8039214, cvarUpperBound call here is incorrect + (t.isSuperBound() || isSubtypeNoCapture(cvarUpperBound(wildUpperBound(s)), wildUpperBound(t)))); } } @@ -1532,7 +1503,7 @@ public class Types { @Override public Boolean visitWildcardType(WildcardType t, Type s) { - return isCastable(upperBound(t), s, warnStack.head); + return isCastable(wildUpperBound(t), s, warnStack.head); } @Override @@ -1773,12 +1744,12 @@ public class Types { if (t.isExtendsBound()) { if (s.isExtendsBound()) - return !isCastableRecursive(t.type, upperBound(s)); + return !isCastableRecursive(t.type, wildUpperBound(s)); else if (s.isSuperBound()) return notSoftSubtypeRecursive(wildLowerBound(s), t.type); } else if (t.isSuperBound()) { if (s.isExtendsBound()) - return notSoftSubtypeRecursive(t.type, upperBound(s)); + return notSoftSubtypeRecursive(t.type, wildUpperBound(s)); } return false; } @@ -1814,7 +1785,7 @@ public class Types { noWarnings); } if (!s.hasTag(WILDCARD)) - s = upperBound(s); + s = cvarUpperBound(s); return !isSubtype(t, relaxBound(s)); } @@ -1871,7 +1842,7 @@ public class Types { // public boolean isArray(Type t) { while (t.hasTag(WILDCARD)) - t = upperBound(t); + t = wildUpperBound(t); return t.hasTag(ARRAY); } @@ -1881,7 +1852,7 @@ public class Types { public Type elemtype(Type t) { switch (t.getTag()) { case WILDCARD: - return elemtype(upperBound(t)); + return elemtype(wildUpperBound(t)); case ARRAY: return ((ArrayType)t).elemtype; case FORALL: @@ -2083,7 +2054,7 @@ public class Types { @Override public Type visitWildcardType(WildcardType t, Symbol sym) { - return memberType(upperBound(t), sym); + return memberType(wildUpperBound(t), sym); } @Override @@ -2211,7 +2182,7 @@ public class Types { @Override public Type visitWildcardType(WildcardType t, Boolean recurse) { final List annos = t.getAnnotationMirrors(); - Type erased = erasure(upperBound(t), recurse); + Type erased = erasure(wildUpperBound(t), recurse); if (!annos.isEmpty()) { erased = erased.annotatedType(annos); } @@ -2420,8 +2391,7 @@ public class Types { if (t.hasErasedSupertypes()) { t.interfaces_field = erasureRecursive(interfaces); } else if (formals.nonEmpty()) { - t.interfaces_field = - upperBounds(subst(interfaces, formals, actuals)); + t.interfaces_field = subst(interfaces, formals, actuals); } else { t.interfaces_field = interfaces; @@ -2990,7 +2960,7 @@ public class Types { t.getAnnotationMirrors()); } else { Type st = subst(supertype(t)); - List is = upperBounds(subst(interfaces(t))); + List is = subst(interfaces(t)); if (st == supertype(t) && is == interfaces(t)) return t; else @@ -3007,7 +2977,7 @@ public class Types { return t; } else { if (t.isExtendsBound() && bound.isExtendsBound()) - bound = upperBound(bound); + bound = wildUpperBound(bound); return new WildcardType(bound, t.kind, syms.boundClass, t.bound, t.getAnnotationMirrors()); } @@ -3461,8 +3431,8 @@ public class Types { TypePair pair = new TypePair(c1, c2); Type m; if (mergeCache.add(pair)) { - m = new WildcardType(lub(upperBound(act1.head), - upperBound(act2.head)), + m = new WildcardType(lub(wildUpperBound(act1.head), + wildUpperBound(act2.head)), BoundKind.EXTENDS, syms.boundClass, Type.noAnnotations); @@ -4044,16 +4014,6 @@ public class Types { // // - private List upperBounds(List ss) { - if (ss.isEmpty()) return ss; - Type head = upperBound(ss.head); - List tail = upperBounds(ss.tail); - if (head != ss.head || tail != ss.tail) - return tail.prepend(head); - else - return ss; - } - private boolean sideCast(Type from, Type to, Warner warn) { // We are casting from type $from$ to type $to$, which are // non-final unrelated types. This method @@ -4210,7 +4170,7 @@ public class Types { @Override public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure { if (source.isExtendsBound()) - adaptRecursive(upperBound(source), upperBound(target)); + adaptRecursive(wildUpperBound(source), wildUpperBound(target)); else if (source.isSuperBound()) adaptRecursive(wildLowerBound(source), wildLowerBound(target)); return null; @@ -4227,7 +4187,7 @@ public class Types { val = isSubtype(wildLowerBound(val), wildLowerBound(target)) ? target : val; } else if (val.isExtendsBound() && target.isExtendsBound()) { - val = isSubtype(upperBound(val), upperBound(target)) + val = isSubtype(wildUpperBound(val), wildUpperBound(target)) ? val : target; } else if (!isSameType(val, target)) { throw new AdaptFailure(); @@ -4338,7 +4298,7 @@ public class Types { } public Type visitType(Type t, Void s) { - return high ? upperBound(t) : t; + return t; } @Override @@ -4736,7 +4696,7 @@ public class Types { assembleClassSig(rawOuter ? types.erasure(outer) : outer); - append('.'); + append(rawOuter ? '$' : '.'); Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname)); append(rawOuter ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength()) diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java index 335704eaef4..defa825bfe5 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java +++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java @@ -1176,7 +1176,7 @@ public class Attr extends JCTree.Visitor { //the Formal Parameter of a for-each loop is not in the scope when //attributing the for-each expression; we mimick this by attributing //the for-each expression first (against original scope). - Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv)); + Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv)); attribStat(tree.var, loopEnv); chk.checkNonVoid(tree.pos(), exprType); Type elemtype = types.elemtype(exprType); // perhaps expr is an array? @@ -1193,7 +1193,7 @@ public class Attr extends JCTree.Visitor { List iterableParams = base.allparams(); elemtype = iterableParams.isEmpty() ? syms.objectType - : types.upperBound(iterableParams.head); + : types.wildUpperBound(iterableParams.head); } } chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type); @@ -4678,16 +4678,30 @@ public class Attr extends JCTree.Visitor { private void initTypeIfNeeded(JCTree that) { if (that.type == null) { if (that.hasTag(METHODDEF)) { - that.type = dummyMethodType(); + that.type = dummyMethodType((JCMethodDecl)that); } else { that.type = syms.unknownType; } } } + /* Construct a dummy method type. If we have a method declaration, + * and the declared return type is void, then use that return type + * instead of UNKNOWN to avoid spurious error messages in lambda + * bodies (see:JDK-8041704). + */ + private Type dummyMethodType(JCMethodDecl md) { + Type restype = syms.unknownType; + if (md != null && md.restype.hasTag(TYPEIDENT)) { + JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype; + if (prim.typetag == VOID) + restype = syms.voidType; + } + return new MethodType(List.nil(), restype, + List.nil(), syms.methodClass); + } private Type dummyMethodType() { - return new MethodType(List.nil(), syms.unknownType, - List.nil(), syms.methodClass); + return dummyMethodType(null); } @Override diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java index 1b412e39405..7cfb78ec5dd 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java +++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Check.java @@ -282,7 +282,7 @@ public class Check { */ public Type completionError(DiagnosticPosition pos, CompletionFailure ex) { log.error(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE, pos, "cant.access", ex.sym, ex.getDetailValue()); - if (ex instanceof ClassReader.BadClassFile + if (ex instanceof ClassFinder.BadClassFile && !suppressAbortOnBadClassFile) throw new Abort(); else return syms.errType; } @@ -621,10 +621,10 @@ public class Check { if (a.isUnbound()) { return true; } else if (!a.hasTag(WILDCARD)) { - a = types.upperBound(a); + a = types.cvarUpperBound(a); return types.isSubtype(a, bound); } else if (a.isExtendsBound()) { - return types.isCastable(bound, types.upperBound(a), types.noWarnings); + return types.isCastable(bound, types.wildUpperBound(a), types.noWarnings); } else if (a.isSuperBound()) { return !types.notSoftSubtype(types.wildLowerBound(a), bound); } diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/DeferredAttr.java b/langtools/src/share/classes/com/sun/tools/javac/comp/DeferredAttr.java index 6265199a8d7..151794853f6 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/comp/DeferredAttr.java +++ b/langtools/src/share/classes/com/sun/tools/javac/comp/DeferredAttr.java @@ -1221,25 +1221,102 @@ public class DeferredAttr extends JCTree.Visitor { } //slow path + Symbol sym = quicklyResolveMethod(env, tree); + + if (sym == null) { + result = ArgumentExpressionKind.POLY; + return; + } + + result = analyzeCandidateMethods(sym, ArgumentExpressionKind.PRIMITIVE, + argumentKindAnalyzer); + } + //where + private boolean isSimpleReceiver(JCTree rec) { + switch (rec.getTag()) { + case IDENT: + return true; + case SELECT: + return isSimpleReceiver(((JCFieldAccess)rec).selected); + case TYPEAPPLY: + case TYPEARRAY: + return true; + case ANNOTATED_TYPE: + return isSimpleReceiver(((JCAnnotatedType)rec).underlyingType); + case APPLY: + return true; + default: + return false; + } + } + private ArgumentExpressionKind reduce(ArgumentExpressionKind kind) { + return argumentKindAnalyzer.reduce(result, kind); + } + MethodAnalyzer argumentKindAnalyzer = + new MethodAnalyzer() { + @Override + public ArgumentExpressionKind process(MethodSymbol ms) { + return ArgumentExpressionKind.methodKind(ms, types); + } + @Override + public ArgumentExpressionKind reduce(ArgumentExpressionKind kind1, + ArgumentExpressionKind kind2) { + switch (kind1) { + case PRIMITIVE: return kind2; + case NO_POLY: return kind2.isPoly() ? kind2 : kind1; + case POLY: return kind1; + default: + Assert.error(); + return null; + } + } + @Override + public boolean shouldStop(ArgumentExpressionKind result) { + return result.isPoly(); + } + }; + + @Override + public void visitLiteral(JCLiteral tree) { + Type litType = attr.litType(tree.typetag); + result = ArgumentExpressionKind.standaloneKind(litType, types); + } + + @Override + void skip(JCTree tree) { + result = ArgumentExpressionKind.NO_POLY; + } + + private Symbol quicklyResolveMethod(Env env, final JCMethodInvocation tree) { final JCExpression rec = tree.meth.hasTag(SELECT) ? ((JCFieldAccess)tree.meth).selected : null; if (rec != null && !isSimpleReceiver(rec)) { - //give up if receiver is too complex (to cut down analysis time) - result = ArgumentExpressionKind.POLY; - return; + return null; } - Type site = rec != null ? - attribSpeculative(rec, env, attr.unknownTypeExprInfo).type : - env.enclClass.sym.type; + Type site; - while (site.hasTag(TYPEVAR)) { - site = site.getUpperBound(); + if (rec != null) { + if (rec.hasTag(APPLY)) { + Symbol recSym = quicklyResolveMethod(env, (JCMethodInvocation) rec); + if (recSym == null) + return null; + Symbol resolvedReturnType = + analyzeCandidateMethods(recSym, syms.errSymbol, returnSymbolAnalyzer); + if (resolvedReturnType == null) + return null; + site = resolvedReturnType.type; + } else { + site = attribSpeculative(rec, env, attr.unknownTypeExprInfo).type; + } + } else { + site = env.enclClass.sym.type; } List args = rs.dummyArgs(tree.args.length()); + Name name = TreeInfo.name(tree.meth); Resolve.LookupHelper lh = rs.new LookupHelper(name, site, args, List.nil(), MethodResolutionPhase.VARARITY) { @Override @@ -1254,61 +1331,60 @@ public class DeferredAttr extends JCTree.Visitor { } }; - Symbol sym = rs.lookupMethod(env, tree, site.tsym, rs.arityMethodCheck, lh); + return rs.lookupMethod(env, tree, site.tsym, rs.arityMethodCheck, lh); + } + //where: + MethodAnalyzer returnSymbolAnalyzer = new MethodAnalyzer() { + @Override + public Symbol process(MethodSymbol ms) { + ArgumentExpressionKind kind = ArgumentExpressionKind.methodKind(ms, types); + return kind != ArgumentExpressionKind.POLY ? ms.getReturnType().tsym : null; + } + @Override + public Symbol reduce(Symbol s1, Symbol s2) { + return s1 == syms.errSymbol ? s2 : s1 == s2 ? s1 : null; + } + @Override + public boolean shouldStop(Symbol result) { + return result == null; + } + }; - if (sym.kind == Kinds.AMBIGUOUS) { - Resolve.AmbiguityError err = (Resolve.AmbiguityError)sym.baseSymbol(); - result = ArgumentExpressionKind.PRIMITIVE; - for (Symbol s : err.ambiguousSyms) { - if (result.isPoly()) break; - if (s.kind == Kinds.MTH) { - result = reduce(ArgumentExpressionKind.methodKind(s, types)); + /** + * Process the result of Resolve.lookupMethod. If sym is a method symbol, the result of + * MethodAnalyzer.process is returned. If sym is an ambiguous symbol, all the candidate + * methods are inspected one by one, using MethodAnalyzer.process. The outcomes are + * reduced using MethodAnalyzer.reduce (using defaultValue as the first value over which + * the reduction runs). MethodAnalyzer.shouldStop can be used to stop the inspection early. + */ + E analyzeCandidateMethods(Symbol sym, E defaultValue, MethodAnalyzer analyzer) { + switch (sym.kind) { + case Kinds.MTH: + return analyzer.process((MethodSymbol) sym); + case Kinds.AMBIGUOUS: + Resolve.AmbiguityError err = (Resolve.AmbiguityError)sym.baseSymbol(); + E res = defaultValue; + for (Symbol s : err.ambiguousSyms) { + if (s.kind == Kinds.MTH) { + res = analyzer.reduce(res, analyzer.process((MethodSymbol) s)); + if (analyzer.shouldStop(res)) + return res; + } } - } - } else { - result = (sym.kind == Kinds.MTH) ? - ArgumentExpressionKind.methodKind(sym, types) : - ArgumentExpressionKind.NO_POLY; + return res; + default: + return defaultValue; } } - //where - private boolean isSimpleReceiver(JCTree rec) { - switch (rec.getTag()) { - case IDENT: - return true; - case SELECT: - return isSimpleReceiver(((JCFieldAccess)rec).selected); - case TYPEAPPLY: - case TYPEARRAY: - return true; - case ANNOTATED_TYPE: - return isSimpleReceiver(((JCAnnotatedType)rec).underlyingType); - default: - return false; - } - } - private ArgumentExpressionKind reduce(ArgumentExpressionKind kind) { - switch (result) { - case PRIMITIVE: return kind; - case NO_POLY: return kind.isPoly() ? kind : result; - case POLY: return result; - default: - Assert.error(); - return null; - } - } - - @Override - public void visitLiteral(JCLiteral tree) { - Type litType = attr.litType(tree.typetag); - result = ArgumentExpressionKind.standaloneKind(litType, types); - } - - @Override - void skip(JCTree tree) { - result = ArgumentExpressionKind.NO_POLY; - } } + + /** Analyzer for methods - used by analyzeCandidateMethods. */ + interface MethodAnalyzer { + E process(MethodSymbol ms); + E reduce(E e1, E e2); + boolean shouldStop(E result); + } + //where private EnumSet deferredCheckerTags = EnumSet.of(LAMBDA, REFERENCE, PARENS, TYPECAST, diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Enter.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Enter.java index bd189b3b696..65df77a2cc5 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/comp/Enter.java +++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Enter.java @@ -96,7 +96,6 @@ public class Enter extends JCTree.Visitor { Symtab syms; Check chk; TreeMaker make; - ClassReader reader; Annotate annotate; MemberEnter memberEnter; Types types; @@ -118,7 +117,6 @@ public class Enter extends JCTree.Visitor { context.put(enterKey, this); log = Log.instance(context); - reader = ClassReader.instance(context); make = TreeMaker.instance(context); syms = Symtab.instance(context); chk = Check.instance(context); diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Flow.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Flow.java index ba2bdc89e20..a9e13874512 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/comp/Flow.java +++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Flow.java @@ -231,7 +231,8 @@ public class Flow { } } - public List analyzeLambdaThrownTypes(Env env, JCLambda that, TreeMaker make) { + public List analyzeLambdaThrownTypes(final Env env, + JCLambda that, TreeMaker make) { //we need to disable diagnostics temporarily; the problem is that if //a lambda expression contains e.g. an unreachable statement, an error //message will be reported and will cause compilation to skip the flow analyis @@ -239,7 +240,13 @@ public class Flow { //related errors, which will allow for more errors to be detected Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log); try { - new AssignAnalyzer(log, syms, lint, names, enforceThisDotInit).analyzeTree(env); + new AssignAnalyzer(log, syms, lint, names, enforceThisDotInit) { + @Override + protected boolean trackable(VarSymbol sym) { + return !env.info.scope.includes(sym) && + sym.owner.kind == MTH; + } + }.analyzeTree(env); LambdaFlowAnalyzer flowAnalyzer = new LambdaFlowAnalyzer(); flowAnalyzer.analyzeTree(env, that, make); return flowAnalyzer.inferredThrownTypes; diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Lower.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Lower.java index bf3e3c122d4..5bffdebdca7 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/comp/Lower.java +++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Lower.java @@ -67,25 +67,24 @@ public class Lower extends TreeTranslator { return instance; } - private Names names; - private Log log; - private Symtab syms; - private Resolve rs; - private Check chk; - private Attr attr; + private final Names names; + private final Log log; + private final Symtab syms; + private final Resolve rs; + private final Check chk; + private final Attr attr; private TreeMaker make; private DiagnosticPosition make_pos; - private ClassWriter writer; - private ClassReader reader; - private ConstFold cfolder; - private Target target; - private Source source; - private boolean allowEnums; + private final ClassWriter writer; + private final ConstFold cfolder; + private final Target target; + private final Source source; + private final boolean allowEnums; private final Name dollarAssertionsDisabled; private final Name classDollar; - private Types types; - private boolean debugLower; - private PkgInfo pkginfoOpt; + private final Types types; + private final boolean debugLower; + private final PkgInfo pkginfoOpt; protected Lower(Context context) { context.put(lowerKey, this); @@ -97,7 +96,6 @@ public class Lower extends TreeTranslator { attr = Attr.instance(context); make = TreeMaker.instance(context); writer = ClassWriter.instance(context); - reader = ClassReader.instance(context); cfolder = ConstFold.instance(context); target = Target.instance(context); source = Source.instance(context); @@ -3524,7 +3522,7 @@ public class Lower extends TreeTranslator { private void visitIterableForeachLoop(JCEnhancedForLoop tree) { make_at(tree.expr.pos()); Type iteratorTarget = syms.objectType; - Type iterableType = types.asSuper(types.upperBound(tree.expr.type), + Type iterableType = types.asSuper(types.cvarUpperBound(tree.expr.type), syms.iterableType.tsym); if (iterableType.getTypeArguments().nonEmpty()) iteratorTarget = types.erasure(iterableType.getTypeArguments().head); @@ -3558,7 +3556,7 @@ public class Lower extends TreeTranslator { List.nil()); JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next)); if (tree.var.type.isPrimitive()) - vardefinit = make.TypeCast(types.upperBound(iteratorTarget), vardefinit); + vardefinit = make.TypeCast(types.cvarUpperBound(iteratorTarget), vardefinit); else vardefinit = make.TypeCast(tree.var.type, vardefinit); JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods, diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/MemberEnter.java b/langtools/src/share/classes/com/sun/tools/javac/comp/MemberEnter.java index ab6e894b739..4fddfb10f85 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/comp/MemberEnter.java +++ b/langtools/src/share/classes/com/sun/tools/javac/comp/MemberEnter.java @@ -25,10 +25,7 @@ package com.sun.tools.javac.comp; -import java.util.HashMap; import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; import java.util.Set; import javax.tools.JavaFileObject; @@ -49,6 +46,7 @@ import static com.sun.tools.javac.code.TypeTag.CLASS; import static com.sun.tools.javac.code.TypeTag.ERROR; import static com.sun.tools.javac.code.TypeTag.TYPEVAR; import static com.sun.tools.javac.tree.JCTree.Tag.*; + import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; @@ -75,7 +73,6 @@ public class MemberEnter extends JCTree.Visitor implements Completer { private final Attr attr; private final Symtab syms; private final TreeMaker make; - private final ClassReader reader; private final Todo todo; private final Annotate annotate; private final TypeAnnotations typeAnnotations; @@ -102,7 +99,6 @@ public class MemberEnter extends JCTree.Visitor implements Completer { attr = Attr.instance(context); syms = Symtab.instance(context); make = TreeMaker.instance(context); - reader = ClassReader.instance(context); todo = Todo.instance(context); annotate = Annotate.instance(context); typeAnnotations = TypeAnnotations.instance(context); diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java index dc79bfd780a..fffe05c55a0 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java +++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java @@ -87,7 +87,7 @@ public class Resolve { DeferredAttr deferredAttr; Check chk; Infer infer; - ClassReader reader; + ClassFinder finder; TreeInfo treeinfo; Types types; JCDiagnostic.Factory diags; @@ -121,7 +121,7 @@ public class Resolve { deferredAttr = DeferredAttr.instance(context); chk = Check.instance(context); infer = Infer.instance(context); - reader = ClassReader.instance(context); + finder = ClassFinder.instance(context); treeinfo = TreeInfo.instance(context); types = Types.instance(context); diags = JCDiagnostic.Factory.instance(context); @@ -347,7 +347,7 @@ public class Resolve { boolean isAccessible(Env env, Type t, boolean checkInner) { return (t.hasTag(ARRAY)) - ? isAccessible(env, types.upperBound(types.elemtype(t))) + ? isAccessible(env, types.cvarUpperBound(types.elemtype(t))) : isAccessible(env, t.tsym, checkInner); } @@ -1014,7 +1014,7 @@ public class Resolve { */ private Type U(Type found) { return found == pt ? - found : types.upperBound(found); + found : types.cvarUpperBound(found); } @Override @@ -1886,9 +1886,9 @@ public class Resolve { */ Symbol loadClass(Env env, Name name) { try { - ClassSymbol c = reader.loadClass(name); + ClassSymbol c = finder.loadClass(name); return isAccessible(env, c) ? c : new AccessError(c); - } catch (ClassReader.BadClassFile err) { + } catch (ClassFinder.BadClassFile err) { throw err; } catch (CompletionFailure ex) { return typeNotFound; diff --git a/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassFile.java b/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassFile.java index e1ff3ac274e..60f12fc4784 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassFile.java +++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassFile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -108,11 +108,21 @@ public class ClassFile { V50(50, 0), // JDK 1.6: stackmaps V51(51, 0), // JDK 1.7 V52(52, 0); // JDK 1.8: lambda, type annos, param names + // JDK9 still marked as V52 // V53(53, 0); // JDK 1.9 + Version(int major, int minor) { this.major = major; this.minor = minor; } public final int major, minor; + + private static final Version MIN = values()[0]; + /** Return the least version supported, MIN */ + public static Version MIN() { return MIN; } + + private static final Version MAX = values()[values().length-1]; + /** Return the largest version supported, MAX */ + public static Version MAX() { return MAX; } } diff --git a/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java b/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java index ed560d52355..0a585735ba7 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java +++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java @@ -35,13 +35,8 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import javax.lang.model.SourceVersion; import javax.tools.JavaFileObject; import javax.tools.JavaFileManager; -import javax.tools.JavaFileManager.Location; -import javax.tools.StandardJavaFileManager; - -import static javax.tools.StandardLocation.*; import com.sun.tools.javac.comp.Annotate; import com.sun.tools.javac.code.*; @@ -119,23 +114,6 @@ public class ClassReader { */ public boolean saveParameterNames; - /** - * Switch: cache completion failures unless -XDdev is used - */ - private boolean cacheCompletionFailure; - - /** - * Switch: prefer source files instead of newer when both source - * and class are available - **/ - public boolean preferSource; - - /** - * Switch: Search classpath and sourcepath for classes before the - * bootclasspath - */ - public boolean userPathsFirst; - /** * The currently selected profile. */ @@ -153,10 +131,6 @@ public class ClassReader { /** The name table. */ final Names names; - /** Force a completion failure on this name - */ - final Name completionFailureName; - /** Access to files */ private final JavaFileManager fileManager; @@ -165,12 +139,6 @@ public class ClassReader { */ JCDiagnostic.Factory diagFactory; - /** Can be reassigned from outside: - * the completer to be used for ".java" files. If this remains unassigned - * ".java" files will not be loaded. - */ - public SourceCompleter sourceCompleter = null; - /** The current scope where type variables are entered. */ protected Scope typevars; @@ -227,20 +195,6 @@ public class ClassReader { */ Set warnedAttrs = new HashSet<>(); - /** - * Completer that delegates to the complete-method of this class. - */ - private final Completer thisCompleter = new Completer() { - @Override - public void complete(Symbol sym) throws CompletionFailure { - ClassReader.this.complete(sym); - } - }; - - public Completer getCompleter() { - return thisCompleter; - } - /** Get the ClassReader instance for this invocation. */ public static ClassReader instance(Context context) { ClassReader instance = context.get(classReaderKey); @@ -274,17 +228,9 @@ public class ClassReader { allowSimplifiedVarargs = source.allowSimplifiedVarargs(); saveParameterNames = options.isSet("save-parameter-names"); - cacheCompletionFailure = options.isUnset("dev"); - preferSource = "source".equals(options.get("-Xprefer")); - userPathsFirst = options.isSet(XXUSERPATHSFIRST); profile = Profile.instance(context); - completionFailureName = - options.isSet("failcomplete") - ? names.fromString(options.get("failcomplete")) - : null; - typevars = new Scope(syms.noSymbol); lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE); @@ -305,26 +251,12 @@ public class ClassReader { * Error Diagnoses ***********************************************************************/ - - public class BadClassFile extends CompletionFailure { - private static final long serialVersionUID = 0; - - public BadClassFile(TypeSymbol sym, JavaFileObject file, JCDiagnostic diag) { - super(sym, createBadClassFileDiagnostic(file, diag)); - } - } - // where - private JCDiagnostic createBadClassFileDiagnostic(JavaFileObject file, JCDiagnostic diag) { - String key = (file.getKind() == JavaFileObject.Kind.SOURCE - ? "bad.source.file.header" : "bad.class.file.header"); - return diagFactory.fragment(key, file, diag); - } - - public BadClassFile badClassFile(String key, Object... args) { - return new BadClassFile ( + public ClassFinder.BadClassFile badClassFile(String key, Object... args) { + return new ClassFinder.BadClassFile ( currentOwner.enclClass(), currentClassFile, - diagFactory.fragment(key, args)); + diagFactory.fragment(key, args), + diagFactory); } /************************************************************************ @@ -1501,7 +1433,7 @@ public class ClassReader { int tag = nextByte(); // TargetType tag is a byte if (!TargetType.isValidTargetTypeValue(tag)) - throw this.badClassFile("bad.type.annotation.value", String.format("0x%02X", tag)); + throw badClassFile("bad.type.annotation.value", String.format("0x%02X", tag)); TargetType type = TargetType.fromTargetTypeValue(tag); @@ -2080,8 +2012,8 @@ public class ClassReader { Type type = readType(nextChar()); if (currentOwner.isInterface() && (flags & ABSTRACT) == 0 && !name.equals(names.clinit)) { - if (majorVersion > Target.JDK1_8.majorVersion || - (majorVersion == Target.JDK1_8.majorVersion && minorVersion >= Target.JDK1_8.minorVersion)) { + if (majorVersion > Version.V52.major || + (majorVersion == Version.V52.major && minorVersion >= Version.V52.minor)) { if ((flags & STATIC) == 0) { currentOwner.flags_field |= DEFAULT; flags |= DEFAULT | ABSTRACT; @@ -2353,20 +2285,20 @@ public class ClassReader { } } - /** Read a class file. + /** Read a class definition from the bytes in buf. */ - private void readClassFile(ClassSymbol c) throws IOException { + private void readClassBuffer(ClassSymbol c) throws IOException { int magic = nextInt(); if (magic != JAVA_MAGIC) throw badClassFile("illegal.start.of.class.file"); minorVersion = nextChar(); majorVersion = nextChar(); - int maxMajor = Target.MAX().majorVersion; - int maxMinor = Target.MAX().minorVersion; + int maxMajor = Version.MAX().major; + int maxMinor = Version.MAX().minor; if (majorVersion > maxMajor || majorVersion * 1000 + minorVersion < - Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion) + Version.MIN().major * 1000 + Version.MIN().minor) { if (majorVersion == (maxMajor + 1)) log.warning("big.major.version", @@ -2395,162 +2327,39 @@ public class ClassReader { readClass(c); } -/************************************************************************ - * Adjusting flags - ***********************************************************************/ - - long adjustFieldFlags(long flags) { - return flags; - } - long adjustMethodFlags(long flags) { - if ((flags & ACC_BRIDGE) != 0) { - flags &= ~ACC_BRIDGE; - flags |= BRIDGE; - if (!allowGenerics) - flags &= ~SYNTHETIC; - } - if ((flags & ACC_VARARGS) != 0) { - flags &= ~ACC_VARARGS; - flags |= VARARGS; - } - return flags; - } - long adjustClassFlags(long flags) { - return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded - } - -/************************************************************************ - * Loading Classes - ***********************************************************************/ - - /** Completion for classes to be loaded. Before a class is loaded - * we make sure its enclosing class (if any) is loaded. - */ - private void complete(Symbol sym) throws CompletionFailure { - if (sym.kind == TYP) { - ClassSymbol c = (ClassSymbol)sym; - c.members_field = new Scope.ErrorScope(c); // make sure it's always defined - annotate.enterStart(); - try { - completeOwners(c.owner); - completeEnclosing(c); - } finally { - // The flush needs to happen only after annotations - // are filled in. - annotate.enterDoneWithoutFlush(); - } - fillIn(c); - } else if (sym.kind == PCK) { - PackageSymbol p = (PackageSymbol)sym; - try { - fillIn(p); - } catch (IOException ex) { - throw new CompletionFailure(sym, ex.getLocalizedMessage()).initCause(ex); - } - } - if (!filling) - annotate.flush(); // finish attaching annotations - } - - /** complete up through the enclosing package. */ - private void completeOwners(Symbol o) { - if (o.kind != PCK) completeOwners(o.owner); - o.complete(); - } - - /** - * Tries to complete lexically enclosing classes if c looks like a - * nested class. This is similar to completeOwners but handles - * the situation when a nested class is accessed directly as it is - * possible with the Tree API or javax.lang.model.*. - */ - private void completeEnclosing(ClassSymbol c) { - if (c.owner.kind == PCK) { - Symbol owner = c.owner; - for (Name name : Convert.enclosingCandidates(Convert.shortName(c.name))) { - Symbol encl = owner.members().lookup(name).sym; - if (encl == null) - encl = syms.classes.get(TypeSymbol.formFlatName(name, owner)); - if (encl != null) - encl.complete(); - } - } - } - - /** We can only read a single class file at a time; this - * flag keeps track of when we are currently reading a class - * file. - */ - private boolean filling = false; - - /** Fill in definition of class `c' from corresponding class or - * source file. - */ - private void fillIn(ClassSymbol c) { - if (completionFailureName == c.fullname) { - throw new CompletionFailure(c, "user-selected completion failure by class name"); - } + public void readClassFile(ClassSymbol c) { currentOwner = c; + currentClassFile = c.classfile; warnedAttrs.clear(); - JavaFileObject classfile = c.classfile; - if (classfile != null) { - JavaFileObject previousClassFile = currentClassFile; - try { - if (filling) { - Assert.error("Filling " + classfile.toUri() + " during " + previousClassFile); - } - currentClassFile = classfile; - if (verbose) { - log.printVerbose("loading", currentClassFile.toString()); - } - if (classfile.getKind() == JavaFileObject.Kind.CLASS) { - filling = true; - try { - bp = 0; - buf = readInputStream(buf, classfile.openInputStream()); - readClassFile(c); - if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) { - List missing = missingTypeVariables; - List found = foundTypeVariables; - missingTypeVariables = List.nil(); - foundTypeVariables = List.nil(); - filling = false; - ClassType ct = (ClassType)currentOwner.type; - ct.supertype_field = - types.subst(ct.supertype_field, missing, found); - ct.interfaces_field = - types.subst(ct.interfaces_field, missing, found); - } else if (missingTypeVariables.isEmpty() != - foundTypeVariables.isEmpty()) { - Name name = missingTypeVariables.head.tsym.name; - throw badClassFile("undecl.type.var", name); - } - } finally { - missingTypeVariables = List.nil(); - foundTypeVariables = List.nil(); - filling = false; - } - } else { - if (sourceCompleter != null) { - sourceCompleter.complete(c); - } else { - throw new IllegalStateException("Source completer required to read " - + classfile.toUri()); - } - } - return; - } catch (IOException ex) { - throw badClassFile("unable.to.access.file", ex.getMessage()); - } catch (ArrayIndexOutOfBoundsException ex) { - throw badClassFile("bad.class.file", c.flatname); - } finally { - currentClassFile = previousClassFile; + filling = true; + try { + bp = 0; + buf = readInputStream(buf, c.classfile.openInputStream()); + readClassBuffer(c); + if (!missingTypeVariables.isEmpty() && !foundTypeVariables.isEmpty()) { + List missing = missingTypeVariables; + List found = foundTypeVariables; + missingTypeVariables = List.nil(); + foundTypeVariables = List.nil(); + filling = false; + ClassType ct = (ClassType)currentOwner.type; + ct.supertype_field = + types.subst(ct.supertype_field, missing, found); + ct.interfaces_field = + types.subst(ct.interfaces_field, missing, found); + } else if (missingTypeVariables.isEmpty() != + foundTypeVariables.isEmpty()) { + Name name = missingTypeVariables.head.tsym.name; + throw badClassFile("undecl.type.var", name); } - } else { - JCDiagnostic diag = - diagFactory.fragment("class.file.not.found", c.flatname); - throw - newCompletionFailure(c, diag); + } catch (IOException ex) { + throw badClassFile("unable.to.access.file", ex.getMessage()); + } catch (ArrayIndexOutOfBoundsException ex) { + throw badClassFile("bad.class.file", c.flatname); + } finally { + missingTypeVariables = List.nil(); + foundTypeVariables = List.nil(); + filling = false; } } // where @@ -2590,253 +2399,39 @@ public class ClassReader { } return buf; } - /** Static factory for CompletionFailure objects. - * In practice, only one can be used at a time, so we share one - * to reduce the expense of allocating new exception objects. - */ - private CompletionFailure newCompletionFailure(TypeSymbol c, - JCDiagnostic diag) { - if (!cacheCompletionFailure) { - // log.warning("proc.messager", - // Log.getLocalizedString("class.file.not.found", c.flatname)); - // c.debug.printStackTrace(); - return new CompletionFailure(c, diag); - } else { - CompletionFailure result = cachedCompletionFailure; - result.sym = c; - result.diag = diag; - return result; - } - } - private CompletionFailure cachedCompletionFailure = - new CompletionFailure(null, (JCDiagnostic) null); - { - cachedCompletionFailure.setStackTrace(new StackTraceElement[0]); - } - - /** Load a toplevel class with given fully qualified name - * The class is entered into `classes' only if load was successful. + /** We can only read a single class file at a time; this + * flag keeps track of when we are currently reading a class + * file. */ - public ClassSymbol loadClass(Name flatname) throws CompletionFailure { - boolean absent = syms.classes.get(flatname) == null; - ClassSymbol c = syms.enterClass(flatname); - if (c.members_field == null && c.completer != null) { - try { - c.complete(); - } catch (CompletionFailure ex) { - if (absent) syms.classes.remove(flatname); - throw ex; - } - } - return c; - } + public boolean filling = false; /************************************************************************ - * Loading Packages + * Adjusting flags ***********************************************************************/ - /** Include class corresponding to given class file in package, - * unless (1) we already have one the same kind (.class or .java), or - * (2) we have one of the other kind, and the given class file - * is older. - */ - protected void includeClassFile(PackageSymbol p, JavaFileObject file) { - if ((p.flags_field & EXISTS) == 0) - for (Symbol q = p; q != null && q.kind == PCK; q = q.owner) - q.flags_field |= EXISTS; - JavaFileObject.Kind kind = file.getKind(); - int seen; - if (kind == JavaFileObject.Kind.CLASS) - seen = CLASS_SEEN; - else - seen = SOURCE_SEEN; - String binaryName = fileManager.inferBinaryName(currentLoc, file); - int lastDot = binaryName.lastIndexOf("."); - Name classname = names.fromString(binaryName.substring(lastDot + 1)); - boolean isPkgInfo = classname == names.package_info; - ClassSymbol c = isPkgInfo - ? p.package_info - : (ClassSymbol) p.members_field.lookup(classname).sym; - if (c == null) { - c = syms.enterClass(classname, p); - if (c.classfile == null) // only update the file if's it's newly created - c.classfile = file; - if (isPkgInfo) { - p.package_info = c; - } else { - if (c.owner == p) // it might be an inner class - p.members_field.enter(c); - } - } else if (!preferCurrent && c.classfile != null && (c.flags_field & seen) == 0) { - // if c.classfile == null, we are currently compiling this class - // and no further action is necessary. - // if (c.flags_field & seen) != 0, we have already encountered - // a file of the same kind; again no further action is necessary. - if ((c.flags_field & (CLASS_SEEN | SOURCE_SEEN)) != 0) - c.classfile = preferredFileObject(file, c.classfile); + long adjustFieldFlags(long flags) { + return flags; + } + + long adjustMethodFlags(long flags) { + if ((flags & ACC_BRIDGE) != 0) { + flags &= ~ACC_BRIDGE; + flags |= BRIDGE; + if (!allowGenerics) + flags &= ~SYNTHETIC; } - c.flags_field |= seen; - } - - /** Implement policy to choose to derive information from a source - * file or a class file when both are present. May be overridden - * by subclasses. - */ - protected JavaFileObject preferredFileObject(JavaFileObject a, - JavaFileObject b) { - - if (preferSource) - return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b; - else { - long adate = a.getLastModified(); - long bdate = b.getLastModified(); - // 6449326: policy for bad lastModifiedTime in ClassReader - //assert adate >= 0 && bdate >= 0; - return (adate > bdate) ? a : b; + if ((flags & ACC_VARARGS) != 0) { + flags &= ~ACC_VARARGS; + flags |= VARARGS; } + return flags; } - /** - * specifies types of files to be read when filling in a package symbol - */ - protected EnumSet getPackageFileKinds() { - return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE); + long adjustClassFlags(long flags) { + return flags & ~ACC_SUPER; // SUPER and SYNCHRONIZED bits overloaded } - /** - * this is used to support javadoc - */ - protected void extraFileActions(PackageSymbol pack, JavaFileObject fe) { - } - - protected Location currentLoc; // FIXME - - private boolean verbosePath = true; - - // Set to true when the currently selected file should be kept - private boolean preferCurrent; - - /** Load directory of package into members scope. - */ - private void fillIn(PackageSymbol p) throws IOException { - if (p.members_field == null) - p.members_field = new Scope(p); - - preferCurrent = false; - if (userPathsFirst) { - scanUserPaths(p); - preferCurrent = true; - scanPlatformPath(p); - } else { - scanPlatformPath(p); - scanUserPaths(p); - } - verbosePath = false; - } - - /** - * Scans class path and source path for files in given package. - */ - private void scanUserPaths(PackageSymbol p) throws IOException { - Set kinds = getPackageFileKinds(); - - Set classKinds = EnumSet.copyOf(kinds); - classKinds.remove(JavaFileObject.Kind.SOURCE); - boolean wantClassFiles = !classKinds.isEmpty(); - - Set sourceKinds = EnumSet.copyOf(kinds); - sourceKinds.remove(JavaFileObject.Kind.CLASS); - boolean wantSourceFiles = !sourceKinds.isEmpty(); - - boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH); - - if (verbose && verbosePath) { - if (fileManager instanceof StandardJavaFileManager) { - StandardJavaFileManager fm = (StandardJavaFileManager)fileManager; - if (haveSourcePath && wantSourceFiles) { - List path = List.nil(); - for (File file : fm.getLocation(SOURCE_PATH)) { - path = path.prepend(file); - } - log.printVerbose("sourcepath", path.reverse().toString()); - } else if (wantSourceFiles) { - List path = List.nil(); - for (File file : fm.getLocation(CLASS_PATH)) { - path = path.prepend(file); - } - log.printVerbose("sourcepath", path.reverse().toString()); - } - if (wantClassFiles) { - List path = List.nil(); - for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) { - path = path.prepend(file); - } - for (File file : fm.getLocation(CLASS_PATH)) { - path = path.prepend(file); - } - log.printVerbose("classpath", path.reverse().toString()); - } - } - } - - String packageName = p.fullname.toString(); - if (wantSourceFiles && !haveSourcePath) { - fillIn(p, CLASS_PATH, - fileManager.list(CLASS_PATH, - packageName, - kinds, - false)); - } else { - if (wantClassFiles) - fillIn(p, CLASS_PATH, - fileManager.list(CLASS_PATH, - packageName, - classKinds, - false)); - if (wantSourceFiles) - fillIn(p, SOURCE_PATH, - fileManager.list(SOURCE_PATH, - packageName, - sourceKinds, - false)); - } - } - - /** - * Scans platform class path for files in given package. - */ - private void scanPlatformPath(PackageSymbol p) throws IOException { - fillIn(p, PLATFORM_CLASS_PATH, - fileManager.list(PLATFORM_CLASS_PATH, - p.fullname.toString(), - EnumSet.of(JavaFileObject.Kind.CLASS), - false)); - } - // where - private void fillIn(PackageSymbol p, - Location location, - Iterable files) - { - currentLoc = location; - for (JavaFileObject fo : files) { - switch (fo.getKind()) { - case CLASS: - case SOURCE: { - // TODO pass binaryName to includeClassFile - String binaryName = fileManager.inferBinaryName(currentLoc, fo); - String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1); - if (SourceVersion.isIdentifier(simpleName) || - simpleName.equals("package-info")) - includeClassFile(p, fo); - break; - } - default: - extraFileActions(p, fo); - } - } - } - /** Output for "-checkclassfile" option. * @param key The key to look up the correct internationalized string. * @param arg An argument for substitution into the output string. @@ -2845,12 +2440,6 @@ public class ClassReader { log.printLines(key, arg); } - - public interface SourceCompleter { - void complete(ClassSymbol sym) - throws CompletionFailure; - } - /** * A subclass of JavaFileObject for the sourcefile attribute found in a classfile. * The attribute is only the last component of the original filename, so is unlikely diff --git a/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java b/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java index 5580d06831f..d86644d864b 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java +++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java @@ -459,11 +459,11 @@ public class ClassWriter extends ClassFile { poolbuf.appendChar(pool.put(names.fromString((String)value))); } else if (value instanceof UniqueType) { Type type = ((UniqueType)value).type; - if (type instanceof MethodType) { + if (type.hasTag(METHOD)) { poolbuf.appendByte(CONSTANT_MethodType); poolbuf.appendChar(pool.put(typeSig((MethodType)type))); } else { - if (type.hasTag(CLASS)) enterInner((ClassSymbol)type.tsym); + Assert.check(type.hasTag(ARRAY)); poolbuf.appendByte(CONSTANT_Class); poolbuf.appendChar(pool.put(xClassName(type))); } diff --git a/langtools/src/share/classes/com/sun/tools/javac/jvm/Code.java b/langtools/src/share/classes/com/sun/tools/javac/jvm/Code.java index 8f28fa0550e..b933b4632b6 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/jvm/Code.java +++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/Code.java @@ -1925,6 +1925,13 @@ public class Code { return aliveRanges.isEmpty() ? null : aliveRanges.get(aliveRanges.size() - 1); } + void removeLastRange() { + Range lastRange = lastRange(); + if (lastRange != null) { + aliveRanges.remove(lastRange); + } + } + @Override public String toString() { if (aliveRanges == null) { @@ -1955,9 +1962,7 @@ public class Code { } } } else { - if (!aliveRanges.isEmpty()) { - aliveRanges.remove(aliveRanges.size() - 1); - } + removeLastRange(); } } @@ -1965,16 +1970,14 @@ public class Code { if (aliveRanges.isEmpty()) { return false; } - Range range = lastRange(); - return range.length == Character.MAX_VALUE; + return lastRange().length == Character.MAX_VALUE; } public boolean isLastRangeInitialized() { if (aliveRanges.isEmpty()) { return false; } - Range range = lastRange(); - return range.start_pc != Character.MAX_VALUE; + return lastRange().start_pc != Character.MAX_VALUE; } public Range getWidestRange() { @@ -2095,7 +2098,7 @@ public class Code { v.closeRange(length); putVar(v); } else { - v.lastRange().start_pc = Character.MAX_VALUE; + v.removeLastRange(); } } } diff --git a/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java b/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java index 943fbb58d62..37050775fb8 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java +++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java @@ -1800,8 +1800,7 @@ public class Gen extends JCTree.Visitor { genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET); thenExit = code.branch(goto_); if (varDebugInfo && lvtRanges.containsKey(code.meth, tree.thenpart)) { - code.closeAliveRanges(tree.thenpart, - thenExit != null && tree.elsepart == null ? thenExit.pc : code.cp); + code.closeAliveRanges(tree.thenpart, code.cp); } } if (elseChain != null) { diff --git a/langtools/src/share/classes/com/sun/tools/javac/jvm/Pool.java b/langtools/src/share/classes/com/sun/tools/javac/jvm/Pool.java index cef21cf52e1..9c9a93df143 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/jvm/Pool.java +++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/Pool.java @@ -28,6 +28,7 @@ package com.sun.tools.javac.jvm; import com.sun.tools.javac.code.Kinds; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.*; +import com.sun.tools.javac.code.TypeTag; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.code.Types.UniqueType; @@ -127,7 +128,14 @@ public class Pool { } else if (o instanceof VarSymbol) { return new Variable((VarSymbol)o, types); } else if (o instanceof Type) { - return new UniqueType((Type)o, types); + Type t = (Type)o; + // ClassRefs can come from ClassSymbols or from Types. + // Return the symbol for these types to avoid duplicates + // in the constant pool + if (t.hasTag(TypeTag.CLASS)) + return t.tsym; + else + return new UniqueType(t, types); } else { return o; } diff --git a/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java b/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java index 6c7ccc11ffa..ff8ff35581a 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java +++ b/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java @@ -219,6 +219,10 @@ public class JavaCompiler { */ protected TreeMaker make; + /** The class finder. + */ + protected ClassFinder finder; + /** The class reader. */ protected ClassReader reader; @@ -296,13 +300,13 @@ public class JavaCompiler { protected MultiTaskListener taskListener; /** - * SourceCompleter that delegates to the complete-method of this class. + * SourceCompleter that delegates to the readSourceFile method of this class. */ - protected final ClassReader.SourceCompleter thisCompleter = - new ClassReader.SourceCompleter() { + protected final Symbol.Completer sourceCompleter = + new Symbol.Completer() { @Override - public void complete(ClassSymbol sym) throws CompletionFailure { - JavaCompiler.this.complete(sym); + public void complete(Symbol sym) throws CompletionFailure { + readSourceFile((ClassSymbol) sym); } }; @@ -338,6 +342,7 @@ public class JavaCompiler { names = Names.instance(context); log = Log.instance(context); diagFactory = JCDiagnostic.Factory.instance(context); + finder = ClassFinder.instance(context); reader = ClassReader.instance(context); make = TreeMaker.instance(context); writer = ClassWriter.instance(context); @@ -355,7 +360,7 @@ public class JavaCompiler { } catch (CompletionFailure ex) { // inlined Check.completionError as it is not initialized yet log.error("cant.access", ex.sym, ex.getDetailValue()); - if (ex instanceof ClassReader.BadClassFile) + if (ex instanceof ClassFinder.BadClassFile) throw new Abort(); } source = Source.instance(context); @@ -370,7 +375,7 @@ public class JavaCompiler { types = Types.instance(context); taskListener = MultiTaskListener.instance(context); - reader.sourceCompleter = thisCompleter; + finder.sourceCompleter = sourceCompleter; options = Options.instance(context); @@ -663,7 +668,7 @@ public class JavaCompiler { public Symbol resolveBinaryNameOrIdent(String name) { try { Name flatname = names.fromString(name.replace("/", ".")); - return reader.loadClass(flatname); + return finder.loadClass(flatname); } catch (CompletionFailure ignore) { return resolveIdent(name); } @@ -737,22 +742,20 @@ public class JavaCompiler { return null; } - /** Complete compiling a source file that has been accessed - * by the class file reader. + /** Compile a source file that has been accessed by the class finder. * @param c The class the source file of which needs to be compiled. */ - public void complete(ClassSymbol c) throws CompletionFailure { - complete(null, c); + private void readSourceFile(ClassSymbol c) throws CompletionFailure { + readSourceFile(null, c); } - /** Complete a ClassSymbol from source, optionally using the given compilation unit as + /** Compile a ClassSymbol from source, optionally using the given compilation unit as * the source tree. - * @param tree the compilation unit int which the given ClassSymbol resides, + * @param tree the compilation unit in which the given ClassSymbol resides, * or null if should be parsed from source * @param c the ClassSymbol to complete */ - public void complete(JCCompilationUnit tree, ClassSymbol c) throws CompletionFailure { -// System.err.println("completing " + c);//DEBUG + public void readSourceFile(JCCompilationUnit tree, ClassSymbol c) throws CompletionFailure { if (completionFailureName == c.fullname) { throw new CompletionFailure(c, "user-selected completion failure by class name"); } @@ -791,13 +794,13 @@ public class JavaCompiler { JCDiagnostic diag = diagFactory.fragment("file.does.not.contain.package", c.location()); - throw reader.new BadClassFile(c, filename, diag); + throw new ClassFinder.BadClassFile(c, filename, diag, diagFactory); } } else { JCDiagnostic diag = diagFactory.fragment("file.doesnt.contain.class", c.getQualifiedName()); - throw reader.new BadClassFile(c, filename, diag); + throw new ClassFinder.BadClassFile(c, filename, diag, diagFactory); } } @@ -1663,6 +1666,7 @@ public class JavaCompiler { */ public void close() { rootClasses = null; + finder = null; reader = null; make = null; writer = null; diff --git a/langtools/src/share/classes/com/sun/tools/javac/processing/JavacProcessingEnvironment.java b/langtools/src/share/classes/com/sun/tools/javac/processing/JavacProcessingEnvironment.java index 5ffe456db60..4e3be1145b7 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/processing/JavacProcessingEnvironment.java +++ b/langtools/src/share/classes/com/sun/tools/javac/processing/JavacProcessingEnvironment.java @@ -54,8 +54,6 @@ import com.sun.tools.javac.comp.Check; import com.sun.tools.javac.comp.Enter; import com.sun.tools.javac.comp.Env; import com.sun.tools.javac.file.JavacFileManager; -import com.sun.tools.javac.jvm.*; -import com.sun.tools.javac.jvm.ClassReader.BadClassFile; import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.model.JavacElements; import com.sun.tools.javac.model.JavacTypes; @@ -203,7 +201,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea symtab = Symtab.instance(context); names = Names.instance(context); enter = Enter.instance(context); - initialCompleter = ClassReader.instance(context).getCompleter(); + initialCompleter = ClassFinder.instance(context).getCompleter(); chk = Check.instance(context); initProcessorClassLoader(); } @@ -799,7 +797,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea RoundEnvironment renv) { try { return proc.process(tes, renv); - } catch (BadClassFile ex) { + } catch (ClassFinder.BadClassFile ex) { log.error("proc.cant.access.1", ex.sym, ex.getDetailValue()); return false; } catch (CompletionFailure ex) { @@ -1308,7 +1306,7 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea } @Override public void complete(Symbol sym) throws CompletionFailure { - compiler.complete(topLevel, (ClassSymbol) sym); + compiler.readSourceFile(topLevel, (ClassSymbol) sym); } } diff --git a/langtools/src/share/classes/com/sun/tools/javac/util/Names.java b/langtools/src/share/classes/com/sun/tools/javac/util/Names.java index 57058c99340..af96c77b066 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/util/Names.java +++ b/langtools/src/share/classes/com/sun/tools/javac/util/Names.java @@ -317,9 +317,9 @@ public class Names { protected Name.Table createTable(Options options) { boolean useUnsharedTable = options.isSet("useUnsharedTable"); if (useUnsharedTable) - return new UnsharedNameTable(this); + return UnsharedNameTable.create(this); else - return new SharedNameTable(this); + return SharedNameTable.create(this); } public void dispose() { diff --git a/langtools/src/share/classes/com/sun/tools/javac/util/StringUtils.java b/langtools/src/share/classes/com/sun/tools/javac/util/StringUtils.java index 4f6d36ab03e..b23af8e5f14 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/util/StringUtils.java +++ b/langtools/src/share/classes/com/sun/tools/javac/util/StringUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 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 @@ -26,6 +26,8 @@ package com.sun.tools.javac.util; import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** A collection of utilities for String manipulation. * @@ -50,4 +52,19 @@ public class StringUtils { return source.toUpperCase(Locale.US); } + /**Case insensitive version of {@link String#indexOf(java.lang.String)}. Equivalent to + * {@code text.indexOf(str)}, except the matching is case insensitive. + */ + public static int indexOfIgnoreCase(String text, String str) { + return indexOfIgnoreCase(text, str, 0); + } + + /**Case insensitive version of {@link String#indexOf(java.lang.String, int)}. Equivalent to + * {@code text.indexOf(str, startIndex)}, except the matching is case insensitive. + */ + public static int indexOfIgnoreCase(String text, String str, int startIndex) { + Matcher m = Pattern.compile(Pattern.quote(str), Pattern.CASE_INSENSITIVE).matcher(text); + return m.find(startIndex) ? m.start() : -1; + } + } diff --git a/langtools/src/share/classes/com/sun/tools/javadoc/DocEnv.java b/langtools/src/share/classes/com/sun/tools/javadoc/DocEnv.java index dfe014ca1fc..17a08f958e4 100644 --- a/langtools/src/share/classes/com/sun/tools/javadoc/DocEnv.java +++ b/langtools/src/share/classes/com/sun/tools/javadoc/DocEnv.java @@ -37,11 +37,19 @@ import com.sun.tools.doclint.DocLint; import com.sun.tools.javac.api.BasicJavacTask; import com.sun.tools.javac.code.*; import com.sun.tools.javac.code.Symbol.*; +import com.sun.tools.javac.code.Symbol.ClassSymbol; +import com.sun.tools.javac.code.Symbol.CompletionFailure; +import com.sun.tools.javac.code.Symbol.MethodSymbol; +import com.sun.tools.javac.code.Symbol.PackageSymbol; +import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type.ClassType; import com.sun.tools.javac.comp.Check; +import com.sun.tools.javac.comp.Enter; import com.sun.tools.javac.file.JavacFileManager; import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.JCTree.*; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import com.sun.tools.javac.tree.JCTree.JCPackageDecl; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Names; @@ -71,21 +79,21 @@ public class DocEnv { return instance; } - private Messager messager; - DocLocale doclocale; + private final Messager messager; + /** Predefined symbols known to the compiler. */ - Symtab syms; + final Symtab syms; /** Referenced directly in RootDocImpl. */ - JavadocClassReader reader; + private final ClassFinder finder; /** Javadoc's own version of the compiler's enter phase. */ - JavadocEnter enter; + final Enter enter; /** The name table. */ - Names names; + private Names names; /** The encoding name. */ private String encoding; @@ -139,8 +147,8 @@ public class DocEnv { messager = Messager.instance0(context); syms = Symtab.instance(context); - reader = JavadocClassReader.instance0(context); - enter = JavadocEnter.instance0(context); + finder = JavadocClassFinder.instance(context); + enter = JavadocEnter.instance(context); names = Names.instance(context); externalizableSym = syms.enterClass(names.fromString("java.io.Externalizable")); chk = Check.instance(context); @@ -176,7 +184,7 @@ public class DocEnv { */ public ClassDocImpl loadClass(String name) { try { - ClassSymbol c = reader.loadClass(names.fromString(name)); + ClassSymbol c = finder.loadClass(names.fromString(name)); return getClassDoc(c); } catch (CompletionFailure ex) { chk.completionError(null, ex); diff --git a/langtools/src/share/classes/com/sun/tools/javadoc/JavadocClassReader.java b/langtools/src/share/classes/com/sun/tools/javadoc/JavadocClassFinder.java similarity index 82% rename from langtools/src/share/classes/com/sun/tools/javadoc/JavadocClassReader.java rename to langtools/src/share/classes/com/sun/tools/javadoc/JavadocClassFinder.java index d9a1e7392b4..ecb3659f174 100644 --- a/langtools/src/share/classes/com/sun/tools/javadoc/JavadocClassReader.java +++ b/langtools/src/share/classes/com/sun/tools/javadoc/JavadocClassFinder.java @@ -29,10 +29,10 @@ import java.util.EnumSet; import javax.tools.JavaFileObject; import com.sun.tools.javac.code.Symbol.PackageSymbol; -import com.sun.tools.javac.jvm.ClassReader; +import com.sun.tools.javac.code.ClassFinder; import com.sun.tools.javac.util.Context; -/** Javadoc uses an extended class reader that records package.html entries +/** Javadoc uses an extended class finder that records package.html entries * *

    This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. @@ -41,19 +41,19 @@ import com.sun.tools.javac.util.Context; * * @author Neal Gafter */ -public class JavadocClassReader extends ClassReader { +public class JavadocClassFinder extends ClassFinder { - public static JavadocClassReader instance0(Context context) { - ClassReader instance = context.get(classReaderKey); + public static JavadocClassFinder instance(Context context) { + ClassFinder instance = context.get(classFinderKey); if (instance == null) - instance = new JavadocClassReader(context); - return (JavadocClassReader)instance; + instance = new JavadocClassFinder(context); + return (JavadocClassFinder)instance; } public static void preRegister(Context context) { - context.put(classReaderKey, new Context.Factory() { - public ClassReader make(Context c) { - return new JavadocClassReader(c); + context.put(classFinderKey, new Context.Factory() { + public ClassFinder make(Context c) { + return new JavadocClassFinder(c); } }); } @@ -65,7 +65,7 @@ public class JavadocClassReader extends ClassReader { private EnumSet noSource = EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.HTML); - public JavadocClassReader(Context context) { + public JavadocClassFinder(Context context) { super(context); docenv = DocEnv.instance(context); preferSource = true; diff --git a/langtools/src/share/classes/com/sun/tools/javadoc/JavadocEnter.java b/langtools/src/share/classes/com/sun/tools/javadoc/JavadocEnter.java index 5215edcb894..50386acabe2 100644 --- a/langtools/src/share/classes/com/sun/tools/javadoc/JavadocEnter.java +++ b/langtools/src/share/classes/com/sun/tools/javadoc/JavadocEnter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -48,7 +48,7 @@ import com.sun.tools.javac.util.List; * @author Neal Gafter */ public class JavadocEnter extends Enter { - public static JavadocEnter instance0(Context context) { + public static JavadocEnter instance(Context context) { Enter instance = context.get(enterKey); if (instance == null) instance = new JavadocEnter(context); diff --git a/langtools/src/share/classes/com/sun/tools/javadoc/JavadocTool.java b/langtools/src/share/classes/com/sun/tools/javadoc/JavadocTool.java index 17d12b864a5..3937ff95720 100644 --- a/langtools/src/share/classes/com/sun/tools/javadoc/JavadocTool.java +++ b/langtools/src/share/classes/com/sun/tools/javadoc/JavadocTool.java @@ -33,12 +33,15 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; + import javax.tools.JavaFileManager.Location; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; +import com.sun.tools.javac.code.ClassFinder; import com.sun.tools.javac.code.Symbol.CompletionFailure; +import com.sun.tools.javac.comp.Enter; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; @@ -66,8 +69,8 @@ public class JavadocTool extends com.sun.tools.javac.main.JavaCompiler { DocEnv docenv; final Messager messager; - final JavadocClassReader javadocReader; - final JavadocEnter javadocEnter; + final ClassFinder javadocFinder; + final Enter javadocEnter; final Set uniquefiles; /** @@ -77,8 +80,8 @@ public class JavadocTool extends com.sun.tools.javac.main.JavaCompiler { protected JavadocTool(Context context) { super(context); messager = Messager.instance0(context); - javadocReader = JavadocClassReader.instance0(context); - javadocEnter = JavadocEnter.instance0(context); + javadocFinder = JavadocClassFinder.instance(context); + javadocEnter = JavadocEnter.instance(context); uniquefiles = new HashSet<>(); } @@ -95,8 +98,8 @@ public class JavadocTool extends com.sun.tools.javac.main.JavaCompiler { public static JavadocTool make0(Context context) { Messager messager = null; try { - // force the use of Javadoc's class reader - JavadocClassReader.preRegister(context); + // force the use of Javadoc's class finder + JavadocClassFinder.preRegister(context); // force the use of Javadoc's own enter phase JavadocEnter.preRegister(context); @@ -137,7 +140,8 @@ public class JavadocTool extends com.sun.tools.javac.main.JavaCompiler { docenv.setEncoding(encoding); docenv.docClasses = docClasses; docenv.legacyDoclet = legacyDoclet; - javadocReader.sourceCompleter = docClasses ? null : thisCompleter; + + javadocFinder.sourceCompleter = docClasses ? null : sourceCompleter; ListBuffer names = new ListBuffer<>(); ListBuffer classTrees = new ListBuffer<>(); diff --git a/langtools/test/com/sun/javadoc/testRelativeLinks/TestRelativeLinks.java b/langtools/test/com/sun/javadoc/testRelativeLinks/TestRelativeLinks.java index 8d53c8dc014..34bd4f5fa4f 100644 --- a/langtools/test/com/sun/javadoc/testRelativeLinks/TestRelativeLinks.java +++ b/langtools/test/com/sun/javadoc/testRelativeLinks/TestRelativeLinks.java @@ -23,7 +23,7 @@ /* * @test - * @bug 4460354 8014636 + * @bug 4460354 8014636 8043186 * @summary Test to make sure that relative paths are redirected in the * output so that they are not broken. * @author jamieh diff --git a/langtools/test/com/sun/javadoc/testRelativeLinks/pkg/C.java b/langtools/test/com/sun/javadoc/testRelativeLinks/pkg/C.java index c899eca037b..12af871502e 100644 --- a/langtools/test/com/sun/javadoc/testRelativeLinks/pkg/C.java +++ b/langtools/test/com/sun/javadoc/testRelativeLinks/pkg/C.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -30,7 +30,7 @@ package pkg; public class C { /** - * Here is a relative link in a field: + * Here is a relative link in a field:\u0130 * relative field link. */ public C field = null; diff --git a/langtools/test/com/sun/javadoc/testTopOption/TestTopOption.java b/langtools/test/com/sun/javadoc/testTopOption/TestTopOption.java index 7d173ed24e6..35bf0337a4d 100644 --- a/langtools/test/com/sun/javadoc/testTopOption/TestTopOption.java +++ b/langtools/test/com/sun/javadoc/testTopOption/TestTopOption.java @@ -23,7 +23,7 @@ /* * @test - * @bug 6227616 + * @bug 6227616 8043186 * @summary Test the new -top option. * @author jamieh * @library ../lib @@ -43,7 +43,30 @@ public class TestTopOption extends JavadocTester { javadoc("-overview", testSrc("overview.html"), "-use", "-top", "TOP TEXT", - "-d", "out", + "-d", "out-1", + "-sourcepath", testSrc, + "pkg"); + checkExit(Exit.OK); + + checkTopText( + "pkg/AnnotationType.html", + "pkg/class-use/AnnotationType.html", + "pkg/Cl.html", + "pkg/class-use/Cl.html", + "pkg/package-summary.html", + "pkg/package-use.html", + "overview-summary.html", + "overview-tree.html", + "constant-values.html", + "help-doc.html"); + } + + @Test + void testDocRootRewrite() { + javadoc("-overview", testSrc("overview.html"), + "-use", + "-top", "\u0130{@docroot}TOP TEXT", + "-d", "out-2", "-sourcepath", testSrc, "pkg"); checkExit(Exit.OK); diff --git a/langtools/test/tools/javac/6330997/T6330997.java b/langtools/test/tools/javac/6330997/T6330997.java index 98c76e22828..8995c1b32a1 100644 --- a/langtools/test/tools/javac/6330997/T6330997.java +++ b/langtools/test/tools/javac/6330997/T6330997.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -36,7 +36,7 @@ import java.nio.*; import java.io.*; import java.nio.channels.*; import com.sun.tools.javac.api.JavacTaskImpl; -import com.sun.tools.javac.jvm.ClassReader.BadClassFile; +import com.sun.tools.javac.code.ClassFinder.BadClassFile; import com.sun.tools.javac.main.JavaCompiler; import javax.tools.ToolProvider; diff --git a/langtools/test/tools/javac/MethodParametersTest.java b/langtools/test/tools/javac/MethodParametersTest.java index 515eee34e23..c2570b7bed1 100644 --- a/langtools/test/tools/javac/MethodParametersTest.java +++ b/langtools/test/tools/javac/MethodParametersTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -129,14 +129,14 @@ public class MethodParametersTest { if (out.length() > 0) System.err.println(out); - // Now get the class reader, construct a name for Baz, and load it. - com.sun.tools.javac.jvm.ClassReader cr = - com.sun.tools.javac.jvm.ClassReader.instance(context); + // Now get the class finder, construct a name for Baz, and load it. + com.sun.tools.javac.code.ClassFinder cf = + com.sun.tools.javac.code.ClassFinder.instance(context); Name name = Names.instance(context).fromString(Baz_name); // Now walk down the language model and check the name of the // parameter. - final Element baz = cr.loadClass(name); + final Element baz = cf.loadClass(name); for (Element e : baz.getEnclosedElements()) { if (e instanceof ExecutableElement) { final ExecutableElement ee = (ExecutableElement) e; diff --git a/langtools/test/tools/javac/T6435291/T6435291.java b/langtools/test/tools/javac/T6435291/T6435291.java index d710f9c4fc5..73985a635f2 100644 --- a/langtools/test/tools/javac/T6435291/T6435291.java +++ b/langtools/test/tools/javac/T6435291/T6435291.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -30,7 +30,7 @@ */ import com.sun.tools.javac.api.JavacTaskImpl; -import com.sun.tools.javac.jvm.ClassReader.BadClassFile; +import com.sun.tools.javac.code.ClassFinder.BadClassFile; import com.sun.tools.javac.main.JavaCompiler; import javax.tools.ToolProvider; diff --git a/langtools/test/tools/javac/T8030816/CrashLambdaExpressionWithNonAccessibleIdTest.out b/langtools/test/tools/javac/T8030816/CrashLambdaExpressionWithNonAccessibleIdTest.out index d253b9c660b..3b2266c0b21 100644 --- a/langtools/test/tools/javac/T8030816/CrashLambdaExpressionWithNonAccessibleIdTest.out +++ b/langtools/test/tools/javac/T8030816/CrashLambdaExpressionWithNonAccessibleIdTest.out @@ -1,3 +1,2 @@ -CrashLambdaExpressionWithNonAccessibleIdTest.java:15:35: compiler.err.missing.ret.stmt CrashLambdaExpressionWithNonAccessibleIdTest.java:14:17: compiler.err.cant.resolve.location: kindname.class, A, , , (compiler.misc.location: kindname.class, CrashLambdaExpressionWithNonAccessibleIdTest, null) -2 errors +1 error diff --git a/langtools/test/tools/javac/classfiles/attributes/SourceFile/NoSourceFileAttribute.java b/langtools/test/tools/javac/classfiles/attributes/SourceFile/NoSourceFileAttribute.java index 835f801d209..90321ed2901 100644 --- a/langtools/test/tools/javac/classfiles/attributes/SourceFile/NoSourceFileAttribute.java +++ b/langtools/test/tools/javac/classfiles/attributes/SourceFile/NoSourceFileAttribute.java @@ -24,10 +24,11 @@ /* * @test * @summary sourcefile attribute test for file compiled without debug information. + * @bug 8040129 * @library /tools/javac/lib ../lib * @build SourceFileTestBase TestBase InMemoryFileManager ToolBox * @compile -g:none NoSourceFileAttribute.java - * @run main NoSourceFileAttribute + * @run main NoSourceFileAttribute */ import com.sun.tools.classfile.Attribute; diff --git a/langtools/test/tools/javac/defaultMethods/BadClassfile.java b/langtools/test/tools/javac/defaultMethods/BadClassfile.java index 424d3acf102..28d0dcf6d41 100644 --- a/langtools/test/tools/javac/defaultMethods/BadClassfile.java +++ b/langtools/test/tools/javac/defaultMethods/BadClassfile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 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 @@ -32,8 +32,8 @@ import com.sun.tools.classfile.*; import com.sun.tools.javac.api.JavacTaskImpl; +import com.sun.tools.javac.code.ClassFinder.BadClassFile; import com.sun.tools.javac.code.Symbol; -import com.sun.tools.javac.jvm.ClassReader.BadClassFile; import com.sun.tools.javac.jvm.Target; import com.sun.tools.javac.util.Assert; import com.sun.tools.javac.util.JCDiagnostic; diff --git a/langtools/test/tools/javac/flow/LVTHarness.java b/langtools/test/tools/javac/flow/LVTHarness.java index c679f52f526..7039a626a57 100644 --- a/langtools/test/tools/javac/flow/LVTHarness.java +++ b/langtools/test/tools/javac/flow/LVTHarness.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 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 @@ -23,8 +23,8 @@ /* * @test - * @bug 7047734 8027660 - * @summary The LVT is not generated correctly during some try/catch scenarios; + * @bug 7047734 8027660 8037937 + * @summary The LVT is not generated correctly during some try/catch scenarios * javac crash while creating LVT entry for a local variable defined in * an inner block * @library /tools/javac/lib @@ -120,7 +120,7 @@ public class LVTHarness { for (Map.Entry entry : aliveRangeMap.entrySet()) { if (!seenAliveRanges.contains(entry.getKey())) { error("Redundant @AliveRanges annotation on method " + - entry.getKey().elem); + entry.getKey().elem + " with key " + entry.getKey()); } } } @@ -134,7 +134,7 @@ public class LVTHarness { for (Method method : classFile.methods) { for (ElementKey elementKey: aliveRangeMap.keySet()) { String methodDesc = method.getName(constantPool) + - method.descriptor.getParameterTypes(constantPool); + method.descriptor.getParameterTypes(constantPool).replace(" ", ""); if (methodDesc.equals(elementKey.elem.toString())) { checkMethod(constantPool, method, aliveRangeMap.get(elementKey)); seenAliveRanges.add(elementKey); diff --git a/langtools/test/tools/javac/flow/T8042741/A.java b/langtools/test/tools/javac/flow/T8042741/A.java new file mode 100644 index 00000000000..36deb2d172f --- /dev/null +++ b/langtools/test/tools/javac/flow/T8042741/A.java @@ -0,0 +1,37 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +// str must be at absolute position greater than that of lambda +// expression in PositionTest.java +// padding..........................................................padding +// padding..........................................................padding +// padding..........................................................padding +// padding..........................................................padding +// padding..........................................................padding + +public class A { + public final String str; + { + str = ""; + } +} diff --git a/langtools/test/tools/javac/flow/T8042741/PositionTest.java b/langtools/test/tools/javac/flow/T8042741/PositionTest.java new file mode 100644 index 00000000000..cc0da15e4f5 --- /dev/null +++ b/langtools/test/tools/javac/flow/T8042741/PositionTest.java @@ -0,0 +1,62 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8042741 + * @summary Java 8 compiler throws NullPointerException depending location in source file + * @compile A.java PositionTest.java + */ + +public class PositionTest extends A { + void test(SAM r) throws E { + test(() -> { System.err.println(str); }); + } + interface SAM { + public void run() throws E; + } + void f() { + try { + test(() -> { + test(() -> { + try { + test(() -> { System.err.println(str); }); + System.err.println(str); + } catch (Exception e) {} + System.err.println(str); + }); + System.err.println(str); + }); + } catch (Exception e) { } + } + void g() throws Exception { + test(() -> { + try { + try { + test(() -> { System.err.println(str); }); + } catch (Exception e) {} + System.err.println(str); + } catch (Exception e) {} + System.err.println(str); + }); + } +} diff --git a/langtools/test/tools/javac/flow/tests/TestCaseIfElse.java b/langtools/test/tools/javac/flow/tests/TestCaseIfElse.java index 3e6cc893794..d789853b43a 100644 --- a/langtools/test/tools/javac/flow/tests/TestCaseIfElse.java +++ b/langtools/test/tools/javac/flow/tests/TestCaseIfElse.java @@ -33,7 +33,7 @@ public class TestCaseIfElse { @AliveRange(varName="o", bytecodeStart=10, bytecodeLength=8) @AliveRange(varName="o", bytecodeStart=21, bytecodeLength=9) - void m2(String[] args) { + void m2() { Object o; int i = 5; if (i != 5) { @@ -45,4 +45,19 @@ public class TestCaseIfElse { } o = "finish"; } + + @AliveRange(varName="o", bytecodeStart=11, bytecodeLength=3) + @AliveRange(varName="o", bytecodeStart=17, bytecodeLength=2) + Object m3(boolean cond1, boolean cond2) { + Object o; + if (cond1) { + if (cond2) { + o = "then"; + } else { + o = "else"; + return null; + } + } + return null; + } } diff --git a/langtools/test/tools/javac/inference/EagerReturnTypeResolution/EagerReturnTypeResolutionTesta.java b/langtools/test/tools/javac/generics/inference/EagerReturnTypeResolution/EagerReturnTypeResolutionTesta.java similarity index 100% rename from langtools/test/tools/javac/inference/EagerReturnTypeResolution/EagerReturnTypeResolutionTesta.java rename to langtools/test/tools/javac/generics/inference/EagerReturnTypeResolution/EagerReturnTypeResolutionTesta.java diff --git a/langtools/test/tools/javac/inference/EagerReturnTypeResolution/EagerReturnTypeResolutionTestb.java b/langtools/test/tools/javac/generics/inference/EagerReturnTypeResolution/EagerReturnTypeResolutionTestb.java similarity index 100% rename from langtools/test/tools/javac/inference/EagerReturnTypeResolution/EagerReturnTypeResolutionTestb.java rename to langtools/test/tools/javac/generics/inference/EagerReturnTypeResolution/EagerReturnTypeResolutionTestb.java diff --git a/langtools/test/tools/javac/inference/EagerReturnTypeResolution/EagerReturnTypeResolutionTestb.out b/langtools/test/tools/javac/generics/inference/EagerReturnTypeResolution/EagerReturnTypeResolutionTestb.out similarity index 100% rename from langtools/test/tools/javac/inference/EagerReturnTypeResolution/EagerReturnTypeResolutionTestb.out rename to langtools/test/tools/javac/generics/inference/EagerReturnTypeResolution/EagerReturnTypeResolutionTestb.out diff --git a/langtools/test/tools/javac/inference/EagerReturnTypeResolution/PrimitiveTypeBoxingTest.java b/langtools/test/tools/javac/generics/inference/EagerReturnTypeResolution/PrimitiveTypeBoxingTest.java similarity index 100% rename from langtools/test/tools/javac/inference/EagerReturnTypeResolution/PrimitiveTypeBoxingTest.java rename to langtools/test/tools/javac/generics/inference/EagerReturnTypeResolution/PrimitiveTypeBoxingTest.java diff --git a/langtools/test/tools/javac/inference/EagerReturnTypeResolution/PrimitiveTypeBoxingTest.out b/langtools/test/tools/javac/generics/inference/EagerReturnTypeResolution/PrimitiveTypeBoxingTest.out similarity index 100% rename from langtools/test/tools/javac/inference/EagerReturnTypeResolution/PrimitiveTypeBoxingTest.out rename to langtools/test/tools/javac/generics/inference/EagerReturnTypeResolution/PrimitiveTypeBoxingTest.out diff --git a/langtools/test/tools/javac/jvm/ClassRefDupInConstantPoolTest.java b/langtools/test/tools/javac/jvm/ClassRefDupInConstantPoolTest.java new file mode 100644 index 00000000000..98c7cf8dabb --- /dev/null +++ b/langtools/test/tools/javac/jvm/ClassRefDupInConstantPoolTest.java @@ -0,0 +1,63 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8015927 + * @summary Class reference duplicates in constant pool + * @clean ClassRefDupInConstantPoolTest$Duplicates.class + * @run main ClassRefDupInConstantPoolTest + */ + +import java.util.TreeSet; + +import com.sun.tools.classfile.*; +import com.sun.tools.classfile.ConstantPool.*; + +public class ClassRefDupInConstantPoolTest { + public static void main(String[] args) throws Exception { + ClassFile cls = ClassFile.read(ClassRefDupInConstantPoolTest.class. + getResourceAsStream("ClassRefDupInConstantPoolTest$Duplicates.class")); + ConstantPool pool = cls.constant_pool; + + int duplicates = 0; + TreeSet set = new TreeSet<>(); + for (CPInfo i : pool.entries()) { + if (i.getTag() == ConstantPool.CONSTANT_Class) { + CONSTANT_Class_info ci = (CONSTANT_Class_info)i; + if (!set.add(ci.name_index)) { + duplicates++; + System.out.println("DUPLICATE CLASS REF " + ci.getName()); + } + } + } + if (duplicates > 0) + throw new Exception("Test Failed"); + } + + class Duplicates { + String concat(String s1, String s2) { + return s1 + (s2 == s1 ? " " : s2); + } + } +} diff --git a/langtools/test/tools/javac/lambda/T8031967.java b/langtools/test/tools/javac/lambda/T8031967.java new file mode 100644 index 00000000000..3836ecd0406 --- /dev/null +++ b/langtools/test/tools/javac/lambda/T8031967.java @@ -0,0 +1,137 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8031967 + * @summary Ensure javac can handle very deeply nested chain of method invocations occurring as + * a parameter to other method invocations. + * @run main T8031967 + */ + +import java.io.IOException; +import java.net.URI; +import java.util.Arrays; +import java.util.List; + +import javax.tools.DiagnosticListener; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.ToolProvider; + +import com.sun.source.util.JavacTask; + +public class T8031967 { + + public static void main(String... args) throws IOException { + new T8031967().run(); + } + + final int depth = 50; + + private void run() throws IOException { + runTestCase(true); + runTestCase(false); + } + + private void runTestCase(boolean withErrors) throws IOException { + StringBuilder code = new StringBuilder(); + + code.append("public class Test {\n" + + " private void test() {\n" + + " GroupLayout l = new GroupLayout();\n" + + " l.setHorizontalGroup(\n"); + + gen(code, depth); + code.append(" );\n" + + " }\n"); + if (!withErrors) { + code.append(" class GroupLayout {\n" + + " ParallelGroup createParallelGroup() {return null;}\n" + + " ParallelGroup createParallelGroup(int i) {return null;}\n" + + " ParallelGroup createParallelGroup(int i, int j) {return null;}\n" + + " void setHorizontalGroup(Group g) { }\n" + + " }\n" + + " \n" + + " class Group {\n" + + " Group addGroup(Group g) { return this; }\n" + + " Group addGroup(int i, Group g) { return this; }\n" + + " Group addGap(int i) { return this; }\n" + + " Group addGap(long l) { return this; }\n" + + " Group addGap(int i, int j) { return this; }\n" + + " Group addComponent(Object c) { return this; }\n" + + " Group addComponent(int i, Object c) { return this; }\n" + + " }\n" + + " class ParallelGroup extends Group {\n" + + " Group addGroup(Group g) { return this; }\n" + + " Group addGroup(int i, Group g) { return this; }\n" + + " Group addGap(int i) { return this; }\n" + + " Group addGap(int i, int j) { return this; }\n" + + " Group addComponent(Object c) { return this; }\n" + + " Group addComponent(int i, Object c) { return this; }\n" + + " }\n"); + } + + code.append("}\n"); + + JavaSource source = new JavaSource(code.toString()); + List sourceList = Arrays.asList(source); + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + DiagnosticListener noErrors = (diagnostic) -> { + throw new IllegalStateException("Should not produce errors: " + diagnostic); + }; + JavacTask task = (JavacTask) compiler.getTask(null, null, withErrors ? null : noErrors, + null, null, sourceList); + + task.analyze(); + } + + private void gen(StringBuilder code, int depth) { + code.append("l.createParallelGroup()\n"); + if (depth > 0) { + code.append(".addGroup(\n"); + gen(code, depth - 1); + code.append(")"); + } + + code.append(".addGap(1)\n" + + ".addComponent(new Object())\n" + + ".addGap(1)\n" + + ".addComponent(new Object())"); + } + + class JavaSource extends SimpleJavaFileObject { + + final String code; + public JavaSource(String code) { + super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE); + this.code = code; + } + + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return code; + } + } +} diff --git a/langtools/test/tools/javac/lambda/T8041704/ErrorMessageTest.java b/langtools/test/tools/javac/lambda/T8041704/ErrorMessageTest.java new file mode 100644 index 00000000000..5bd38c79d59 --- /dev/null +++ b/langtools/test/tools/javac/lambda/T8041704/ErrorMessageTest.java @@ -0,0 +1,12 @@ +/** + * @test /nodynamiccopyright/ + * @bug 8041704 + * @summary wrong error message when mixing lambda expression and inner class + * @compile/fail/ref=ErrorMessageTest.out -XDrawDiagnostics ErrorMessageTest.java + */ + +public class ErrorMessageTest { + void f(Runnable r) { + f(() -> { f(new MISSING() { public void run() {} }); }); + } +} diff --git a/langtools/test/tools/javac/lambda/T8041704/ErrorMessageTest.out b/langtools/test/tools/javac/lambda/T8041704/ErrorMessageTest.out new file mode 100644 index 00000000000..bdd25993c86 --- /dev/null +++ b/langtools/test/tools/javac/lambda/T8041704/ErrorMessageTest.out @@ -0,0 +1,2 @@ +ErrorMessageTest.java:10:25: compiler.err.cant.resolve.location: kindname.class, MISSING, , , (compiler.misc.location: kindname.class, ErrorMessageTest, null) +1 error diff --git a/langtools/test/tools/javac/lambda/TargetType23.java b/langtools/test/tools/javac/lambda/TargetType23.java index bac45e9351e..4f20232a3cc 100644 --- a/langtools/test/tools/javac/lambda/TargetType23.java +++ b/langtools/test/tools/javac/lambda/TargetType23.java @@ -1,6 +1,6 @@ /* * @test /nodynamiccopyright/ - * @bug 8003280 + * @bug 8003280 8034223 * @summary Add lambda tests * check case of ambiguous method call with lambda whose body cannot complete normally diff --git a/langtools/test/tools/javac/types/BadSigTest.java b/langtools/test/tools/javac/types/BadSigTest.java new file mode 100644 index 00000000000..14b3ff9cbb0 --- /dev/null +++ b/langtools/test/tools/javac/types/BadSigTest.java @@ -0,0 +1,40 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8037934 + * @summary Javac generates invalid signatures for local types + * @run main BadSigTest + */ + +public class BadSigTest { + void m(){ + class Local1{} + class Local2 extends Local1{} + Local2.class.getTypeParameters(); + } + public static void main(String[] args) { + new BadSigTest().m(); + } +} diff --git a/langtools/test/tools/javac/util/StringUtilsTest.java b/langtools/test/tools/javac/util/StringUtilsTest.java index ec8db20ef77..854a77381b1 100644 --- a/langtools/test/tools/javac/util/StringUtilsTest.java +++ b/langtools/test/tools/javac/util/StringUtilsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 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 @@ -23,7 +23,7 @@ /** * @test - * @bug 8029800 + * @bug 8029800 8043186 * @summary Unit test StringUtils * @run main StringUtilsTest */ @@ -44,12 +44,14 @@ public class StringUtilsTest { assertEquals("\u0131", "I".toLowerCase()); assertEquals("\u0130", "i".toUpperCase()); - //verify the StringUtils does what it should + //verify the StringUtils.toLowerCase/toUpperCase do what they should: assertEquals("i", StringUtils.toLowerCase("I")); assertEquals("I", StringUtils.toUpperCase("i")); - //verify we can use index from indexOf of toLowerCase String in the original: - assertEquals(2, StringUtils.toLowerCase("\u0130\u0130lookFor").indexOf("lookfor")); + //verify StringUtils.caseInsensitiveIndexOf works: + assertEquals(2, StringUtils.indexOfIgnoreCase(" lookFor", "lookfor")); + assertEquals(11, StringUtils.indexOfIgnoreCase(" lookFor LOOKfor", "lookfor", 11)); + assertEquals(2, StringUtils.indexOfIgnoreCase("\u0130\u0130lookFor", "lookfor")); } void assertEquals(String expected, String actual) { diff --git a/make/Jprt.gmk b/make/Jprt.gmk index 75ee37da374..a7f9226d99f 100644 --- a/make/Jprt.gmk +++ b/make/Jprt.gmk @@ -23,8 +23,22 @@ # questions. # -# This file is contains targets utilities needed by JPRT. +# This file contains targets and utilities needed by JPRT. +# Cygpath is only defined when running on Cygwin +ifneq ($(CYGPATH), ) + # If we get JPRT_ARCHIVE_*BUNDLE externally, make sure they have /cygdrive + # style paths + ifdef JPRT_ARCHIVE_BUNDLE + override JPRT_ARCHIVE_BUNDLE := $(shell $(CYGPATH) -u $(JPRT_ARCHIVE_BUNDLE)) + endif + ifdef JPRT_ARCHIVE_INSTALL_BUNDLE + override JPRT_ARCHIVE_INSTALL_BUNDLE := $(shell $(CYGPATH) -u $(JPRT_ARCHIVE_INSTALL_BUNDLE)) + endif +endif + +# When running in JPRT these will be provided. Need defaults so that this makefile +# is valid anyway. ifndef JPRT_ARCHIVE_BUNDLE JPRT_ARCHIVE_BUNDLE=/tmp/jprt_bundles/j2sdk-image.zip endif diff --git a/nashorn/.hgtags b/nashorn/.hgtags index 4eb279cc390..0a256647f7b 100644 --- a/nashorn/.hgtags +++ b/nashorn/.hgtags @@ -247,3 +247,5 @@ b3517e51f40477f10db8bc30a557aa0ea712c274 jdk9-b02 4d60c3292e14aac90dc3b8232496ba4af4254cc3 jdk9-b11 282e9a675e079cc84dbfaa4c10050f08397faab0 jdk9-b12 be4580ae56e2ef0ce521d3f840753eaa83cacf33 jdk9-b13 +806df06b6ac58d3e9c9c6a680dbdd7a6c94ca700 jdk9-b14 +32b66f4661eac52f8b04fb3d7703feb2c96febb7 jdk9-b15 diff --git a/nashorn/make/build.xml b/nashorn/make/build.xml index e8058a32f9b..83cbb91bd4b 100644 --- a/nashorn/make/build.xml +++ b/nashorn/make/build.xml @@ -196,14 +196,16 @@ - - + + - + @@ -211,6 +213,19 @@ + + + + + + + + + + + + @@ -360,6 +375,10 @@ grant codeBase "file:/${basedir}/test/script/markdown.js" { + + + + @@ -376,6 +395,21 @@ grant codeBase "file:/${basedir}/test/script/markdown.js" { + + + + + + + + + + + + + + diff --git a/nashorn/make/project.properties b/nashorn/make/project.properties index 5af728794e2..ba4e57a1003 100644 --- a/nashorn/make/project.properties +++ b/nashorn/make/project.properties @@ -59,6 +59,7 @@ nashorn.api.tests.jar=${build.dir}/nashorn-api-tests.jar # test results directory build.test.results.dir=${build.dir}/test/reports +build.nosecurity.test.results.dir=${build.dir}/test/nosecurity/reports # This directory is removed when the project is cleaned: dist.dir=dist @@ -113,6 +114,7 @@ run.classpath=\ # test scripts to run test.dir=test +test.nosecurity.dir=test/script/nosecurity test.script.dir=test/script test.basic.dir=test/script/basic test.maptests.dir=test/script/maptests @@ -131,8 +133,12 @@ test-sys-prop.test262.suite.dir=${test262.suite.dir} test-sys-prop.es5conform.testcases.dir=${test.external.dir}/ES5Conform/TestCases test-sys-prop.test.basic.dir=${test.basic.dir} +test-sys-prop-no-security.test.dir=${test.dir} +test-sys-prop-no-security.test.js.roots=${test.nosecurity.dir} + # framework root for our script tests test-sys-prop.test.js.framework=${test.script.dir}/assert.js +test-sys-prop-no-security.test.js.framework=${test.script.dir}/assert.js # Control the verbosity of ParserTest test-sys-prop.parsertest.verbose=false @@ -259,7 +265,7 @@ src.dir=src test.src.dir=test/src # -Xmx is used for all tests, -Xms only for octane benchmark -run.test.xmx=3G +run.test.xmx=2G run.test.xms=2G run.test.user.language=tr diff --git a/nashorn/samples/filebrowser.js b/nashorn/samples/filebrowser.js new file mode 100644 index 00000000000..da00553a4ec --- /dev/null +++ b/nashorn/samples/filebrowser.js @@ -0,0 +1,100 @@ +#// Usage: jjs -fx filebrowser.js -- + +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Uses -fx and javafx TreeView to visualize directories +if (!$OPTIONS._fx) { + print("Usage: jjs -fx filebrowser.js -- "); + exit(1); +} + +// Java classes used +var File = Java.type("java.io.File"); +var Files = Java.type("java.nio.file.Files"); + +// check directory argument, if passed +var dir = arguments.length > 0? new File(arguments[0]) : new File("."); +if (! dir.isDirectory()) { + print(dir + " is not a directory!"); + exit(2); +} + +// JavaFX classes used +var FXCollections = Java.type("javafx.collections.FXCollections"); +var Scene = Java.type("javafx.scene.Scene"); +var TreeItem = Java.type("javafx.scene.control.TreeItem"); +var TreeView = Java.type("javafx.scene.control.TreeView"); + +// create a subclass of JavaFX TreeItem class +var LazyTreeItem = Java.extend(TreeItem); + +// lazily filling children of a directory LazyTreeItem +function buildChildren(dir) { + var children = FXCollections.observableArrayList(); + var stream = Files.list(dir.toPath()); + stream.forEach(function(path) { + var file = path.toFile(); + var item = file.isDirectory()? + makeLazyTreeItem(file) : new TreeItem(file.name); + children.add(item); + }); + stream.close(); + return children; +} + +// create an instance LazyTreeItem with override methods +function makeLazyTreeItem(dir) { + var item = new LazyTreeItem(dir.name) { + expanded: false, + isLeaf: function() false, + getChildren: function() { + if (! this.expanded) { + // call super class (TreeItem) method + Java.super(item).getChildren().setAll(buildChildren(dir)); + this.expanded = true; + } + // call super class (TreeItem) method + return Java.super(item).getChildren(); + } + } + return item; +} + +// JavaFX start method +function start(stage) { + stage.title = dir.absolutePath; + var rootItem = makeLazyTreeItem(dir); + rootItem.expanded = true; + var tree = new TreeView(rootItem); + stage.scene = new Scene(tree, 300, 450); + stage.show(); +} diff --git a/nashorn/samples/word_histogram.js b/nashorn/samples/word_histogram.js new file mode 100644 index 00000000000..9c739ea0375 --- /dev/null +++ b/nashorn/samples/word_histogram.js @@ -0,0 +1,53 @@ +#nashorn word histogram of a file + +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * This example demonstrates how to print word histogram + * of a given text file using regex, array and JSON + * functions. + */ + +if (arguments.length < 1) { + print("Usage: jjs -scripting word_histogram.js -- "); + exit(1); +} + +var obj = {}; + +readFully(arguments[0]). + split(/[^\w+]/). + forEach(function(x) + (x in obj? obj[x]++ : obj[x] = 1)); + +print(JSON.stringify(obj)); + diff --git a/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java b/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java index b12553369d4..07f4e8a6864 100644 --- a/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java +++ b/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java @@ -621,6 +621,7 @@ public final class ScriptObjectMirror extends AbstractJSObject implements Bindin /** * Utilitity to convert this script object to the given type. * + * @param destination type to convert to * @param type destination type to convert to * @return converted object */ diff --git a/nashorn/src/jdk/nashorn/api/scripting/package-info.java b/nashorn/src/jdk/nashorn/api/scripting/package-info.java index 6876151e330..f017ba9ef4f 100644 --- a/nashorn/src/jdk/nashorn/api/scripting/package-info.java +++ b/nashorn/src/jdk/nashorn/api/scripting/package-info.java @@ -32,7 +32,8 @@ * ScriptEngine nashornEngine = new ScriptEngineManager().getEngineByName("Nashorn"); * *

    Nashorn script engines implement the optional {@link javax.script.Invocable} and {@link javax.script.Compilable} - * interfaces, allowing for efficient pre-compilation and repeated execution of scripts. See + * interfaces, allowing for efficient pre-compilation and repeated execution of scripts. In addition, + * this package provides nashorn specific extension classes, interfaces and methods. See * {@link jdk.nashorn.api.scripting.NashornScriptEngineFactory} for further details. */ package jdk.nashorn.api.scripting; diff --git a/nashorn/src/jdk/nashorn/internal/ir/annotations/Reference.java b/nashorn/src/jdk/nashorn/internal/ir/annotations/Reference.java index 20c8ffca53b..27f6a697666 100644 --- a/nashorn/src/jdk/nashorn/internal/ir/annotations/Reference.java +++ b/nashorn/src/jdk/nashorn/internal/ir/annotations/Reference.java @@ -32,9 +32,7 @@ import java.lang.annotation.RetentionPolicy; * Reference node in AST, i.e. anything not a copy. Important for * AST traversal and cloning. Cloning currently as a rule uses * existingOrSame for references and otherwise existingOrCopy - *

    */ - @Retention(value=RetentionPolicy.RUNTIME) public @interface Reference { // EMPTY diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java index c8f39fcfaca..48821036d25 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java @@ -61,9 +61,17 @@ public final class Bootstrap { private static final DynamicLinker dynamicLinker; static { final DynamicLinkerFactory factory = new DynamicLinkerFactory(); - factory.setPrioritizedLinkers(new NashornLinker(), new NashornPrimitiveLinker(), new NashornStaticClassLinker(), - new BoundDynamicMethodLinker(), new JavaSuperAdapterLinker(), new JSObjectLinker(), new ReflectionCheckLinker()); - factory.setFallbackLinkers(new NashornBeansLinker(), new NashornBottomLinker()); + final NashornBeansLinker nashornBeansLinker = new NashornBeansLinker(); + final JSObjectLinker jsObjectLinker = new JSObjectLinker(nashornBeansLinker); + factory.setPrioritizedLinkers( + new NashornLinker(), + new NashornPrimitiveLinker(), + new NashornStaticClassLinker(), + new BoundDynamicMethodLinker(), + new JavaSuperAdapterLinker(), + jsObjectLinker, + new ReflectionCheckLinker()); + factory.setFallbackLinkers(nashornBeansLinker, new NashornBottomLinker()); factory.setSyncOnRelink(true); final int relinkThreshold = Options.getIntProperty("nashorn.unstable.relink.threshold", -1); if (relinkThreshold > -1) { diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/JSObjectLinker.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/JSObjectLinker.java index f3c8284be86..52fb46bc5c7 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/linker/JSObjectLinker.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/JSObjectLinker.java @@ -30,6 +30,7 @@ import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.util.HashMap; import java.util.Map; +import javax.script.Bindings; import jdk.internal.dynalink.CallSiteDescriptor; import jdk.internal.dynalink.linker.GuardedInvocation; import jdk.internal.dynalink.linker.GuardedTypeConversion; @@ -48,14 +49,23 @@ import jdk.nashorn.internal.runtime.JSType; * as ScriptObjects from other Nashorn contexts. */ final class JSObjectLinker implements TypeBasedGuardingDynamicLinker, GuardingTypeConverterFactory { + private final NashornBeansLinker nashornBeansLinker; + + JSObjectLinker(final NashornBeansLinker nashornBeansLinker) { + this.nashornBeansLinker = nashornBeansLinker; + } + @Override public boolean canLinkType(final Class type) { return canLinkTypeStatic(type); } static boolean canLinkTypeStatic(final Class type) { - // can link JSObject - return JSObject.class.isAssignableFrom(type); + // can link JSObject also handles Map, Bindings to make + // sure those are not JSObjects. + return Map.class.isAssignableFrom(type) || + Bindings.class.isAssignableFrom(type) || + JSObject.class.isAssignableFrom(type); } @Override @@ -72,6 +82,11 @@ final class JSObjectLinker implements TypeBasedGuardingDynamicLinker, GuardingTy final GuardedInvocation inv; if (self instanceof JSObject) { inv = lookup(desc); + } else if (self instanceof Map || self instanceof Bindings) { + // guard to make sure the Map or Bindings does not turn into JSObject later! + final GuardedInvocation beanInv = nashornBeansLinker.getGuardedInvocation(request, linkerServices); + inv = new GuardedInvocation(beanInv.getInvocation(), + NashornGuards.combineGuards(beanInv.getGuard(), NashornGuards.getNotJSObjectGuard())); } else { throw new AssertionError(); // Should never reach here. } diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornGuards.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornGuards.java index ca3e10c48d4..77c5e93cb77 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornGuards.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornGuards.java @@ -31,6 +31,7 @@ import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.ref.WeakReference; import jdk.internal.dynalink.CallSiteDescriptor; +import jdk.nashorn.api.scripting.JSObject; import jdk.nashorn.internal.codegen.ObjectClassGenerator; import jdk.nashorn.internal.objects.Global; import jdk.nashorn.internal.runtime.Property; @@ -43,6 +44,7 @@ import jdk.nashorn.internal.runtime.ScriptObject; */ public final class NashornGuards { private static final MethodHandle IS_SCRIPTOBJECT = findOwnMH("isScriptObject", boolean.class, Object.class); + private static final MethodHandle IS_NOT_JSOBJECT = findOwnMH("isNotJSObject", boolean.class, Object.class); private static final MethodHandle IS_SCRIPTFUNCTION = findOwnMH("isScriptFunction", boolean.class, Object.class); private static final MethodHandle IS_MAP = findOwnMH("isMap", boolean.class, Object.class, PropertyMap.class); private static final MethodHandle SAME_OBJECT = findOwnMH("sameObject", boolean.class, Object.class, WeakReference.class); @@ -60,6 +62,14 @@ public final class NashornGuards { return IS_SCRIPTOBJECT; } + /** + * Get the guard that checks if an item is not a {@code JSObject} + * @return method handle for guard + */ + public static MethodHandle getNotJSObjectGuard() { + return IS_NOT_JSOBJECT; + } + /** * Get the guard that checks if an item is a {@code ScriptFunction} * @return method handle for guard @@ -156,6 +166,11 @@ public final class NashornGuards { return self instanceof ScriptObject; } + @SuppressWarnings("unused") + private static boolean isNotJSObject(final Object self) { + return !(self instanceof JSObject); + } + @SuppressWarnings("unused") private static boolean isScriptFunction(final Object self) { return self instanceof ScriptFunction; diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornStaticClassLinker.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornStaticClassLinker.java index 272b4ec0ac4..f8ea9916041 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornStaticClassLinker.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornStaticClassLinker.java @@ -25,6 +25,7 @@ package jdk.nashorn.internal.runtime.linker; +import java.lang.reflect.Modifier; import jdk.internal.dynalink.CallSiteDescriptor; import jdk.internal.dynalink.beans.BeansLinker; import jdk.internal.dynalink.beans.StaticClass; @@ -65,10 +66,15 @@ final class NashornStaticClassLinker implements TypeBasedGuardingDynamicLinker { return null; } final Class receiverClass = ((StaticClass) self).getRepresentedClass(); + Bootstrap.checkReflectionAccess(receiverClass, true); final CallSiteDescriptor desc = request.getCallSiteDescriptor(); // We intercept "new" on StaticClass instances to provide additional capabilities if ("new".equals(desc.getNameToken(CallSiteDescriptor.OPERATOR))) { + if (! Modifier.isPublic(receiverClass.getModifiers())) { + throw ECMAErrors.typeError("new.on.nonpublic.javatype", receiverClass.getName()); + } + // make sure new is on accessible Class Context.checkPackageAccess(receiverClass); diff --git a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/Analyser.java b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/Analyser.java index a75e84cafee..eb612cd3d36 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/Analyser.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/Analyser.java @@ -771,7 +771,7 @@ final class Analyser extends Parser { while (value < end) { int ovalue = value; - buf = Character.toLowerCase(chars[value++]); + buf = EncodingHelper.toLowerCase(chars[value++]); if (chars[ovalue] != buf) { @@ -779,7 +779,7 @@ final class Analyser extends Parser { System.arraycopy(chars, sn.p, sbuf, 0, ovalue - sn.p); value = ovalue; while (value < end) { - buf = Character.toLowerCase(chars[value++]); + buf = EncodingHelper.toLowerCase(chars[value++]); if (sp >= sbuf.length) { char[]tmp = new char[sbuf.length << 1]; System.arraycopy(sbuf, 0, tmp, 0, sbuf.length); diff --git a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/ApplyCaseFold.java b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/ApplyCaseFold.java index 397b05cef47..dda5b733e27 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/ApplyCaseFold.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/ApplyCaseFold.java @@ -20,70 +20,42 @@ package jdk.nashorn.internal.runtime.regexp.joni; import jdk.nashorn.internal.runtime.regexp.joni.ast.CClassNode; -import jdk.nashorn.internal.runtime.regexp.joni.ast.ConsAltNode; -import jdk.nashorn.internal.runtime.regexp.joni.ast.StringNode; final class ApplyCaseFold { // i_apply_case_fold - public void apply(int from, int[]to, int length, Object o) { + public void apply(int from, int to, Object o) { ApplyCaseFoldArg arg = (ApplyCaseFoldArg)o; ScanEnvironment env = arg.env; CClassNode cc = arg.cc; BitSet bs = cc.bs; - if (length == 1) { - boolean inCC = cc.isCodeInCC(from); + boolean inCC = cc.isCodeInCC(from); - if (Config.CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS) { - if ((inCC && !cc.isNot()) || (!inCC && cc.isNot())) { - if (to[0] >= BitSet.SINGLE_BYTE_SIZE) { - cc.addCodeRange(env, to[0], to[0]); - } else { - /* /(?i:[^A-C])/.match("a") ==> fail. */ - bs.set(to[0]); - } - } - } else { - if (inCC) { - if (to[0] >= BitSet.SINGLE_BYTE_SIZE) { - if (cc.isNot()) cc.clearNotFlag(); - cc.addCodeRange(env, to[0], to[0]); - } else { - if (cc.isNot()) { - bs.clear(to[0]); - } else { - bs.set(to[0]); - } - } - } - } // CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS - - } else { - if (cc.isCodeInCC(from) && (!Config.CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS || !cc.isNot())) { - StringNode node = null; - for (int i=0; i= BitSet.SINGLE_BYTE_SIZE) { + cc.addCodeRange(env, to, to); } else { - arg.tail.setCdr(alt); + /* /(?i:[^A-C])/.match("a") ==> fail. */ + bs.set(to); } - arg.tail = alt; } - - } + } else { + if (inCC) { + if (to >= BitSet.SINGLE_BYTE_SIZE) { + if (cc.isNot()) cc.clearNotFlag(); + cc.addCodeRange(env, to, to); + } else { + if (cc.isNot()) { + bs.clear(to); + } else { + bs.set(to); + } + } + } + } // CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS } diff --git a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/ByteCodeMachine.java b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/ByteCodeMachine.java index df4b125bcee..b897a8cbf19 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/ByteCodeMachine.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/ByteCodeMachine.java @@ -58,8 +58,8 @@ class ByteCodeMachine extends StackMachine { int end1 = s1 + mbLen; while (s1 < end1) { - char c1 = Character.toLowerCase(chars[s1++]); - char c2 = Character.toLowerCase(chars[s2++]); + char c1 = EncodingHelper.toLowerCase(chars[s1++]); + char c2 = EncodingHelper.toLowerCase(chars[s2++]); if (c1 != c2) { return false; @@ -367,7 +367,7 @@ class ByteCodeMachine extends StackMachine { } private void opExact1IC() { - if (s >= range || code[ip] != Character.toLowerCase(chars[s++])) {opFail(); return;} + if (s >= range || code[ip] != EncodingHelper.toLowerCase(chars[s++])) {opFail(); return;} ip++; sprev = sbegin; // break; } @@ -380,10 +380,10 @@ class ByteCodeMachine extends StackMachine { char[] bs = regex.templates[code[ip++]]; int ps = code[ip++]; - while (tlen-- > 0) if (bs[ps++] != Character.toLowerCase(chars[s++])) {opFail(); return;} + while (tlen-- > 0) if (bs[ps++] != EncodingHelper.toLowerCase(chars[s++])) {opFail(); return;} } else { - while (tlen-- > 0) if (code[ip++] != Character.toLowerCase(chars[s++])) {opFail(); return;} + while (tlen-- > 0) if (code[ip++] != EncodingHelper.toLowerCase(chars[s++])) {opFail(); return;} } sprev = s - 1; } diff --git a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/EncodingHelper.java b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/EncodingHelper.java index afbb1b20bd1..0c9c8ab410c 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/EncodingHelper.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/EncodingHelper.java @@ -93,41 +93,78 @@ public final class EncodingHelper { return s; } - public static int mbcToCode(byte[] bytes, int p, int end) { - int code = 0; - for (int i = p; i < end; i++) { - code = (code << 8) | (bytes[i] & 0xff); - } - return code; - } - public static int mbcodeStartPosition() { return 0x80; } public static char[] caseFoldCodesByString(int flag, char c) { - if (Character.isUpperCase(c)) { - return new char[] {Character.toLowerCase(c)}; - } else if (Character.isLowerCase(c)) { - return new char[] {Character.toUpperCase(c)}; - } else { - return EMPTYCHARS; + char[] codes = EMPTYCHARS; + final char upper = toUpperCase(c); + + if (upper != toLowerCase(upper)) { + int count = 0; + char ch = 0; + + do { + final char u = toUpperCase(ch); + if (u == upper && ch != c) { + // Almost all characters will return array of length 1, very few 2 or 3, so growing by one is fine. + codes = count == 0 ? new char[1] : Arrays.copyOf(codes, count + 1); + codes[count++] = ch; + } + } while (ch++ < 0xffff); } + return codes; } public static void applyAllCaseFold(int flag, ApplyCaseFold fun, Object arg) { - int[] code = new int[1]; - for (int c = 0; c < 0xffff; c++) { - if (Character.getType(c) == Character.LOWERCASE_LETTER) { + if (Character.isLowerCase(c)) { + final int upper = toUpperCase(c); - int upper = code[0] = Character.toUpperCase(c); - fun.apply(c, code, 1, arg); - - code[0] = c; - fun.apply(upper, code, 1, arg); + if (upper != c) { + fun.apply(c, upper, arg); + } } } + + // Some characters have multiple lower case variants, hence we need to do a second run + for (int c = 0; c < 0xffff; c++) { + if (Character.isLowerCase(c)) { + final int upper = toUpperCase(c); + + if (upper != c) { + fun.apply(upper, c, arg); + } + } + } + } + + public static char toLowerCase(char c) { + return (char)toLowerCase((int)c); + } + + public static int toLowerCase(int c) { + if (c < 128) { + return ('A' <= c && c <= 'Z') ? (c + ('a' - 'A')) : c; + } + // Do not convert non-ASCII upper case character to ASCII lower case. + int lower = Character.toLowerCase(c); + return (lower < 128) ? c : lower; + + } + + public static char toUpperCase(char c) { + return (char)toUpperCase((int)c); + } + + public static int toUpperCase(int c) { + if (c < 128) { + return ('a' <= c && c <= 'z') ? c + ('A' - 'a') : c; + } + // Do not convert non-ASCII lower case character to ASCII upper case. + int upper = Character.toUpperCase(c); + return (upper < 128) ? c : upper; } public static int[] ctypeCodeRange(int ctype, IntHolder sbOut) { diff --git a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/SearchAlgorithm.java b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/SearchAlgorithm.java index 758679a267b..5b2eac97142 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/SearchAlgorithm.java +++ b/nashorn/src/jdk/nashorn/internal/runtime/regexp/joni/SearchAlgorithm.java @@ -168,7 +168,7 @@ public abstract class SearchAlgorithm { char[] chars, int p, int end) { while (tP < tEnd) { - if (t[tP++] != Character.toLowerCase(chars[p++])) return false; + if (t[tP++] != EncodingHelper.toLowerCase(chars[p++])) return false; } return true; } diff --git a/nashorn/src/jdk/nashorn/internal/runtime/resources/Messages.properties b/nashorn/src/jdk/nashorn/internal/runtime/resources/Messages.properties index 47248fce715..c98c1c7c84a 100644 --- a/nashorn/src/jdk/nashorn/internal/runtime/resources/Messages.properties +++ b/nashorn/src/jdk/nashorn/internal/runtime/resources/Messages.properties @@ -138,6 +138,7 @@ type.error.no.method.matches.args=Can not invoke method {0} with the passed argu type.error.method.not.constructor=Java method {0} can't be used as a constructor. type.error.env.not.object=$ENV must be an Object. type.error.unsupported.java.to.type=Unsupported Java.to target type {0}. +type.error.new.on.nonpublic.javatype=new cannot be used with non-public java type {0}. range.error.dataview.constructor.offset=Wrong offset or length in DataView constructor range.error.dataview.offset=Offset is outside the bounds of the DataView diff --git a/nashorn/test/script/basic/JDK-8030202.js b/nashorn/test/script/basic/JDK-8030202.js new file mode 100644 index 00000000000..6cf5647513b --- /dev/null +++ b/nashorn/test/script/basic/JDK-8030202.js @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2010, 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * JDK-8030202: Nashorn: Multiple RegExp#ignoreCase issues + * + * @test + * @run + */ + +print(/\u2160/i.test("\u2170")); +print(/[\u2160]/i.test("\u2170")); +print(/\u2170/i.test("\u2160")); +print(/[\u2170]/i.test("\u2160")); + +print(/\u0130/i.test("\u0069")); +print(/[\u0130]/i.test("\u0069")); +print(/\u0069/i.test("\u0130")); +print(/[\u0069]/i.test("\u0130")); + +print(/\u1e9e/i.test("\u00df")); +print(/[\u1e9e]/i.test("\u00df")); +print(/\u00df/i.test("\u1e9e")); +print(/[\u00df]/i.test("\u1e9e")); + +print(/[^\u1e9e]/i.test("\u00df")); +print(/[^\u00df]/i.test("\u1e9e")); + +print(/\u0345{4}/i.test("\u0345\u0399\u03b9\u1fbe")); +print(/\u0399{4}/i.test("\u0345\u0399\u03b9\u1fbe")); +print(/\u03b9{4}/i.test("\u0345\u0399\u03b9\u1fbe")); +print(/\u1fbe{4}/i.test("\u0345\u0399\u03b9\u1fbe")); + +print(/[\u0345]{4}/i.test("\u0345\u0399\u03b9\u1fbe")); +print(/[\u0399]{4}/i.test("\u0345\u0399\u03b9\u1fbe")); +print(/[\u03b9]{4}/i.test("\u0345\u0399\u03b9\u1fbe")); +print(/[\u1fbe]{4}/i.test("\u0345\u0399\u03b9\u1fbe")); diff --git a/nashorn/test/script/basic/JDK-8030202.js.EXPECTED b/nashorn/test/script/basic/JDK-8030202.js.EXPECTED new file mode 100644 index 00000000000..7c73d8c04b1 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8030202.js.EXPECTED @@ -0,0 +1,22 @@ +true +true +true +true +false +false +false +false +false +false +false +false +true +true +true +true +true +true +true +true +true +true diff --git a/nashorn/test/script/basic/JDK-8043930.js b/nashorn/test/script/basic/JDK-8043930.js new file mode 100644 index 00000000000..a89b3541e37 --- /dev/null +++ b/nashorn/test/script/basic/JDK-8043930.js @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2010, 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * JDK-8043930: TypeError when attemping to create an instance of non-public class could be better + * + * @test + * @run + */ + +var NonPublicClass = Java.type("jdk.nashorn.test.models.NonPublicClass"); +try { + var obj = new NonPublicClass(); + fail("Expected TypeError to be thrown!"); +} catch (e) { + print(e); +} diff --git a/nashorn/test/script/basic/JDK-8043930.js.EXPECTED b/nashorn/test/script/basic/JDK-8043930.js.EXPECTED new file mode 100644 index 00000000000..ee5cf9dc81c --- /dev/null +++ b/nashorn/test/script/basic/JDK-8043930.js.EXPECTED @@ -0,0 +1 @@ +TypeError: new cannot be used with non-public java type jdk.nashorn.test.models.NonPublicClass. diff --git a/nashorn/test/script/nosecurity/nosecurity.js b/nashorn/test/script/nosecurity/nosecurity.js new file mode 100644 index 00000000000..688af8cf6a0 --- /dev/null +++ b/nashorn/test/script/nosecurity/nosecurity.js @@ -0,0 +1,34 @@ +/* + * 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * 8043443: Test framework changes to run script tests without security manager + * @test + * @run + */ + +var System = Java.type("java.lang.System"); + +if (System.securityManager != null) { + fail("SecurityManager is set!"); +} diff --git a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptObjectMirrorTest.java b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptObjectMirrorTest.java index 241f22c39ea..30eaefcadb5 100644 --- a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptObjectMirrorTest.java +++ b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptObjectMirrorTest.java @@ -29,6 +29,8 @@ import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.script.Bindings; +import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; @@ -276,4 +278,31 @@ public class ScriptObjectMirrorTest { "({ toString: function() { return 'foo' } })"); assertEquals("foo", obj.to(String.class)); } + + // @bug 8044000: Access to undefined property yields "null" instead of "undefined" + @Test + public void mapScriptObjectMirrorCallsiteTest() throws ScriptException { + final ScriptEngineManager m = new ScriptEngineManager(); + final ScriptEngine engine = m.getEngineByName("nashorn"); + final String TEST_SCRIPT = "typeof obj.foo"; + + final Bindings global = engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE); + engine.eval("var obj = java.util.Collections.emptyMap()"); + // this will drive callsite "obj.foo" of TEST_SCRIPT + // to use "obj instanceof Map" as it's guard + engine.eval(TEST_SCRIPT, global); + // redefine 'obj' to be a script object + engine.eval("obj = {}"); + + final Bindings newGlobal = engine.createBindings(); + // transfer 'obj' from default global to new global + // new global will get a ScriptObjectMirror wrapping 'obj' + newGlobal.put("obj", global.get("obj")); + + // Every ScriptObjectMirror is a Map! If callsite "obj.foo" + // does not see the new 'obj' is a ScriptObjectMirror, it'll + // continue to use Map's get("obj.foo") instead of ScriptObjectMirror's + // getMember("obj.foo") - thereby getting null instead of undefined + assertEquals("undefined", engine.eval(TEST_SCRIPT, newGlobal)); + } } diff --git a/test/Makefile b/test/Makefile index 08b91bf7f9c..7a66290318c 100644 --- a/test/Makefile +++ b/test/Makefile @@ -33,6 +33,7 @@ TOPDIR=.. # This makefile depends on the availability of sibling directories. LANGTOOLS_DIR=$(TOPDIR)/langtools JDK_DIR=$(TOPDIR)/jdk +HOTSPOT_DIR=$(TOPDIR)/hotspot # Macro to run a test target in a subdir define SUBDIR_TEST # subdirectory target @@ -62,6 +63,9 @@ langtools_% : jdk_% core_%s svc_%: @$(NO_STOPPING)$(call SUBDIR_TEST, $(JDK_DIR), TEST="$@" $@) +hotspot_%: + @$(NO_STOPPING)$(call SUBDIR_TEST, $(HOTSPOT_DIR), TEST="$@" $@) + ################################################################ # Phony targets (e.g. these are not filenames)