diff --git a/.hgtags b/.hgtags index 24dc9213f13fbcadddfb2807883e1d9b4f333064..5ca82e2575b4f101e0ceeffde6badd3dfb900b1b 100644 --- a/.hgtags +++ b/.hgtags @@ -93,3 +93,5 @@ e250cef36ea05e627e7e6f7d75e5e19f529e2ba3 jdk7-b114 1657ed4e1d86c8aa2028ab5a41f9da1ac4a369f8 jdk7-b116 3e6726bbf80a4254ecd01051c8ed77ee19325e46 jdk7-b117 b357910aa04aead2a16b6d6ff395a8df4b51d1dd jdk7-b118 +ecab7eefb8f2326fd90fb632f47f1b6f81e928f8 jdk7-b119 +37d74e29687cf07c2bf9411af58c7e42440855c3 jdk7-b120 diff --git a/make/common/shared/Defs-linux.gmk b/make/common/shared/Defs-linux.gmk index fbc059c1da6cd396ee11d851d785e6cb8cfa6eca..71272540c055fb75662fe158efe2b1164c251f77 100644 --- a/make/common/shared/Defs-linux.gmk +++ b/make/common/shared/Defs-linux.gmk @@ -123,7 +123,7 @@ LIBM=-lm # GCC29_COMPILER_PATH: is the path to where the gcc 2.9 compiler is installed # NOTE: Must end with / so that it could be empty, allowing PATH usage. -ifneq "$(origin ALT_GCC29_COMPILER_PATH)" "undefined" +ifdef ALT_GCC29_COMPILER_PATH GCC29_COMPILER_PATH :=$(call PrefixPath,$(ALT_GCC29_COMPILER_PATH)) else GCC29_COMPILER_PATH = $(JDK_DEVTOOLS_DIR)/$(PLATFORM)/gcc29/usr/ diff --git a/make/common/shared/Defs-versions.gmk b/make/common/shared/Defs-versions.gmk index 91fe4be805661f928a7a278da5bded4547672cbc..7fada0d2b7c1e3d2dfa537c24cb0e9ad317df27d 100644 --- a/make/common/shared/Defs-versions.gmk +++ b/make/common/shared/Defs-versions.gmk @@ -65,7 +65,7 @@ # If we are using freetype, the freetype version expected. # # REQUIRED_GCC_VER -# Solaris and Linux only. The required version of gcc/g++ for the plugin. +# Solaris and Linux only. The required version of gcc/g++ for the legacy OJI plugin. # # REQUIRED_LINK_VER # Windows only: The version of link.exe expected. diff --git a/make/common/shared/Sanity.gmk b/make/common/shared/Sanity.gmk index 39f99ae7c17c8e70ad5175d838e2eb62f99b9c35..f1d0e0451e22927ea01a9e0a5876081e70200338 100644 --- a/make/common/shared/Sanity.gmk +++ b/make/common/shared/Sanity.gmk @@ -99,12 +99,16 @@ ifeq ($(PLATFORM), linux) echo "RedHat"; \ elif [ -f /etc/SuSE-release ] ; then \ echo "SuSE"; \ + elif [ -f /etc/lsb-release ] ; then \ + $(EGREP) DISTRIB_ID /etc/lsb-release | $(SED) -e 's@.*DISTRIB_ID=\(.*\)@\1@'; \ else \ echo "Unknown"; \ fi) OS_VARIANT_VERSION := $(shell \ if [ "$(OS_VARIANT_NAME)" = "Fedora" ] ; then \ $(CAT) /etc/fedora-release | $(HEAD) -1 | $(NAWK) '{ print $$3; }' ; \ + elif [ -f /etc/lsb-release ] ; then \ + $(EGREP) DISTRIB_RELEASE /etc/lsb-release | $(SED) -e 's@.*DISTRIB_RELEASE=\(.*\)@\1@'; \ fi) ALSA_INCLUDE=/usr/include/alsa/version.h ALSA_LIBRARY=/usr/lib/libasound.so @@ -279,7 +283,7 @@ sane-arch_data_model: fi ###################################################### -# Check the OS version (windows and linus have release name checks) +# Check the OS version (windows and linux have release name checks) # NOTE: OPENJDK explicitly does not check for OS release information. # Unless we know for sure that it will not build somewhere, we cannot # generate a fatal sanity error, and a warning about the official @@ -1476,20 +1480,20 @@ ifeq ($(PLATFORM), windows) endif ###################################################### -# Check the Solaris GNU c++ compiler for solaris plugin +# Check the GNU C++ compiler for OJI plugin ###################################################### sane-gcc-compiler: -ifeq ($(PLATFORM), solaris) - ifndef OPENJDK - @if [ -r $(GCC_COMPILER_PATH) ]; then \ - if [ ! "$(GCC_VER)" = $(REQUIRED_GCC_VERSION) ]; then \ - $(ECHO) "ERROR: The Solaris GCC compiler version must be $(REQUIRED_GCC_VERSION). \n" \ +ifndef OPENJDK + ifeq ($(PLATFORM), solaris) + @if [ -r $(GCC_COMPILER_PATH) ]; then \ + if [ ! "$(GCC_VER)" = $(REQUIRED_GCC_VER) ]; then \ + $(ECHO) "ERROR: The Solaris GCC compiler version must be $(REQUIRED_GCC_VER). \n" \ " You are using the following compiler version: $(GCC_VER) \n" \ " The compiler was obtained from the following location: \n" \ " $(GCC_COMPILER_PATH) \n" \ " Please change your compiler. \n" \ "" >> $(ERROR_FILE) ; \ - fi \ + fi \ else \ $(ECHO) "ERROR: You do not have a valid GCC_COMPILER_PATH setting. \n" \ " Please check your access to \n" \ @@ -1501,15 +1505,16 @@ ifeq ($(PLATFORM), solaris) endif ifeq ($(PLATFORM), linux) + ifeq ($(ARCH_DATA_MODEL), 32) ifdef ALT_GCC29_COMPILER_PATH @if [ ! -x $(ALT_GCC29_COMPILER_PATH)/bin/gcc ]; then \ - $(ECHO) "ERROR: You do not have a valid ALT_GCC29_COMPILER_PATH setting. \n" \ + $(ECHO) "ERROR: You do not have a valid ALT_GCC29_COMPILER_PATH setting. \n" \ " Please check your access to \n" \ " $(ALT_GCC29_COMPILER_PATH)/bin/gcc \n" \ " This will affect you if you build the plugin target. \n" \ "" >> $(ERROR_FILE) ; \ fi - endif + else ifdef ALT_GCC29_PLUGIN_LIB_PATH @if [ ! -r $(ALT_GCC29_PLUGIN_LIB_PATH)/libjavaplugin_oji.so ]; then \ $(ECHO) "Error: You do not have a valid ALT_GCC29_PLUGIN_LIB_PATH setting. \n" \ @@ -1523,13 +1528,15 @@ ifeq ($(PLATFORM), solaris) $(ECHO) "ERROR: You do not have a valid GCC29_COMPILER_PATH setting. \n" \ " Please check your access to \n" \ " $(GCC29_COMPILER_PATH) \n" \ - " and/or check your value of ALT_GCC29_COMPILER_PATH. \n" \ + " and/or check your value of ALT_GCC29_COMPILER_PATH or ALT_GCC29_PLUGIN_LIB_PATH \n" \ " This will affect you if you build the plugin target. \n" \ "" >> $(ERROR_FILE) ; \ fi - endif - endif -endif + endif # ALT_GCC29_PLUGIN_LIB_PATH + endif # ALT_GCC29_COMPILER_PATH + endif # ARCH_DATA_MODEL, 32 + endif # LINUX +endif # OPEN_JDK ###################################################### diff --git a/make/docs/Makefile b/make/docs/Makefile index 960c99947f3614663af4bb17d8538ef33f54756a..98bf18b76da85b45971e2d10c8676f78b2d3a232 100644 --- a/make/docs/Makefile +++ b/make/docs/Makefile @@ -190,7 +190,6 @@ $(call CopyrightLine,$(COPYRIGHT_URL),$(FIRST_COPYRIGHT_YEAR),)\ # Common javadoc options used by all COMMON_JAVADOCFLAGS = \ $(NO_PROPRIETARY_API_WARNINGS) \ - -source 1.5 \ -quiet \ -use \ -keywords \ diff --git a/make/mkdemo/nio/zipfs/Makefile b/make/mkdemo/nio/zipfs/Makefile index a2405030dc1b8e66e390f5ff3bcb657b2111a78f..e1120d8a6f4e14008b877ce1ef74490c6da1cf8c 100644 --- a/make/mkdemo/nio/zipfs/Makefile +++ b/make/mkdemo/nio/zipfs/Makefile @@ -33,8 +33,8 @@ DEMONAME = zipfs include $(BUILDDIR)/common/Defs.gmk DEMO_ROOT = $(SHARE_SRC)/demo/nio/$(DEMONAME) -DEMO_TOPFILES = ./README.txt -DEMO_SRCDIR = $(DEMO_ROOT) +DEMO_TOPFILES = README.txt Demo.java +DEMO_SRCDIR = $(DEMO_ROOT)/src DEMO_DESTDIR = $(DEMODIR)/nio/$(DEMONAME) # @@ -42,10 +42,10 @@ DEMO_DESTDIR = $(DEMODIR)/nio/$(DEMONAME) # include $(BUILDDIR)/common/Demo.gmk -#EXTJAR = $(EXTDIR)/$(DEMONAME).jar -# -#all : build $(EXTJAR) -# -#$(EXTJAR) : $(DEMO_JAR) -# $(prep-target) -# $(CP) $(DEMO_JAR) $(EXTJAR) +EXTJAR = $(EXTDIR)/$(DEMONAME).jar + +all : build $(EXTJAR) + +$(EXTJAR) : $(DEMO_JAR) + $(prep-target) + $(CP) $(DEMO_JAR) $(EXTJAR) diff --git a/make/sun/xawt/mapfile-vers b/make/sun/xawt/mapfile-vers index fa5fe360ffc626ae25098661b2fea1142e6006bf..0d951efff1d200ae6110026c0a6594869d5de64b 100644 --- a/make/sun/xawt/mapfile-vers +++ b/make/sun/xawt/mapfile-vers @@ -429,6 +429,7 @@ SUNWprivate_1.1 { Java_com_sun_java_swing_plaf_gtk_GTKStyle_nativeGetClassValue; Java_com_sun_java_swing_plaf_gtk_GTKStyle_nativeGetPangoFontName; + Java_sun_awt_X11_GtkFileDialogPeer_initIDs; Java_sun_awt_X11_GtkFileDialogPeer_run; Java_sun_awt_X11_GtkFileDialogPeer_quit; diff --git a/make/tools/CharsetMapping/extsbcs b/make/tools/CharsetMapping/extsbcs index e66fe5bbb1cde40f855061c8f7dd65c73c4982b8..ac24dbe7a7dbd1f127a27259ef36d2c3e67f2194 100644 --- a/make/tools/CharsetMapping/extsbcs +++ b/make/tools/CharsetMapping/extsbcs @@ -32,7 +32,7 @@ IBM297 IBM297 Cp297 false sun.nio.cs.ext IBM420 IBM420 Cp420 false sun.nio.cs.ext IBM424 IBM424 Cp424 false sun.nio.cs.ext IBM500 IBM500 Cp500 false sun.nio.cs.ext -IBM833 IBM833 Cp833 false sun.nio.cs.ext +IBM833 x-IBM833 Cp833 false sun.nio.cs.ext IBM838 IBM-Thai Cp838 false sun.nio.cs.ext IBM856 x-IBM856 Cp856 false sun.nio.cs.ext IBM860 IBM860 Cp860 false sun.nio.cs.ext diff --git a/src/share/bin/java.c b/src/share/bin/java.c index 01eeb2a0547ab076b0db300e7e2eed29c301f54f..e02b8ac8bb0896eb147df78fd013c7be587ea57e 100644 --- a/src/share/bin/java.c +++ b/src/share/bin/java.c @@ -65,6 +65,7 @@ static jboolean printVersion = JNI_FALSE; /* print and exit */ static jboolean showVersion = JNI_FALSE; /* print but continue */ static jboolean printUsage = JNI_FALSE; /* print and exit*/ static jboolean printXUsage = JNI_FALSE; /* print and exit*/ +static char *showSettings = NULL; /* print but continue */ static const char *_program_name; static const char *_launcher_name; @@ -109,6 +110,7 @@ static void SetApplicationClassPath(const char**); static void PrintJavaVersion(JNIEnv *env, jboolean extraLF); static void PrintUsage(JNIEnv* env, jboolean doXUsage); +static void ShowSettings(JNIEnv* env, char *optString); static void SetPaths(int argc, char **argv); @@ -157,6 +159,7 @@ static jboolean IsWildCardEnabled(); * create a new thread to invoke JVM. See 6316197 for more information. */ static jlong threadStackSize = 0; /* stack size of the new thread */ +static jlong heapSize = 0; /* heap size */ int JNICALL JavaMain(void * args); /* entry point */ @@ -376,6 +379,10 @@ JavaMain(void * _args) } } + if (showSettings != NULL) { + ShowSettings(env, showSettings); + CHECK_EXCEPTION_LEAVE(0); + } /* If the user specified neither a class name nor a JAR file */ if (printXUsage || printUsage || (jarfile == 0 && classname == 0)) { PrintUsage(env, printXUsage); @@ -611,7 +618,7 @@ CheckJvmType(int *pargc, char ***argv, jboolean speculative) { /* copied from HotSpot function "atomll()" */ static int -parse_stack_size(const char *s, jlong *result) { +parse_size(const char *s, jlong *result) { jlong n = 0; int args_read = sscanf(s, jlong_format_specifier(), &n); if (args_read != 1) { @@ -673,10 +680,17 @@ AddOption(char *str, void *info) options[numOptions++].extraInfo = info; if (JLI_StrCCmp(str, "-Xss") == 0) { - jlong tmp; - if (parse_stack_size(str + 4, &tmp)) { - threadStackSize = tmp; - } + jlong tmp; + if (parse_size(str + 4, &tmp)) { + threadStackSize = tmp; + } + } + + if (JLI_StrCCmp(str, "-Xmx") == 0) { + jlong tmp; + if (parse_size(str + 4, &tmp)) { + heapSize = tmp; + } } } @@ -1014,6 +1028,13 @@ ParseArguments(int *pargc, char ***pargv, char **pjarfile, } else if (JLI_StrCmp(arg, "-X") == 0) { printXUsage = JNI_TRUE; return JNI_TRUE; +/* + * The following case checks for -XshowSettings OR -XshowSetting:SUBOPT. + * In the latter case, any SUBOPT value not recognized will default to "all" + */ + } else if (JLI_StrCmp(arg, "-XshowSettings") == 0 || + JLI_StrCCmp(arg, "-XshowSettings:") == 0) { + showSettings = arg; /* * The following case provide backward compatibility with old-style * command line options. @@ -1474,6 +1495,27 @@ PrintJavaVersion(JNIEnv *env, jboolean extraLF) (*env)->CallStaticVoidMethod(env, ver, print); } +/* + * Prints all the Java settings, see the java implementation for more details. + */ +static void +ShowSettings(JNIEnv *env, char *optString) +{ + jclass cls; + jmethodID showSettingsID; + jstring joptString; + NULL_CHECK(cls = FindBootStrapClass(env, "sun/launcher/LauncherHelper")); + NULL_CHECK(showSettingsID = (*env)->GetStaticMethodID(env, cls, + "showSettings", "(ZLjava/lang/String;JJZ)V")); + joptString = (*env)->NewStringUTF(env, optString); + (*env)->CallStaticVoidMethod(env, cls, showSettingsID, + JNI_TRUE, + joptString, + (jlong)heapSize, + (jlong)threadStackSize, + ServerClassMachine()); +} + /* * Prints default usage or the Xusage message, see sun.launcher.LauncherHelper.java */ diff --git a/src/share/classes/com/sun/java/util/jar/pack/AdaptiveCoding.java b/src/share/classes/com/sun/java/util/jar/pack/AdaptiveCoding.java index 477806bd912f6e2cf851683107bfee938524f699..a782e8631e5a935c9dec9b3dba9813b0b7ca35a0 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/AdaptiveCoding.java +++ b/src/share/classes/com/sun/java/util/jar/pack/AdaptiveCoding.java @@ -25,8 +25,10 @@ package com.sun.java.util.jar.pack; -import java.util.*; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; /** * Adaptive coding. diff --git a/src/share/classes/com/sun/java/util/jar/pack/Attribute.java b/src/share/classes/com/sun/java/util/jar/pack/Attribute.java index b662ebb9683ddfd1e5e4c6ccb8f3c29744fd32b1..7b838f26d022ddc35c6ec27787cf7ff5cb94d75b 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Attribute.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Attribute.java @@ -25,9 +25,17 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; -import com.sun.java.util.jar.pack.ConstantPool.*; +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import com.sun.java.util.jar.pack.ConstantPool.Index; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * Represents an attribute in a class-file. diff --git a/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java b/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java index 1c8266cd69f579b65f9b9c8fcd9f6d79e79d0a3c..7af5e38019d3ab1b3197d7ec4fc64b1bd8d87deb 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java +++ b/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java @@ -25,12 +25,28 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; -import java.util.jar.*; -import com.sun.java.util.jar.pack.Package.Class; -import com.sun.java.util.jar.pack.Package.InnerClass; -import com.sun.java.util.jar.pack.ConstantPool.*; +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import com.sun.java.util.jar.pack.ConstantPool.Index; +import com.sun.java.util.jar.pack.Package.Class.Field; +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.EOFException; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FilterInputStream; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.jar.Pack200; /** * Define the structure and ordering of "bands" in a packed file. @@ -1629,7 +1645,7 @@ class BandStructure implements Constants { } } - protected void setConstantValueIndex(Class.Field f) { + protected void setConstantValueIndex(com.sun.java.util.jar.pack.Package.Class.Field f) { Index ix = null; if (f != null) { byte tag = f.getLiteralTag(); diff --git a/src/share/classes/com/sun/java/util/jar/pack/ClassReader.java b/src/share/classes/com/sun/java/util/jar/pack/ClassReader.java index 356be128b450c14afeb0cda28fae068e7c5517a5..a1bce52a5e2b8e60587b248638b271372bc051ed 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/ClassReader.java +++ b/src/share/classes/com/sun/java/util/jar/pack/ClassReader.java @@ -25,11 +25,19 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; +import com.sun.java.util.jar.pack.ConstantPool.ClassEntry; +import com.sun.java.util.jar.pack.ConstantPool.DescriptorEntry; +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import com.sun.java.util.jar.pack.ConstantPool.SignatureEntry; +import com.sun.java.util.jar.pack.ConstantPool.Utf8Entry; import com.sun.java.util.jar.pack.Package.Class; import com.sun.java.util.jar.pack.Package.InnerClass; -import com.sun.java.util.jar.pack.ConstantPool.*; +import java.io.DataInputStream; +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Map; /** * Reader for a class file that is being incorporated into a package. diff --git a/src/share/classes/com/sun/java/util/jar/pack/ClassWriter.java b/src/share/classes/com/sun/java/util/jar/pack/ClassWriter.java index 516954c937a67e19c4b28f52111880d2d132dffc..a4ceff5768665b480255ba4fe3a047f008be89c4 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/ClassWriter.java +++ b/src/share/classes/com/sun/java/util/jar/pack/ClassWriter.java @@ -25,11 +25,19 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; + +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import com.sun.java.util.jar.pack.ConstantPool.Index; +import com.sun.java.util.jar.pack.ConstantPool.NumberEntry; import com.sun.java.util.jar.pack.Package.Class; import com.sun.java.util.jar.pack.Package.InnerClass; -import com.sun.java.util.jar.pack.ConstantPool.*; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Iterator; +import java.util.List; /** * Writer for a class file that is incorporated into a package. diff --git a/src/share/classes/com/sun/java/util/jar/pack/Code.java b/src/share/classes/com/sun/java/util/jar/pack/Code.java index 3461d44293c171b69d229c54c85a142c9e000dbf..e6272f57a5bb528260c62818e9b5ef2454b8de13 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Code.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Code.java @@ -25,10 +25,10 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; import com.sun.java.util.jar.pack.Package.Class; import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.Collection; /** * Represents a chunk of bytecodes. diff --git a/src/share/classes/com/sun/java/util/jar/pack/Coding.java b/src/share/classes/com/sun/java/util/jar/pack/Coding.java index 6e72d1baae8def13ab5aa316cb4ba9d817992b08..a35261f5db91bdcc65f79f786d29b19bc1cab487 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Coding.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Coding.java @@ -25,8 +25,10 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.HashMap; /** * Define the conversions between sequences of small integers and raw bytes. diff --git a/src/share/classes/com/sun/java/util/jar/pack/CodingChooser.java b/src/share/classes/com/sun/java/util/jar/pack/CodingChooser.java index 2f1f3e1b83900f3d014ac1c6fb4011688db7739e..61a6710a6f6d202208132ad92440b27d25e04122 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/CodingChooser.java +++ b/src/share/classes/com/sun/java/util/jar/pack/CodingChooser.java @@ -25,9 +25,17 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; -import java.util.zip.*; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Random; +import java.util.zip.Deflater; +import java.util.zip.DeflaterOutputStream; /** * Heuristic chooser of basic encodings. diff --git a/src/share/classes/com/sun/java/util/jar/pack/CodingMethod.java b/src/share/classes/com/sun/java/util/jar/pack/CodingMethod.java index 75f32a86118524d2d159299ba71266ce15c4ee5f..d0b1d9d9604a0cb436e58ed817ba17d5e44cca4d 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/CodingMethod.java +++ b/src/share/classes/com/sun/java/util/jar/pack/CodingMethod.java @@ -25,7 +25,9 @@ package com.sun.java.util.jar.pack; -import java.io.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; /** * Interface for encoding and decoding int arrays using bytewise codes. diff --git a/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java b/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java index ac6199abe25e3dee29c821326bf683110e2f13a2..abafbd92b4096c644fdb74e7616a0c4844ed5b4d 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java +++ b/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java @@ -25,7 +25,14 @@ package com.sun.java.util.jar.pack; -import java.util.*; +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Set; /** * Representation of constant pool entries and indexes. diff --git a/src/share/classes/com/sun/java/util/jar/pack/Constants.java b/src/share/classes/com/sun/java/util/jar/pack/Constants.java index 19ce04cf559612e4574d7dfc965a0e309a17e301..512dac7972fd09d803639a6a27c900ab081ddc91 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Constants.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Constants.java @@ -25,7 +25,8 @@ package com.sun.java.util.jar.pack; -import java.util.*; +import java.util.Arrays; +import java.util.List; /** * Shared constants diff --git a/src/share/classes/com/sun/java/util/jar/pack/Driver.java b/src/share/classes/com/sun/java/util/jar/pack/Driver.java index 2630febb7c35c721c54154cd3525f1fe03e28d9f..a7c47a8a8cc6b6e1f4f01031d73e5264927e4e06 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Driver.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Driver.java @@ -25,11 +25,32 @@ package com.sun.java.util.jar.pack; -import java.io.*; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; import java.text.MessageFormat; -import java.util.*; -import java.util.jar.*; -import java.util.zip.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Properties; +import java.util.ResourceBundle; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.jar.JarFile; +import java.util.jar.JarOutputStream; +import java.util.jar.Pack200; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; /** Command line interface for Pack200. */ diff --git a/src/share/classes/com/sun/java/util/jar/pack/Fixups.java b/src/share/classes/com/sun/java/util/jar/pack/Fixups.java index 3cb47069c8f3ee9334995202219f144cb58be8ee..77815b43b2275f05e88d3e872326fd465e09aab4 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Fixups.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Fixups.java @@ -25,9 +25,11 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; -import com.sun.java.util.jar.pack.ConstantPool.*; +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import java.util.AbstractCollection; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; /** * Collection of relocatable constant pool references. diff --git a/src/share/classes/com/sun/java/util/jar/pack/Histogram.java b/src/share/classes/com/sun/java/util/jar/pack/Histogram.java index 1c03e592b0260e936b79371c39737de404fd921d..92cf6e4e918b36184eaa2b538966d607a43b27cf 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Histogram.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Histogram.java @@ -25,8 +25,10 @@ package com.sun.java.util.jar.pack; -import java.util.*; -import java.io.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.util.Arrays; /** * Histogram derived from an integer array of events (int[]). diff --git a/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java b/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java index c6d9608518014840ae2750f3dcd118ee42436091..2ea9f4d4721c091b9e7a561576a5d0ed3ad796df 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java +++ b/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java @@ -26,10 +26,18 @@ package com.sun.java.util.jar.pack; -import java.nio.*; -import java.io.*; -import java.util.jar.*; -import java.util.zip.*; +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.util.jar.JarOutputStream; +import java.util.jar.Pack200; +import java.util.zip.CRC32; +import java.util.zip.Deflater; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; class NativeUnpack { // Pointer to the native unpacker obj diff --git a/src/share/classes/com/sun/java/util/jar/pack/Package.java b/src/share/classes/com/sun/java/util/jar/pack/Package.java index 29d217687c49b1283ad03ba864bff6d24543509f..981bd53b75c67adbabb9ec9b02df6619e4bda90a 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Package.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Package.java @@ -26,11 +26,32 @@ package com.sun.java.util.jar.pack; import com.sun.java.util.jar.pack.Attribute.Layout; +import com.sun.java.util.jar.pack.ConstantPool.ClassEntry; +import com.sun.java.util.jar.pack.ConstantPool.DescriptorEntry; +import com.sun.java.util.jar.pack.ConstantPool.Index; +import com.sun.java.util.jar.pack.ConstantPool.LiteralEntry; +import com.sun.java.util.jar.pack.ConstantPool.Utf8Entry; +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.SequenceInputStream; import java.lang.reflect.Modifier; -import java.util.*; -import java.util.jar.*; -import java.io.*; -import com.sun.java.util.jar.pack.ConstantPool.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Set; +import java.util.jar.JarFile; /** * Define the main data structure transmitted by pack/unpack. diff --git a/src/share/classes/com/sun/java/util/jar/pack/PackageReader.java b/src/share/classes/com/sun/java/util/jar/pack/PackageReader.java index 73efca5ca85e0f518663fc06d140a252643f29c2..be8ba0d008b0c0d7ac134d115ddcf42df05b579b 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/PackageReader.java +++ b/src/share/classes/com/sun/java/util/jar/pack/PackageReader.java @@ -25,12 +25,18 @@ package com.sun.java.util.jar.pack; +import com.sun.java.util.jar.pack.ConstantPool.ClassEntry; +import com.sun.java.util.jar.pack.ConstantPool.DescriptorEntry; +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import com.sun.java.util.jar.pack.ConstantPool.Index; +import com.sun.java.util.jar.pack.ConstantPool.MemberEntry; +import com.sun.java.util.jar.pack.ConstantPool.SignatureEntry; +import com.sun.java.util.jar.pack.ConstantPool.Utf8Entry; import java.io.*; import java.util.*; import com.sun.java.util.jar.pack.Package.Class; import com.sun.java.util.jar.pack.Package.File; import com.sun.java.util.jar.pack.Package.InnerClass; -import com.sun.java.util.jar.pack.ConstantPool.*; /** * Reader for a package file. diff --git a/src/share/classes/com/sun/java/util/jar/pack/PackageWriter.java b/src/share/classes/com/sun/java/util/jar/pack/PackageWriter.java index 55b64cce5e851ca2bfa1072f419a17a088f524d3..cbfcb8aacfd0a13fbf283ffafc0e8d40fa6d91a0 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/PackageWriter.java +++ b/src/share/classes/com/sun/java/util/jar/pack/PackageWriter.java @@ -25,12 +25,30 @@ package com.sun.java.util.jar.pack; -import java.io.*; -import java.util.*; +import com.sun.java.util.jar.pack.ConstantPool.ClassEntry; +import com.sun.java.util.jar.pack.ConstantPool.DescriptorEntry; +import com.sun.java.util.jar.pack.ConstantPool.Entry; +import com.sun.java.util.jar.pack.ConstantPool.Index; +import com.sun.java.util.jar.pack.ConstantPool.IndexGroup; +import com.sun.java.util.jar.pack.ConstantPool.MemberEntry; +import com.sun.java.util.jar.pack.ConstantPool.NumberEntry; +import com.sun.java.util.jar.pack.ConstantPool.SignatureEntry; +import com.sun.java.util.jar.pack.ConstantPool.StringEntry; import com.sun.java.util.jar.pack.Package.Class; import com.sun.java.util.jar.pack.Package.File; import com.sun.java.util.jar.pack.Package.InnerClass; -import com.sun.java.util.jar.pack.ConstantPool.*; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; /** * Writer for a package file. diff --git a/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java b/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java index f48407099977518c970cb7b33bdf9858c669b64c..7e2f6a27c02f7bf6de89b495442783ff90980586 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java +++ b/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java @@ -26,10 +26,27 @@ package com.sun.java.util.jar.pack; import com.sun.java.util.jar.pack.Attribute.Layout; -import java.util.*; -import java.util.jar.*; -import java.io.*; import java.beans.PropertyChangeListener; +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.SortedMap; +import java.util.TimeZone; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarInputStream; +import java.util.jar.Pack200; /* diff --git a/src/share/classes/com/sun/java/util/jar/pack/PopulationCoding.java b/src/share/classes/com/sun/java/util/jar/pack/PopulationCoding.java index 599d86fa6b2604e632257dd83ccb84d947673be0..3e5ecf170c3dd31b3279d4e0ee3cabef46302923 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/PopulationCoding.java +++ b/src/share/classes/com/sun/java/util/jar/pack/PopulationCoding.java @@ -25,8 +25,12 @@ package com.sun.java.util.jar.pack; -import java.util.*; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.HashSet; /** * Population-based coding. diff --git a/src/share/classes/com/sun/java/util/jar/pack/PropMap.java b/src/share/classes/com/sun/java/util/jar/pack/PropMap.java index 78c709f343d554c5b2c25699a10574f29c9cd734..3072ef394eb0ddb53027fcf227063e94d821a539 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/PropMap.java +++ b/src/share/classes/com/sun/java/util/jar/pack/PropMap.java @@ -25,13 +25,24 @@ package com.sun.java.util.jar.pack; -import java.util.*; -import java.util.jar.*; -import java.util.jar.Pack200; -import java.util.zip.*; -import java.io.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.jar.Pack200; /** * Control block for publishing Pack200 options to the other classes. */ diff --git a/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java b/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java index 5b9f8ec61f6ee56434660cce13aa738f1ec41df8..a0c1e4d26ef457e873c5ce658fb66974b38077ca 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java +++ b/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java @@ -25,11 +25,25 @@ package com.sun.java.util.jar.pack; -import java.util.*; -import java.util.jar.*; -import java.util.zip.*; -import java.io.*; import java.beans.PropertyChangeListener; +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.HashSet; +import java.util.Iterator; +import java.util.SortedMap; +import java.util.TimeZone; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; +import java.util.jar.JarOutputStream; +import java.util.jar.Pack200; +import java.util.zip.CRC32; +import java.util.zip.CheckedOutputStream; +import java.util.zip.ZipEntry; /* * Implementation of the Pack provider. diff --git a/src/share/classes/com/sun/java/util/jar/pack/Utils.java b/src/share/classes/com/sun/java/util/jar/pack/Utils.java index 84f65ac2ccfcbbbc769f769e95b43eeef2c6b8da..d14d59926ca60471f10e6b7b2f150ce2bfc105b7 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/Utils.java +++ b/src/share/classes/com/sun/java/util/jar/pack/Utils.java @@ -25,18 +25,27 @@ package com.sun.java.util.jar.pack; -import com.sun.java.util.jar.pack.Attribute.Layout; import com.sun.java.util.jar.pack.ConstantPool.ClassEntry; import com.sun.java.util.jar.pack.ConstantPool.DescriptorEntry; import com.sun.java.util.jar.pack.ConstantPool.LiteralEntry; import com.sun.java.util.jar.pack.ConstantPool.MemberEntry; import com.sun.java.util.jar.pack.ConstantPool.SignatureEntry; import com.sun.java.util.jar.pack.ConstantPool.Utf8Entry; -import java.util.*; -import java.util.jar.*; -import java.util.zip.*; -import java.io.*; - +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Date; +import java.util.Enumeration; +import java.util.Map; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarInputStream; +import java.util.jar.JarOutputStream; +import java.util.zip.ZipEntry; import sun.util.logging.PlatformLogger; class Utils { diff --git a/src/share/classes/com/sun/jndi/ldap/BasicControl.java b/src/share/classes/com/sun/jndi/ldap/BasicControl.java index ebe745d49452ae02fd1a8fcdf8098dfbc38e1874..d068704142a2d588a9fa3879e1e2715176e47837 100644 --- a/src/share/classes/com/sun/jndi/ldap/BasicControl.java +++ b/src/share/classes/com/sun/jndi/ldap/BasicControl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -113,6 +113,6 @@ public class BasicControl implements Control { * ASN.1 BER encoded value. */ public byte[] getEncodedValue() { - return value; + return value == null ? null : value.clone(); } } diff --git a/src/share/classes/com/sun/jndi/ldap/Filter.java b/src/share/classes/com/sun/jndi/ldap/Filter.java index 626f1f86f9540ed741924a764bf764dddd163868..467b8db9065dd6c78f5d2340cc165daacfea891d 100644 --- a/src/share/classes/com/sun/jndi/ldap/Filter.java +++ b/src/share/classes/com/sun/jndi/ldap/Filter.java @@ -427,7 +427,10 @@ final class Filter { } } else { // descriptor - if (filter[i] != '-' && + // The underscore ("_") character is not allowed by + // the LDAP specification. We allow it here to + // tolerate the incorrect use in practice. + if (filter[i] != '-' && filter[i] != '_' && !(filter[i] >= '0' && filter[i] <= '9') && !(filter[i] >= 'A' && filter[i] <= 'Z') && !(filter[i] >= 'a' && filter[i] <= 'z')) { @@ -467,7 +470,10 @@ final class Filter { break; } - if (filter[i] != '-' && + // The underscore ("_") character is not allowed by + // the LDAP specification. We allow it here to + // tolerate the incorrect use in practice. + if (filter[i] != '-' && filter[i] != '_' && !(filter[i] >= '0' && filter[i] <= '9') && !(filter[i] >= 'A' && filter[i] <= 'Z') && !(filter[i] >= 'a' && filter[i] <= 'z')) { @@ -515,7 +521,10 @@ final class Filter { } } else { // descriptor - if (filter[j] != '-' && + // The underscore ("_") character is not allowed by + // the LDAP specification. We allow it here to + // tolerate the incorrect use in practice. + if (filter[j] != '-' && filter[j] != '_' && !(filter[j] >= '0' && filter[j] <= '9') && !(filter[j] >= 'A' && filter[j] <= 'Z') && !(filter[j] >= 'a' && filter[j] <= 'z')) { diff --git a/src/share/classes/com/sun/security/auth/module/NTSystem.java b/src/share/classes/com/sun/security/auth/module/NTSystem.java index 82cdd853106c9f2885c4094c1d51576994989788..5ed6c357df1f278bead5acaeeb5db600b3450062 100644 --- a/src/share/classes/com/sun/security/auth/module/NTSystem.java +++ b/src/share/classes/com/sun/security/auth/module/NTSystem.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. * 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,8 +25,6 @@ package com.sun.security.auth.module; -import javax.security.auth.login.LoginException; - /** *

This class implementation retrieves and makes available NT * security information for the current user. @@ -124,7 +122,7 @@ public class NTSystem { * @return the group SIDs for the current NT user. */ public String[] getGroupIDs() { - return groupIDs; + return groupIDs == null ? null : groupIDs.clone(); } /** diff --git a/src/share/classes/com/sun/security/auth/module/SolarisSystem.java b/src/share/classes/com/sun/security/auth/module/SolarisSystem.java index 028b80a1312b865293024c923629e25874ea3350..622671bd3fbb30ff3c2df15b5e300b552ce1d75c 100644 --- a/src/share/classes/com/sun/security/auth/module/SolarisSystem.java +++ b/src/share/classes/com/sun/security/auth/module/SolarisSystem.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. * 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,9 +25,6 @@ package com.sun.security.auth.module; -import javax.security.auth.*; -import javax.security.auth.login.*; - /** *

This class implementation retrieves and makes available Solaris * UID/GID/groups information for the current user. @@ -92,6 +89,6 @@ public class SolarisSystem { * @return the supplementary groups for the current Solaris user. */ public long[] getGroups() { - return groups; + return groups == null ? null : groups.clone(); } } diff --git a/src/share/classes/com/sun/security/auth/module/UnixSystem.java b/src/share/classes/com/sun/security/auth/module/UnixSystem.java index d000cc8007d50fe4699966791d54c9ea7a08f01b..b902cc9e36af1334fab0dbe1a63e696f13592b5f 100644 --- a/src/share/classes/com/sun/security/auth/module/UnixSystem.java +++ b/src/share/classes/com/sun/security/auth/module/UnixSystem.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. * 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,9 +25,6 @@ package com.sun.security.auth.module; -import javax.security.auth.*; -import javax.security.auth.login.*; - /** *

This class implementation retrieves and makes available Unix * UID/GID/groups information for the current user. @@ -92,6 +89,6 @@ public class UnixSystem { * @return the supplementary groups for the current Unix user. */ public long[] getGroups() { - return groups; + return groups == null ? null : groups.clone(); } } diff --git a/src/share/classes/java/awt/Component.java b/src/share/classes/java/awt/Component.java index f8bdac15d408678cc4dc03a70c69de30c6aa8270..cff463b3526c0d7eadf1ddabfdc061189f3faf23 100644 --- a/src/share/classes/java/awt/Component.java +++ b/src/share/classes/java/awt/Component.java @@ -2154,6 +2154,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * * @param d the dimension specifying the new size * of this component + * @throws NullPointerException if {@code d} is {@code null} * @see #setSize * @see #setBounds * @see #invalidate @@ -2351,6 +2352,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * invalidates the component hierarchy. * * @param r the new bounding rectangle for this component + * @throws NullPointerException if {@code r} is {@code null} * @see #getBounds * @see #setLocation(int, int) * @see #setLocation(Point) @@ -4545,6 +4547,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * where the point's x and y coordinates are defined * to be relative to the coordinate system of this component. * @param p the point + * @throws NullPointerException if {@code p} is {@code null} * @see #getComponentAt(Point) * @since JDK1.1 */ @@ -5879,7 +5882,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * @exception ClassCastException if listenerType * doesn't specify a class or interface that implements * java.util.EventListener - * + * @throws NullPointerException if {@code listenerType} is {@code null} * @see #getComponentListeners * @see #getFocusListeners * @see #getHierarchyListeners @@ -8038,6 +8041,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * Prints a listing of this component to the specified output * stream. * @param out a print stream + * @throws NullPointerException if {@code out} is {@code null} * @since JDK1.0 */ public void list(PrintStream out) { @@ -8050,6 +8054,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * @param out a print stream * @param indent number of spaces to indent * @see java.io.PrintStream#println(java.lang.Object) + * @throws NullPointerException if {@code out} is {@code null} * @since JDK1.0 */ public void list(PrintStream out, int indent) { @@ -8062,6 +8067,7 @@ public abstract class Component implements ImageObserver, MenuContainer, /** * Prints a listing to the specified print writer. * @param out the print writer to print to + * @throws NullPointerException if {@code out} is {@code null} * @since JDK1.1 */ public void list(PrintWriter out) { @@ -8073,6 +8079,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * the specified print writer. * @param out the print writer to print to * @param indent the number of spaces to indent + * @throws NullPointerException if {@code out} is {@code null} * @see java.io.PrintStream#println(java.lang.Object) * @since JDK1.1 */ diff --git a/src/share/classes/java/awt/Container.java b/src/share/classes/java/awt/Container.java index bf635fd45acd364b4e9298ee55f93d9c4307d2c1..a7ee77e16cbf5a711e34256fade7a0d46796b97e 100644 --- a/src/share/classes/java/awt/Container.java +++ b/src/share/classes/java/awt/Container.java @@ -1231,6 +1231,7 @@ public class Container extends Component { * reflect the changes. * * @param comp the component to be removed + * @throws NullPointerException if {@code comp} is {@code null} * @see #add * @see #invalidate * @see #validate @@ -2154,6 +2155,7 @@ public class Container extends Component { * @exception ClassCastException if listenerType * doesn't specify a class or interface that implements * java.util.EventListener + * @exception NullPointerException if {@code listenerType} is {@code null} * * @see #getContainerListeners * @@ -2705,6 +2707,7 @@ public class Container extends Component { * If there is no child component at the requested point and the * point is within the bounds of the container the container itself * is returned. + * @throws NullPointerException if {@code p} is {@code null} * @see Component#contains * @see #getComponentAt * @since 1.2 @@ -2969,6 +2972,7 @@ public class Container extends Component { * * @param out a print stream * @param indent the number of spaces to indent + * @throws NullPointerException if {@code out} is {@code null} * @see Component#list(java.io.PrintStream, int) * @since JDK1.0 */ @@ -2995,6 +2999,7 @@ public class Container extends Component { * * @param out a print writer * @param indent the number of spaces to indent + * @throws NullPointerException if {@code out} is {@code null} * @see Component#list(java.io.PrintWriter, int) * @since JDK1.1 */ diff --git a/src/share/classes/java/awt/ScrollPane.java b/src/share/classes/java/awt/ScrollPane.java index 6a06acb5403bc6d4cb96bda60b8e6919c32cd55a..104318abf6f292f7b2c05ec014accca1e612b484 100644 --- a/src/share/classes/java/awt/ScrollPane.java +++ b/src/share/classes/java/awt/ScrollPane.java @@ -377,6 +377,7 @@ public class ScrollPane extends Container implements Accessible { * This is a convenience method which interfaces with the Adjustable * objects which represent the state of the scrollbars. * @param p the Point representing the position to scroll to + * @throws NullPointerException if {@code p} is {@code null} */ public void setScrollPosition(Point p) { setScrollPosition(p.x, p.y); diff --git a/src/share/classes/java/awt/Window.java b/src/share/classes/java/awt/Window.java index 7dce80e9564de856c0cab5f1bfddfee284375171..03dbd535e9f0d5f146c83ba2ad6247399096e1e6 100644 --- a/src/share/classes/java/awt/Window.java +++ b/src/share/classes/java/awt/Window.java @@ -1888,6 +1888,7 @@ public class Window extends Container implements Accessible { * @exception ClassCastException if listenerType * doesn't specify a class or interface that implements * java.util.EventListener + * @exception NullPointerException if {@code listenerType} is {@code null} * * @see #getWindowListeners * @since 1.3 diff --git a/src/share/classes/java/io/FileOutputStream.java b/src/share/classes/java/io/FileOutputStream.java index 71bdee89f3b148384e6b87530d446559b83a32d7..70f6851d7326bad52313067151657171ab7a386e 100644 --- a/src/share/classes/java/io/FileOutputStream.java +++ b/src/share/classes/java/io/FileOutputStream.java @@ -56,7 +56,15 @@ class FileOutputStream extends OutputStream */ private final FileDescriptor fd; - private FileChannel channel= null; + /** + * True if the file is opened for append. + */ + private final boolean append; + + /** + * The associated channel, initalized lazily. + */ + private FileChannel channel; private final Object closeLock = new Object(); private volatile boolean closed = false; @@ -196,7 +204,9 @@ class FileOutputStream extends OutputStream if (name == null) { throw new NullPointerException(); } - fd = new FileDescriptor(); + this.fd = new FileDescriptor(); + this.append = append; + fd.incrementAndGetUseCount(); open(name, append); } @@ -232,7 +242,8 @@ class FileOutputStream extends OutputStream if (security != null) { security.checkWrite(fdObj); } - fd = fdObj; + this.fd = fdObj; + this.append = false; /* * FileDescriptor is being shared by streams. @@ -250,6 +261,15 @@ class FileOutputStream extends OutputStream private native void open(String name, boolean append) throws FileNotFoundException; + /** + * Writes the specified byte to this file output stream. + * + * @param b the byte to be written. + * @param append {@code true} if the write operation first + * advances the position to the end of file + */ + private native void write(int b, boolean append) throws IOException; + /** * Writes the specified byte to this file output stream. Implements * the write method of OutputStream. @@ -257,16 +277,21 @@ class FileOutputStream extends OutputStream * @param b the byte to be written. * @exception IOException if an I/O error occurs. */ - public native void write(int b) throws IOException; + public void write(int b) throws IOException { + write(b, append); + } /** * Writes a sub array as a sequence of bytes. * @param b the data to be written * @param off the start offset in the data * @param len the number of bytes that are written + * @param append {@code true} to first advance the position to the + * end of file * @exception IOException If an I/O error has occurred. */ - private native void writeBytes(byte b[], int off, int len) throws IOException; + private native void writeBytes(byte b[], int off, int len, boolean append) + throws IOException; /** * Writes b.length bytes from the specified byte array @@ -276,7 +301,7 @@ class FileOutputStream extends OutputStream * @exception IOException if an I/O error occurs. */ public void write(byte b[]) throws IOException { - writeBytes(b, 0, b.length); + writeBytes(b, 0, b.length, append); } /** @@ -289,7 +314,7 @@ class FileOutputStream extends OutputStream * @exception IOException if an I/O error occurs. */ public void write(byte b[], int off, int len) throws IOException { - writeBytes(b, off, len); + writeBytes(b, off, len, append); } /** @@ -372,7 +397,7 @@ class FileOutputStream extends OutputStream public FileChannel getChannel() { synchronized (this) { if (channel == null) { - channel = FileChannelImpl.open(fd, false, true, this); + channel = FileChannelImpl.open(fd, false, true, append, this); /* * Increment fd's use count. Invoking the channel's close() diff --git a/src/share/classes/java/io/ObjectInputStream.java b/src/share/classes/java/io/ObjectInputStream.java index 2ed505f3b07c6cd940bb632037e8e854f9cf4cd9..3ec3cd4fbdc763057db8b6ee4366ffd389164305 100644 --- a/src/share/classes/java/io/ObjectInputStream.java +++ b/src/share/classes/java/io/ObjectInputStream.java @@ -3498,8 +3498,8 @@ public class ObjectInputStream return ((int[]) array).clone(); } else if (array instanceof long[]) { return ((long[]) array).clone(); - } else if (array instanceof double[]) { - return ((double[]) array).clone(); + } else if (array instanceof short[]) { + return ((short[]) array).clone(); } else { throw new AssertionError(); } diff --git a/src/share/classes/java/lang/Double.java b/src/share/classes/java/lang/Double.java index ab732d3851be4df667481ab6908d378b8212b745..2957f0b541db044ad3a7852548667fbc8dde3595 100644 --- a/src/share/classes/java/lang/Double.java +++ b/src/share/classes/java/lang/Double.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1994, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -973,7 +973,8 @@ public final class Double extends Number implements Comparable { if (d1 > d2) return 1; // Neither val is NaN, thisVal is larger - long thisBits = Double.doubleToLongBits(d1); + // Cannot use doubleToRawLongBits because of possibility of NaNs. + long thisBits = Double.doubleToLongBits(d1); long anotherBits = Double.doubleToLongBits(d2); return (thisBits == anotherBits ? 0 : // Values are equal diff --git a/src/share/classes/java/lang/Float.java b/src/share/classes/java/lang/Float.java index acd96d38e4423b3adf1bb8a7fa7d8da0378efd00..f725def1d0affcb8ac31fa0f5da224648d4814e6 100644 --- a/src/share/classes/java/lang/Float.java +++ b/src/share/classes/java/lang/Float.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1994, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -872,12 +872,13 @@ public final class Float extends Number implements Comparable { * @since 1.4 */ public static int compare(float f1, float f2) { - if (f1 < f2) + if (f1 < f2) return -1; // Neither val is NaN, thisVal is smaller if (f1 > f2) return 1; // Neither val is NaN, thisVal is larger - int thisBits = Float.floatToIntBits(f1); + // Cannot use floatToRawIntBits because of possibility of NaNs. + int thisBits = Float.floatToIntBits(f1); int anotherBits = Float.floatToIntBits(f2); return (thisBits == anotherBits ? 0 : // Values are equal diff --git a/src/share/classes/java/lang/ProcessBuilder.java b/src/share/classes/java/lang/ProcessBuilder.java index 97ce45cdf658eccb2d0e29119d4c82c98cae0c40..ebc372380bba446f4817dd88bbec61fb4e8d79c5 100644 --- a/src/share/classes/java/lang/ProcessBuilder.java +++ b/src/share/classes/java/lang/ProcessBuilder.java @@ -537,7 +537,11 @@ public final class ProcessBuilder */ public File file() { return null; } - FileOutputStream toFileOutputStream() throws IOException { + /** + * When redirected to a destination file, indicates if the output + * is to be written to the end of the file. + */ + boolean append() { throw new UnsupportedOperationException(); } @@ -588,9 +592,7 @@ public final class ProcessBuilder public String toString() { return "redirect to write to file \"" + file + "\""; } - FileOutputStream toFileOutputStream() throws IOException { - return new FileOutputStream(file, false); - } + boolean append() { return false; } }; } @@ -620,9 +622,7 @@ public final class ProcessBuilder public String toString() { return "redirect to append to file \"" + file + "\""; } - FileOutputStream toFileOutputStream() throws IOException { - return new FileOutputStream(file, true); - } + boolean append() { return true; } }; } diff --git a/src/share/classes/java/lang/StrictMath.java b/src/share/classes/java/lang/StrictMath.java index 916b82ff9d043e30076d0063fe783d7d68d6f3e4..56be3c5f17abeb912339cc4361a6abb7fecfc3f2 100644 --- a/src/share/classes/java/lang/StrictMath.java +++ b/src/share/classes/java/lang/StrictMath.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -801,8 +801,9 @@ public final class StrictMath { return (a >= b) ? a : b; } - private static long negativeZeroFloatBits = Float.floatToIntBits(-0.0f); - private static long negativeZeroDoubleBits = Double.doubleToLongBits(-0.0d); + // Use raw bit-wise conversions on guaranteed non-NaN arguments. + private static long negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f); + private static long negativeZeroDoubleBits = Double.doubleToRawLongBits(-0.0d); /** * Returns the greater of two {@code float} values. That is, @@ -819,9 +820,12 @@ public final class StrictMath { * @return the larger of {@code a} and {@code b}. */ public static float max(float a, float b) { - if (a != a) return a; // a is NaN - if ((a == 0.0f) && (b == 0.0f) - && (Float.floatToIntBits(a) == negativeZeroFloatBits)) { + if (a != a) + return a; // a is NaN + if ((a == 0.0f) && + (b == 0.0f) && + (Float.floatToRawIntBits(a) == negativeZeroFloatBits)) { + // Raw conversion ok since NaN can't map to -0.0. return b; } return (a >= b) ? a : b; @@ -842,9 +846,12 @@ public final class StrictMath { * @return the larger of {@code a} and {@code b}. */ public static double max(double a, double b) { - if (a != a) return a; // a is NaN - if ((a == 0.0d) && (b == 0.0d) - && (Double.doubleToLongBits(a) == negativeZeroDoubleBits)) { + if (a != a) + return a; // a is NaN + if ((a == 0.0d) && + (b == 0.0d) && + (Double.doubleToRawLongBits(a) == negativeZeroDoubleBits)) { + // Raw conversion ok since NaN can't map to -0.0. return b; } return (a >= b) ? a : b; @@ -893,9 +900,12 @@ public final class StrictMath { * @return the smaller of {@code a} and {@code b.} */ public static float min(float a, float b) { - if (a != a) return a; // a is NaN - if ((a == 0.0f) && (b == 0.0f) - && (Float.floatToIntBits(b) == negativeZeroFloatBits)) { + if (a != a) + return a; // a is NaN + if ((a == 0.0f) && + (b == 0.0f) && + (Float.floatToRawIntBits(b) == negativeZeroFloatBits)) { + // Raw conversion ok since NaN can't map to -0.0. return b; } return (a <= b) ? a : b; @@ -916,9 +926,12 @@ public final class StrictMath { * @return the smaller of {@code a} and {@code b}. */ public static double min(double a, double b) { - if (a != a) return a; // a is NaN - if ((a == 0.0d) && (b == 0.0d) - && (Double.doubleToLongBits(b) == negativeZeroDoubleBits)) { + if (a != a) + return a; // a is NaN + if ((a == 0.0d) && + (b == 0.0d) && + (Double.doubleToRawLongBits(b) == negativeZeroDoubleBits)) { + // Raw conversion ok since NaN can't map to -0.0. return b; } return (a <= b) ? a : b; diff --git a/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java b/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java index d37bd2efc463d7750a37dd4ddb14c972e55802ca..6d04f4f52a2a74309bb8eeb4d88435f566c30772 100644 --- a/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java +++ b/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java @@ -110,7 +110,8 @@ import java.nio.ByteBuffer; * state of the {@link ByteBuffer}, or the sequence of buffers, for the I/O * operation is not defined. Buffers should be discarded or at least care must * be taken to ensure that the buffers are not accessed while the channel remains - * open. + * open. All methods that accept timeout parameters treat values less than or + * equal to zero to mean that the I/O operation does not timeout. * * @since 1.7 */ @@ -367,7 +368,7 @@ public abstract class AsynchronousSocketChannel * @param dst * The buffer into which bytes are to be transferred * @param timeout - * The timeout, or {@code 0L} for no timeout + * The maximum time for the I/O operation to complete * @param unit * The time unit of the {@code timeout} argument * @param attachment @@ -376,8 +377,7 @@ public abstract class AsynchronousSocketChannel * The handler for consuming the result * * @throws IllegalArgumentException - * If the {@code timeout} parameter is negative or the buffer is - * read-only + * If the buffer is read-only * @throws ReadPendingException * If a read operation is already in progress on this channel * @throws NotYetConnectedException @@ -471,7 +471,7 @@ public abstract class AsynchronousSocketChannel * The maximum number of buffers to be accessed; must be non-negative * and no larger than {@code dsts.length - offset} * @param timeout - * The timeout, or {@code 0L} for no timeout + * The maximum time for the I/O operation to complete * @param unit * The time unit of the {@code timeout} argument * @param attachment @@ -483,8 +483,7 @@ public abstract class AsynchronousSocketChannel * If the pre-conditions for the {@code offset} and {@code length} * parameter aren't met * @throws IllegalArgumentException - * If the {@code timeout} parameter is negative, or a buffer is - * read-only + * If the buffer is read-only * @throws ReadPendingException * If a read operation is already in progress on this channel * @throws NotYetConnectedException @@ -524,7 +523,7 @@ public abstract class AsynchronousSocketChannel * @param src * The buffer from which bytes are to be retrieved * @param timeout - * The timeout, or {@code 0L} for no timeout + * The maximum time for the I/O operation to complete * @param unit * The time unit of the {@code timeout} argument * @param attachment @@ -532,8 +531,6 @@ public abstract class AsynchronousSocketChannel * @param handler * The handler for consuming the result * - * @throws IllegalArgumentException - * If the {@code timeout} parameter is negative * @throws WritePendingException * If a write operation is already in progress on this channel * @throws NotYetConnectedException @@ -623,7 +620,7 @@ public abstract class AsynchronousSocketChannel * The maximum number of buffers to be accessed; must be non-negative * and no larger than {@code srcs.length - offset} * @param timeout - * The timeout, or {@code 0L} for no timeout + * The maximum time for the I/O operation to complete * @param unit * The time unit of the {@code timeout} argument * @param attachment @@ -634,8 +631,6 @@ public abstract class AsynchronousSocketChannel * @throws IndexOutOfBoundsException * If the pre-conditions for the {@code offset} and {@code length} * parameter aren't met - * @throws IllegalArgumentException - * If the {@code timeout} parameter is negative * @throws WritePendingException * If a write operation is already in progress on this channel * @throws NotYetConnectedException diff --git a/src/share/classes/java/security/Timestamp.java b/src/share/classes/java/security/Timestamp.java index 33d7b4a30c3a06c3ef0b0fee62642cd2c274a99a..f9bb77cd19db3016211a38cd7cfa29b04e663ac1 100644 --- a/src/share/classes/java/security/Timestamp.java +++ b/src/share/classes/java/security/Timestamp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. * 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,9 +26,11 @@ package java.security; import java.io.Serializable; +import java.security.cert.Certificate; import java.security.cert.CertPath; import java.security.cert.X509Extension; import java.util.Date; +import java.util.List; /** * This class encapsulates information about a signed timestamp. @@ -142,7 +144,12 @@ public final class Timestamp implements Serializable { StringBuffer sb = new StringBuffer(); sb.append("("); sb.append("timestamp: " + timestamp); - sb.append("TSA: " + signerCertPath.getCertificates().get(0)); + List certs = signerCertPath.getCertificates(); + if (!certs.isEmpty()) { + sb.append("TSA: " + certs.get(0)); + } else { + sb.append("TSA: "); + } sb.append(")"); return sb.toString(); } diff --git a/src/share/classes/java/util/AbstractCollection.java b/src/share/classes/java/util/AbstractCollection.java index 427f42739b227eeca4b11e6b48503261240ac211..9b675d756e6d86b0120e5d399ca19ed4049d271f 100644 --- a/src/share/classes/java/util/AbstractCollection.java +++ b/src/share/classes/java/util/AbstractCollection.java @@ -96,14 +96,14 @@ public abstract class AbstractCollection implements Collection { * @throws NullPointerException {@inheritDoc} */ public boolean contains(Object o) { - Iterator e = iterator(); + Iterator it = iterator(); if (o==null) { - while (e.hasNext()) - if (e.next()==null) + while (it.hasNext()) + if (it.next()==null) return true; } else { - while (e.hasNext()) - if (o.equals(e.next())) + while (it.hasNext()) + if (o.equals(it.next())) return true; } return false; @@ -269,18 +269,18 @@ public abstract class AbstractCollection implements Collection { * @throws NullPointerException {@inheritDoc} */ public boolean remove(Object o) { - Iterator e = iterator(); + Iterator it = iterator(); if (o==null) { - while (e.hasNext()) { - if (e.next()==null) { - e.remove(); + while (it.hasNext()) { + if (it.next()==null) { + it.remove(); return true; } } } else { - while (e.hasNext()) { - if (o.equals(e.next())) { - e.remove(); + while (it.hasNext()) { + if (o.equals(it.next())) { + it.remove(); return true; } } @@ -304,9 +304,8 @@ public abstract class AbstractCollection implements Collection { * @see #contains(Object) */ public boolean containsAll(Collection c) { - Iterator e = c.iterator(); - while (e.hasNext()) - if (!contains(e.next())) + for (Object e : c) + if (!contains(e)) return false; return true; } @@ -331,11 +330,9 @@ public abstract class AbstractCollection implements Collection { */ public boolean addAll(Collection c) { boolean modified = false; - Iterator e = c.iterator(); - while (e.hasNext()) { - if (add(e.next())) + for (E e : c) + if (add(e)) modified = true; - } return modified; } @@ -362,10 +359,10 @@ public abstract class AbstractCollection implements Collection { */ public boolean removeAll(Collection c) { boolean modified = false; - Iterator e = iterator(); - while (e.hasNext()) { - if (c.contains(e.next())) { - e.remove(); + Iterator it = iterator(); + while (it.hasNext()) { + if (c.contains(it.next())) { + it.remove(); modified = true; } } @@ -395,10 +392,10 @@ public abstract class AbstractCollection implements Collection { */ public boolean retainAll(Collection c) { boolean modified = false; - Iterator e = iterator(); - while (e.hasNext()) { - if (!c.contains(e.next())) { - e.remove(); + Iterator it = iterator(); + while (it.hasNext()) { + if (!c.contains(it.next())) { + it.remove(); modified = true; } } @@ -421,10 +418,10 @@ public abstract class AbstractCollection implements Collection { * @throws UnsupportedOperationException {@inheritDoc} */ public void clear() { - Iterator e = iterator(); - while (e.hasNext()) { - e.next(); - e.remove(); + Iterator it = iterator(); + while (it.hasNext()) { + it.next(); + it.remove(); } } @@ -442,18 +439,18 @@ public abstract class AbstractCollection implements Collection { * @return a string representation of this collection */ public String toString() { - Iterator i = iterator(); - if (! i.hasNext()) + Iterator it = iterator(); + if (! it.hasNext()) return "[]"; StringBuilder sb = new StringBuilder(); sb.append('['); for (;;) { - E e = i.next(); + E e = it.next(); sb.append(e == this ? "(this Collection)" : e); - if (! i.hasNext()) + if (! it.hasNext()) return sb.append(']').toString(); - sb.append(", "); + sb.append(',').append(' '); } } diff --git a/src/share/classes/java/util/AbstractList.java b/src/share/classes/java/util/AbstractList.java index c0304df1561b6ef0d3f3b228100c5a3b2d30efd4..9752de1d08f027480eebecfced1c50ece40fd20e 100644 --- a/src/share/classes/java/util/AbstractList.java +++ b/src/share/classes/java/util/AbstractList.java @@ -175,15 +175,15 @@ public abstract class AbstractList extends AbstractCollection implements L * @throws NullPointerException {@inheritDoc} */ public int indexOf(Object o) { - ListIterator e = listIterator(); + ListIterator it = listIterator(); if (o==null) { - while (e.hasNext()) - if (e.next()==null) - return e.previousIndex(); + while (it.hasNext()) + if (it.next()==null) + return it.previousIndex(); } else { - while (e.hasNext()) - if (o.equals(e.next())) - return e.previousIndex(); + while (it.hasNext()) + if (o.equals(it.next())) + return it.previousIndex(); } return -1; } @@ -200,15 +200,15 @@ public abstract class AbstractList extends AbstractCollection implements L * @throws NullPointerException {@inheritDoc} */ public int lastIndexOf(Object o) { - ListIterator e = listIterator(size()); + ListIterator it = listIterator(size()); if (o==null) { - while (e.hasPrevious()) - if (e.previous()==null) - return e.nextIndex(); + while (it.hasPrevious()) + if (it.previous()==null) + return it.nextIndex(); } else { - while (e.hasPrevious()) - if (o.equals(e.previous())) - return e.nextIndex(); + while (it.hasPrevious()) + if (o.equals(it.previous())) + return it.nextIndex(); } return -1; } @@ -517,7 +517,7 @@ public abstract class AbstractList extends AbstractCollection implements L ListIterator e1 = listIterator(); ListIterator e2 = ((List) o).listIterator(); - while(e1.hasNext() && e2.hasNext()) { + while (e1.hasNext() && e2.hasNext()) { E o1 = e1.next(); Object o2 = e2.next(); if (!(o1==null ? o2==null : o1.equals(o2))) diff --git a/src/share/classes/java/util/AbstractMap.java b/src/share/classes/java/util/AbstractMap.java index 43c801a8093ece3e3d890677a9c164a03de37b5f..431313e8ff4b3ba4a259a67159743dbf5d09415f 100644 --- a/src/share/classes/java/util/AbstractMap.java +++ b/src/share/classes/java/util/AbstractMap.java @@ -523,7 +523,7 @@ public abstract class AbstractMap implements Map { sb.append(value == this ? "(this Map)" : value); if (! i.hasNext()) return sb.append('}').toString(); - sb.append(", "); + sb.append(',').append(' '); } } diff --git a/src/share/classes/java/util/ArrayList.java b/src/share/classes/java/util/ArrayList.java index 7c6eded3a830094f02f422bb6a2945e3c4efc494..45ca44296ca42882b6ef7268a6ca7d27b07cb1b9 100644 --- a/src/share/classes/java/util/ArrayList.java +++ b/src/share/classes/java/util/ArrayList.java @@ -120,9 +120,9 @@ public class ArrayList extends AbstractList /** * Constructs an empty list with the specified initial capacity. * - * @param initialCapacity the initial capacity of the list - * @exception IllegalArgumentException if the specified initial capacity - * is negative + * @param initialCapacity the initial capacity of the list + * @throws IllegalArgumentException if the specified initial capacity + * is negative */ public ArrayList(int initialCapacity) { super(); @@ -173,7 +173,7 @@ public class ArrayList extends AbstractList * necessary, to ensure that it can hold at least the number of elements * specified by the minimum capacity argument. * - * @param minCapacity the desired minimum capacity + * @param minCapacity the desired minimum capacity */ public void ensureCapacity(int minCapacity) { if (minCapacity > 0) diff --git a/src/share/classes/java/util/Collections.java b/src/share/classes/java/util/Collections.java index e4329dc0e43d83295acf48d6918aa927aae94af8..c5d8476c8a35613fe4ec4f6bc3991a667861335d 100644 --- a/src/share/classes/java/util/Collections.java +++ b/src/share/classes/java/util/Collections.java @@ -124,7 +124,7 @@ public class Collections { * *

The implementation takes equal advantage of ascending and * descending order in its input array, and can take advantage of - * ascending and descending order in different parts of the the same + * ascending and descending order in different parts of the same * input array. It is well-suited to merging two or more sorted arrays: * simply concatenate the arrays and sort the resulting array. * @@ -184,7 +184,7 @@ public class Collections { * *

The implementation takes equal advantage of ascending and * descending order in its input array, and can take advantage of - * ascending and descending order in different parts of the the same + * ascending and descending order in different parts of the same * input array. It is well-suited to merging two or more sorted arrays: * simply concatenate the arrays and sort the resulting array. * @@ -823,7 +823,7 @@ public class Collections { i -= size; displaced = list.set(i, displaced); nMoved ++; - } while(i != cycleStart); + } while (i != cycleStart); } } @@ -1452,9 +1452,9 @@ public class Collections { * when o is a Map.Entry, and calls o.setValue. */ public boolean containsAll(Collection coll) { - Iterator e = coll.iterator(); - while (e.hasNext()) - if (!contains(e.next())) // Invokes safe contains() above + Iterator it = coll.iterator(); + while (it.hasNext()) + if (!contains(it.next())) // Invokes safe contains() above return false; return true; } @@ -1482,12 +1482,12 @@ public class Collections { UnmodifiableEntry(Map.Entry e) {this.e = e;} - public K getKey() {return e.getKey();} - public V getValue() {return e.getValue();} + public K getKey() {return e.getKey();} + public V getValue() {return e.getValue();} public V setValue(V value) { throw new UnsupportedOperationException(); } - public int hashCode() {return e.hashCode();} + public int hashCode() {return e.hashCode();} public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; @@ -1495,7 +1495,7 @@ public class Collections { return eq(e.getKey(), t.getKey()) && eq(e.getValue(), t.getValue()); } - public String toString() {return e.toString();} + public String toString() {return e.toString();} } } } @@ -1562,7 +1562,7 @@ public class Collections { *

      *  Collection c = Collections.synchronizedCollection(myCollection);
      *     ...
-     *  synchronized(c) {
+     *  synchronized (c) {
      *      Iterator i = c.iterator(); // Must be in the synchronized block
      *      while (i.hasNext())
      *         foo(i.next());
@@ -1611,19 +1611,19 @@ public class Collections {
         }
 
         public int size() {
-            synchronized(mutex) {return c.size();}
+            synchronized (mutex) {return c.size();}
         }
         public boolean isEmpty() {
-            synchronized(mutex) {return c.isEmpty();}
+            synchronized (mutex) {return c.isEmpty();}
         }
         public boolean contains(Object o) {
-            synchronized(mutex) {return c.contains(o);}
+            synchronized (mutex) {return c.contains(o);}
         }
         public Object[] toArray() {
-            synchronized(mutex) {return c.toArray();}
+            synchronized (mutex) {return c.toArray();}
         }
         public  T[] toArray(T[] a) {
-            synchronized(mutex) {return c.toArray(a);}
+            synchronized (mutex) {return c.toArray(a);}
         }
 
         public Iterator iterator() {
@@ -1631,32 +1631,32 @@ public class Collections {
         }
 
         public boolean add(E e) {
-            synchronized(mutex) {return c.add(e);}
+            synchronized (mutex) {return c.add(e);}
         }
         public boolean remove(Object o) {
-            synchronized(mutex) {return c.remove(o);}
+            synchronized (mutex) {return c.remove(o);}
         }
 
         public boolean containsAll(Collection coll) {
-            synchronized(mutex) {return c.containsAll(coll);}
+            synchronized (mutex) {return c.containsAll(coll);}
         }
         public boolean addAll(Collection coll) {
-            synchronized(mutex) {return c.addAll(coll);}
+            synchronized (mutex) {return c.addAll(coll);}
         }
         public boolean removeAll(Collection coll) {
-            synchronized(mutex) {return c.removeAll(coll);}
+            synchronized (mutex) {return c.removeAll(coll);}
         }
         public boolean retainAll(Collection coll) {
-            synchronized(mutex) {return c.retainAll(coll);}
+            synchronized (mutex) {return c.retainAll(coll);}
         }
         public void clear() {
-            synchronized(mutex) {c.clear();}
+            synchronized (mutex) {c.clear();}
         }
         public String toString() {
-            synchronized(mutex) {return c.toString();}
+            synchronized (mutex) {return c.toString();}
         }
         private void writeObject(ObjectOutputStream s) throws IOException {
-            synchronized(mutex) {s.defaultWriteObject();}
+            synchronized (mutex) {s.defaultWriteObject();}
         }
     }
 
@@ -1671,7 +1671,7 @@ public class Collections {
      * 
      *  Set s = Collections.synchronizedSet(new HashSet());
      *      ...
-     *  synchronized(s) {
+     *  synchronized (s) {
      *      Iterator i = s.iterator(); // Must be in the synchronized block
      *      while (i.hasNext())
      *          foo(i.next());
@@ -1709,10 +1709,10 @@ public class Collections {
         }
 
         public boolean equals(Object o) {
-            synchronized(mutex) {return c.equals(o);}
+            synchronized (mutex) {return c.equals(o);}
         }
         public int hashCode() {
-            synchronized(mutex) {return c.hashCode();}
+            synchronized (mutex) {return c.hashCode();}
         }
     }
 
@@ -1728,7 +1728,7 @@ public class Collections {
      * 
      *  SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
      *      ...
-     *  synchronized(s) {
+     *  synchronized (s) {
      *      Iterator i = s.iterator(); // Must be in the synchronized block
      *      while (i.hasNext())
      *          foo(i.next());
@@ -1739,7 +1739,7 @@ public class Collections {
      *  SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
      *  SortedSet s2 = s.headSet(foo);
      *      ...
-     *  synchronized(s) {  // Note: s, not s2!!!
+     *  synchronized (s) {  // Note: s, not s2!!!
      *      Iterator i = s2.iterator(); // Must be in the synchronized block
      *      while (i.hasNext())
      *          foo(i.next());
@@ -1766,7 +1766,7 @@ public class Collections {
     {
         private static final long serialVersionUID = 8695801310862127406L;
 
-        final private SortedSet ss;
+        private final SortedSet ss;
 
         SynchronizedSortedSet(SortedSet s) {
             super(s);
@@ -1778,31 +1778,31 @@ public class Collections {
         }
 
         public Comparator comparator() {
-            synchronized(mutex) {return ss.comparator();}
+            synchronized (mutex) {return ss.comparator();}
         }
 
         public SortedSet subSet(E fromElement, E toElement) {
-            synchronized(mutex) {
+            synchronized (mutex) {
                 return new SynchronizedSortedSet(
                     ss.subSet(fromElement, toElement), mutex);
             }
         }
         public SortedSet headSet(E toElement) {
-            synchronized(mutex) {
+            synchronized (mutex) {
                 return new SynchronizedSortedSet(ss.headSet(toElement), mutex);
             }
         }
         public SortedSet tailSet(E fromElement) {
-            synchronized(mutex) {
+            synchronized (mutex) {
                return new SynchronizedSortedSet(ss.tailSet(fromElement),mutex);
             }
         }
 
         public E first() {
-            synchronized(mutex) {return ss.first();}
+            synchronized (mutex) {return ss.first();}
         }
         public E last() {
-            synchronized(mutex) {return ss.last();}
+            synchronized (mutex) {return ss.last();}
         }
     }
 
@@ -1817,7 +1817,7 @@ public class Collections {
      * 
      *  List list = Collections.synchronizedList(new ArrayList());
      *      ...
-     *  synchronized(list) {
+     *  synchronized (list) {
      *      Iterator i = list.iterator(); // Must be in synchronized block
      *      while (i.hasNext())
      *          foo(i.next());
@@ -1863,34 +1863,34 @@ public class Collections {
         }
 
         public boolean equals(Object o) {
-            synchronized(mutex) {return list.equals(o);}
+            synchronized (mutex) {return list.equals(o);}
         }
         public int hashCode() {
-            synchronized(mutex) {return list.hashCode();}
+            synchronized (mutex) {return list.hashCode();}
         }
 
         public E get(int index) {
-            synchronized(mutex) {return list.get(index);}
+            synchronized (mutex) {return list.get(index);}
         }
         public E set(int index, E element) {
-            synchronized(mutex) {return list.set(index, element);}
+            synchronized (mutex) {return list.set(index, element);}
         }
         public void add(int index, E element) {
-            synchronized(mutex) {list.add(index, element);}
+            synchronized (mutex) {list.add(index, element);}
         }
         public E remove(int index) {
-            synchronized(mutex) {return list.remove(index);}
+            synchronized (mutex) {return list.remove(index);}
         }
 
         public int indexOf(Object o) {
-            synchronized(mutex) {return list.indexOf(o);}
+            synchronized (mutex) {return list.indexOf(o);}
         }
         public int lastIndexOf(Object o) {
-            synchronized(mutex) {return list.lastIndexOf(o);}
+            synchronized (mutex) {return list.lastIndexOf(o);}
         }
 
         public boolean addAll(int index, Collection c) {
-            synchronized(mutex) {return list.addAll(index, c);}
+            synchronized (mutex) {return list.addAll(index, c);}
         }
 
         public ListIterator listIterator() {
@@ -1902,7 +1902,7 @@ public class Collections {
         }
 
         public List subList(int fromIndex, int toIndex) {
-            synchronized(mutex) {
+            synchronized (mutex) {
                 return new SynchronizedList(list.subList(fromIndex, toIndex),
                                             mutex);
             }
@@ -1943,7 +1943,7 @@ public class Collections {
         }
 
         public List subList(int fromIndex, int toIndex) {
-            synchronized(mutex) {
+            synchronized (mutex) {
                 return new SynchronizedRandomAccessList(
                     list.subList(fromIndex, toIndex), mutex);
             }
@@ -1975,7 +1975,7 @@ public class Collections {
      *      ...
      *  Set s = m.keySet();  // Needn't be in synchronized block
      *      ...
-     *  synchronized(m) {  // Synchronizing on m, not s!
+     *  synchronized (m) {  // Synchronizing on m, not s!
      *      Iterator i = s.iterator(); // Must be in synchronized block
      *      while (i.hasNext())
      *          foo(i.next());
@@ -2016,32 +2016,32 @@ public class Collections {
         }
 
         public int size() {
-            synchronized(mutex) {return m.size();}
+            synchronized (mutex) {return m.size();}
         }
         public boolean isEmpty() {
-            synchronized(mutex) {return m.isEmpty();}
+            synchronized (mutex) {return m.isEmpty();}
         }
         public boolean containsKey(Object key) {
-            synchronized(mutex) {return m.containsKey(key);}
+            synchronized (mutex) {return m.containsKey(key);}
         }
         public boolean containsValue(Object value) {
-            synchronized(mutex) {return m.containsValue(value);}
+            synchronized (mutex) {return m.containsValue(value);}
         }
         public V get(Object key) {
-            synchronized(mutex) {return m.get(key);}
+            synchronized (mutex) {return m.get(key);}
         }
 
         public V put(K key, V value) {
-            synchronized(mutex) {return m.put(key, value);}
+            synchronized (mutex) {return m.put(key, value);}
         }
         public V remove(Object key) {
-            synchronized(mutex) {return m.remove(key);}
+            synchronized (mutex) {return m.remove(key);}
         }
         public void putAll(Map map) {
-            synchronized(mutex) {m.putAll(map);}
+            synchronized (mutex) {m.putAll(map);}
         }
         public void clear() {
-            synchronized(mutex) {m.clear();}
+            synchronized (mutex) {m.clear();}
         }
 
         private transient Set keySet = null;
@@ -2049,7 +2049,7 @@ public class Collections {
         private transient Collection values = null;
 
         public Set keySet() {
-            synchronized(mutex) {
+            synchronized (mutex) {
                 if (keySet==null)
                     keySet = new SynchronizedSet(m.keySet(), mutex);
                 return keySet;
@@ -2057,7 +2057,7 @@ public class Collections {
         }
 
         public Set> entrySet() {
-            synchronized(mutex) {
+            synchronized (mutex) {
                 if (entrySet==null)
                     entrySet = new SynchronizedSet>(m.entrySet(), mutex);
                 return entrySet;
@@ -2065,7 +2065,7 @@ public class Collections {
         }
 
         public Collection values() {
-            synchronized(mutex) {
+            synchronized (mutex) {
                 if (values==null)
                     values = new SynchronizedCollection(m.values(), mutex);
                 return values;
@@ -2073,16 +2073,16 @@ public class Collections {
         }
 
         public boolean equals(Object o) {
-            synchronized(mutex) {return m.equals(o);}
+            synchronized (mutex) {return m.equals(o);}
         }
         public int hashCode() {
-            synchronized(mutex) {return m.hashCode();}
+            synchronized (mutex) {return m.hashCode();}
         }
         public String toString() {
-            synchronized(mutex) {return m.toString();}
+            synchronized (mutex) {return m.toString();}
         }
         private void writeObject(ObjectOutputStream s) throws IOException {
-            synchronized(mutex) {s.defaultWriteObject();}
+            synchronized (mutex) {s.defaultWriteObject();}
         }
     }
 
@@ -2101,7 +2101,7 @@ public class Collections {
      *      ...
      *  Set s = m.keySet();  // Needn't be in synchronized block
      *      ...
-     *  synchronized(m) {  // Synchronizing on m, not s!
+     *  synchronized (m) {  // Synchronizing on m, not s!
      *      Iterator i = s.iterator(); // Must be in synchronized block
      *      while (i.hasNext())
      *          foo(i.next());
@@ -2114,7 +2114,7 @@ public class Collections {
      *      ...
      *  Set s2 = m2.keySet();  // Needn't be in synchronized block
      *      ...
-     *  synchronized(m) {  // Synchronizing on m, not m2 or s2!
+     *  synchronized (m) {  // Synchronizing on m, not m2 or s2!
      *      Iterator i = s.iterator(); // Must be in synchronized block
      *      while (i.hasNext())
      *          foo(i.next());
@@ -2154,31 +2154,31 @@ public class Collections {
         }
 
         public Comparator comparator() {
-            synchronized(mutex) {return sm.comparator();}
+            synchronized (mutex) {return sm.comparator();}
         }
 
         public SortedMap subMap(K fromKey, K toKey) {
-            synchronized(mutex) {
+            synchronized (mutex) {
                 return new SynchronizedSortedMap(
                     sm.subMap(fromKey, toKey), mutex);
             }
         }
         public SortedMap headMap(K toKey) {
-            synchronized(mutex) {
+            synchronized (mutex) {
                 return new SynchronizedSortedMap(sm.headMap(toKey), mutex);
             }
         }
         public SortedMap tailMap(K fromKey) {
-            synchronized(mutex) {
+            synchronized (mutex) {
                return new SynchronizedSortedMap(sm.tailMap(fromKey),mutex);
             }
         }
 
         public K firstKey() {
-            synchronized(mutex) {return sm.firstKey();}
+            synchronized (mutex) {return sm.firstKey();}
         }
         public K lastKey() {
-            synchronized(mutex) {return sm.lastKey();}
+            synchronized (mutex) {return sm.lastKey();}
         }
     }
 
@@ -3317,7 +3317,7 @@ public class Collections {
     {
         private static final long serialVersionUID = 3193687207550431679L;
 
-        final private E element;
+        private final E element;
 
         SingletonSet(E e) {element = e;}
 
@@ -3448,7 +3448,7 @@ public class Collections {
      * @param  o the element to appear repeatedly in the returned list.
      * @return an immutable list consisting of n copies of the
      *         specified object.
-     * @throws IllegalArgumentException if n < 0.
+     * @throws IllegalArgumentException if {@code n < 0}
      * @see    List#addAll(Collection)
      * @see    List#addAll(int, Collection)
      */
diff --git a/src/share/classes/java/util/ComparableTimSort.java b/src/share/classes/java/util/ComparableTimSort.java
index 4907a0f5bcd0935d3aeebaf9bda10bccf9450597..f78ee9a2efc711bf0e1dde89eed9a5fe38976548 100644
--- a/src/share/classes/java/util/ComparableTimSort.java
+++ b/src/share/classes/java/util/ComparableTimSort.java
@@ -207,7 +207,7 @@ class ComparableTimSort {
      * @param lo the index of the first element in the range to be sorted
      * @param hi the index after the last element in the range to be sorted
      * @param start the index of the first element in the range that is
-     *        not already known to be sorted (@code lo <= start <= hi}
+     *        not already known to be sorted ({@code lo <= start <= hi})
      */
     @SuppressWarnings("fallthrough")
     private static void binarySort(Object[] a, int lo, int hi, int start) {
@@ -245,7 +245,7 @@ class ComparableTimSort {
              */
             int n = start - left;  // The number of elements to move
             // Switch is just an optimization for arraycopy in default case
-            switch(n) {
+            switch (n) {
                 case 2:  a[left + 2] = a[left + 1];
                 case 1:  a[left + 1] = a[left];
                          break;
@@ -275,7 +275,7 @@ class ComparableTimSort {
      * @param a the array in which a run is to be counted and possibly reversed
      * @param lo index of the first element in the run
      * @param hi index after the last element that may be contained in the run.
-              It is required that @code{lo < hi}.
+              It is required that {@code lo < hi}.
      * @return  the length of the run beginning at the specified position in
      *          the specified array
      */
@@ -288,7 +288,7 @@ class ComparableTimSort {
 
         // Find end of run, and reverse range if descending
         if (((Comparable) a[runHi++]).compareTo(a[lo]) < 0) { // Descending
-            while(runHi < hi && ((Comparable) a[runHi]).compareTo(a[runHi - 1]) < 0)
+            while (runHi < hi && ((Comparable) a[runHi]).compareTo(a[runHi - 1]) < 0)
                 runHi++;
             reverseRange(a, lo, runHi);
         } else {                              // Ascending
diff --git a/src/share/classes/java/util/Random.java b/src/share/classes/java/util/Random.java
index 833cfbbe256cf0eb68b35ecee4abed0160147497..8f217833bfe260e3053fb3c5ad6437bda97f50f9 100644
--- a/src/share/classes/java/util/Random.java
+++ b/src/share/classes/java/util/Random.java
@@ -77,9 +77,9 @@ class Random implements java.io.Serializable {
      */
     private final AtomicLong seed;
 
-    private final static long multiplier = 0x5DEECE66DL;
-    private final static long addend = 0xBL;
-    private final static long mask = (1L << 48) - 1;
+    private static final long multiplier = 0x5DEECE66DL;
+    private static final long addend = 0xBL;
+    private static final long mask = (1L << 48) - 1;
 
     /**
      * Creates a new random number generator. This constructor sets
@@ -285,7 +285,7 @@ class Random implements java.io.Serializable {
      * @return the next pseudorandom, uniformly distributed {@code int}
      *         value between {@code 0} (inclusive) and {@code n} (exclusive)
      *         from this random number generator's sequence
-     * @exception IllegalArgumentException if n is not positive
+     * @throws IllegalArgumentException if n is not positive
      * @since 1.2
      */
 
diff --git a/src/share/classes/java/util/Stack.java b/src/share/classes/java/util/Stack.java
index 9c17b31a75bc145ab266c5ed4cfa4043f549735d..8dd2ebddbbe3df2d85cbca86fec1f876c1e41177 100644
--- a/src/share/classes/java/util/Stack.java
+++ b/src/share/classes/java/util/Stack.java
@@ -73,9 +73,9 @@ class Stack extends Vector {
      * Removes the object at the top of this stack and returns that
      * object as the value of this function.
      *
-     * @return     The object at the top of this stack (the last item
-     *             of the Vector object).
-     * @exception  EmptyStackException  if this stack is empty.
+     * @return  The object at the top of this stack (the last item
+     *          of the Vector object).
+     * @throws  EmptyStackException  if this stack is empty.
      */
     public synchronized E pop() {
         E       obj;
@@ -91,9 +91,9 @@ class Stack extends Vector {
      * Looks at the object at the top of this stack without removing it
      * from the stack.
      *
-     * @return     the object at the top of this stack (the last item
-     *             of the Vector object).
-     * @exception  EmptyStackException  if this stack is empty.
+     * @return  the object at the top of this stack (the last item
+     *          of the Vector object).
+     * @throws  EmptyStackException  if this stack is empty.
      */
     public synchronized E peek() {
         int     len = size();
diff --git a/src/share/classes/java/util/TimSort.java b/src/share/classes/java/util/TimSort.java
index 6940883d02a98a0a68513da9b8e7245a03ff1ae8..6d4727ac4e7a574aeb7df1f786357f3c3e5d55ca 100644
--- a/src/share/classes/java/util/TimSort.java
+++ b/src/share/classes/java/util/TimSort.java
@@ -239,7 +239,7 @@ class TimSort {
      * @param lo the index of the first element in the range to be sorted
      * @param hi the index after the last element in the range to be sorted
      * @param start the index of the first element in the range that is
-     *        not already known to be sorted (@code lo <= start <= hi}
+     *        not already known to be sorted ({@code lo <= start <= hi})
      * @param c comparator to used for the sort
      */
     @SuppressWarnings("fallthrough")
@@ -278,7 +278,7 @@ class TimSort {
              */
             int n = start - left;  // The number of elements to move
             // Switch is just an optimization for arraycopy in default case
-            switch(n) {
+            switch (n) {
                 case 2:  a[left + 2] = a[left + 1];
                 case 1:  a[left + 1] = a[left];
                          break;
@@ -308,7 +308,7 @@ class TimSort {
      * @param a the array in which a run is to be counted and possibly reversed
      * @param lo index of the first element in the run
      * @param hi index after the last element that may be contained in the run.
-              It is required that @code{lo < hi}.
+              It is required that {@code lo < hi}.
      * @param c the comparator to used for the sort
      * @return  the length of the run beginning at the specified position in
      *          the specified array
@@ -322,7 +322,7 @@ class TimSort {
 
         // Find end of run, and reverse range if descending
         if (c.compare(a[runHi++], a[lo]) < 0) { // Descending
-            while(runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
+            while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
                 runHi++;
             reverseRange(a, lo, runHi);
         } else {                              // Ascending
diff --git a/src/share/classes/java/util/TreeMap.java b/src/share/classes/java/util/TreeMap.java
index b0c9aa7d67a781c473e38c1576bbcaf8b8962eb6..8c055d8ce98607a965c26e781dc6a8c224c06f07 100644
--- a/src/share/classes/java/util/TreeMap.java
+++ b/src/share/classes/java/util/TreeMap.java
@@ -1056,11 +1056,11 @@ public class TreeMap
         public Comparator comparator() { return m.comparator(); }
         public E pollFirst() {
             Map.Entry e = m.pollFirstEntry();
-            return e == null? null : e.getKey();
+            return (e == null) ? null : e.getKey();
         }
         public E pollLast() {
             Map.Entry e = m.pollLastEntry();
-            return e == null? null : e.getKey();
+            return (e == null) ? null : e.getKey();
         }
         public boolean remove(Object o) {
             int oldSize = size();
@@ -1196,7 +1196,7 @@ public class TreeMap
      * Test two values for equality.  Differs from o1.equals(o2) only in
      * that it copes with {@code null} o1 properly.
      */
-    final static boolean valEquals(Object o1, Object o2) {
+    static final boolean valEquals(Object o1, Object o2) {
         return (o1==null ? o2==null : o1.equals(o2));
     }
 
@@ -1204,7 +1204,7 @@ public class TreeMap
      * Return SimpleImmutableEntry for entry, or null if null
      */
     static  Map.Entry exportEntry(TreeMap.Entry e) {
-        return e == null? null :
+        return (e == null) ? null :
             new AbstractMap.SimpleImmutableEntry(e);
     }
 
@@ -1212,7 +1212,7 @@ public class TreeMap
      * Return key for entry, or null if null
      */
     static  K keyOrNull(TreeMap.Entry e) {
-        return e == null? null : e.key;
+        return (e == null) ? null : e.key;
     }
 
     /**
@@ -1237,7 +1237,7 @@ public class TreeMap
     /**
      * @serial include
      */
-    static abstract class NavigableSubMap extends AbstractMap
+    abstract static class NavigableSubMap extends AbstractMap
         implements NavigableMap, java.io.Serializable {
         /**
          * The backing map.
@@ -1412,11 +1412,11 @@ public class TreeMap
         }
 
         public final V get(Object key) {
-            return !inRange(key)? null :  m.get(key);
+            return !inRange(key) ? null :  m.get(key);
         }
 
         public final V remove(Object key) {
-            return !inRange(key)? null  : m.remove(key);
+            return !inRange(key) ? null : m.remove(key);
         }
 
         public final Map.Entry ceilingEntry(K key) {
@@ -1559,7 +1559,8 @@ public class TreeMap
                 if (!inRange(key))
                     return false;
                 TreeMap.Entry node = m.getEntry(key);
-                if (node!=null && valEquals(node.getValue(),entry.getValue())){
+                if (node!=null && valEquals(node.getValue(),
+                                            entry.getValue())) {
                     m.deleteEntry(node);
                     return true;
                 }
@@ -1724,7 +1725,7 @@ public class TreeMap
                                        false,     toKey, inclusive);
         }
 
-        public NavigableMap tailMap(K fromKey, boolean inclusive){
+        public NavigableMap tailMap(K fromKey, boolean inclusive) {
             if (!inRange(fromKey, inclusive))
                 throw new IllegalArgumentException("fromKey out of range");
             return new AscendingSubMap(m,
@@ -1805,7 +1806,7 @@ public class TreeMap
                                         toEnd, hi,    hiInclusive);
         }
 
-        public NavigableMap tailMap(K fromKey, boolean inclusive){
+        public NavigableMap tailMap(K fromKey, boolean inclusive) {
             if (!inRange(fromKey, inclusive))
                 throw new IllegalArgumentException("fromKey out of range");
             return new DescendingSubMap(m,
@@ -2143,7 +2144,7 @@ public class TreeMap
         // If strictly internal, copy successor's element to p and then make p
         // point to successor.
         if (p.left != null && p.right != null) {
-            Entry s = successor (p);
+            Entry s = successor(p);
             p.key = s.key;
             p.value = s.value;
             p = s;
diff --git a/src/share/classes/java/util/TreeSet.java b/src/share/classes/java/util/TreeSet.java
index 99e3f313ad681213e99e19ca050270d14c2b04c0..c2e2bdf8ffd1af21c38eae27960b019da2a363fd 100644
--- a/src/share/classes/java/util/TreeSet.java
+++ b/src/share/classes/java/util/TreeSet.java
@@ -452,7 +452,7 @@ public class TreeSet extends AbstractSet
      */
     public E pollFirst() {
         Map.Entry e = m.pollFirstEntry();
-        return (e == null)? null : e.getKey();
+        return (e == null) ? null : e.getKey();
     }
 
     /**
@@ -460,7 +460,7 @@ public class TreeSet extends AbstractSet
      */
     public E pollLast() {
         Map.Entry e = m.pollLastEntry();
-        return (e == null)? null : e.getKey();
+        return (e == null) ? null : e.getKey();
     }
 
     /**
diff --git a/src/share/classes/java/util/Vector.java b/src/share/classes/java/util/Vector.java
index e508aa5b5c00180054275766c9d6ff64044ae5fc..f1a9c172a278cd3ad40ee06ea4dc6e8e06361ed6 100644
--- a/src/share/classes/java/util/Vector.java
+++ b/src/share/classes/java/util/Vector.java
@@ -919,7 +919,7 @@ public class Vector
      *         elements (optional), or if the specified collection is null
      * @since 1.2
      */
-    public synchronized boolean retainAll(Collection c)  {
+    public synchronized boolean retainAll(Collection c) {
         return super.retainAll(c);
     }
 
diff --git a/src/share/classes/java/util/concurrent/AbstractExecutorService.java b/src/share/classes/java/util/concurrent/AbstractExecutorService.java
index 3a43617b0be61f44b6156910b90f7863b79d9e14..0322289e52e6f069e42c12bc57fe0331215c2173 100644
--- a/src/share/classes/java/util/concurrent/AbstractExecutorService.java
+++ b/src/share/classes/java/util/concurrent/AbstractExecutorService.java
@@ -51,20 +51,20 @@ import java.util.*;
  * 

Extension example. Here is a sketch of a class * that customizes {@link ThreadPoolExecutor} to use * a CustomTask class instead of the default FutureTask: - *

+ *  
 {@code
  * public class CustomThreadPoolExecutor extends ThreadPoolExecutor {
  *
- *   static class CustomTask<V> implements RunnableFuture<V> {...}
+ *   static class CustomTask implements RunnableFuture {...}
  *
- *   protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) {
- *       return new CustomTask<V>(c);
+ *   protected  RunnableFuture newTaskFor(Callable c) {
+ *       return new CustomTask(c);
  *   }
- *   protected <V> RunnableFuture<V> newTaskFor(Runnable r, V v) {
- *       return new CustomTask<V>(r, v);
+ *   protected  RunnableFuture newTaskFor(Runnable r, V v) {
+ *       return new CustomTask(r, v);
  *   }
  *   // ... add constructors, etc.
- * }
- * 
+ * }}
+ * * @since 1.5 * @author Doug Lea */ @@ -106,7 +106,7 @@ public abstract class AbstractExecutorService implements ExecutorService { */ public Future submit(Runnable task) { if (task == null) throw new NullPointerException(); - RunnableFuture ftask = newTaskFor(task, null); + RunnableFuture ftask = newTaskFor(task, null); execute(ftask); return ftask; } @@ -158,7 +158,7 @@ public abstract class AbstractExecutorService implements ExecutorService { // Record exceptions so that if we fail to obtain any // result, we can throw the last exception we got. ExecutionException ee = null; - long lastTime = (timed)? System.nanoTime() : 0; + long lastTime = timed ? System.nanoTime() : 0; Iterator> it = tasks.iterator(); // Start one task for sure; the rest incrementally @@ -191,8 +191,6 @@ public abstract class AbstractExecutorService implements ExecutorService { --active; try { return f.get(); - } catch (InterruptedException ie) { - throw ie; } catch (ExecutionException eex) { ee = eex; } catch (RuntimeException rex) { diff --git a/src/share/classes/java/util/concurrent/ConcurrentHashMap.java b/src/share/classes/java/util/concurrent/ConcurrentHashMap.java index 7fb9b07c872bd3f0b66ffb7a7bc9239f660aef32..8074669654c5a0b9de2cbcce2524374a8bac6382 100644 --- a/src/share/classes/java/util/concurrent/ConcurrentHashMap.java +++ b/src/share/classes/java/util/concurrent/ConcurrentHashMap.java @@ -1270,7 +1270,7 @@ public class ConcurrentHashMap extends AbstractMap * for each key-value mapping, followed by a null pair. * The key-value mappings are emitted in no particular order. */ - private void writeObject(java.io.ObjectOutputStream s) throws IOException { + private void writeObject(java.io.ObjectOutputStream s) throws IOException { s.defaultWriteObject(); for (int k = 0; k < segments.length; ++k) { @@ -1298,7 +1298,7 @@ public class ConcurrentHashMap extends AbstractMap * @param s the stream */ private void readObject(java.io.ObjectInputStream s) - throws IOException, ClassNotFoundException { + throws IOException, ClassNotFoundException { s.defaultReadObject(); // Initialize each segment to be minimally sized, and let grow. diff --git a/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java b/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java index 4837661a4416028e8a3e5a12a98150b8f1229be0..72133fedad7691db6cd64c944b17251fe3156bb0 100644 --- a/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java +++ b/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java @@ -38,7 +38,6 @@ package java.util.concurrent; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; -import java.util.ConcurrentModificationException; import java.util.Deque; import java.util.Iterator; import java.util.NoSuchElementException; @@ -212,7 +211,7 @@ public class ConcurrentLinkedDeque * The actual representation we use is that p.next == p means to * goto the first node (which in turn is reached by following prev * pointers from head), and p.next == null && p.prev == p means - * that the iteration is at an end and that p is a (final static) + * that the iteration is at an end and that p is a (static final) * dummy node, NEXT_TERMINATOR, and not the last active node. * Finishing the iteration when encountering such a TERMINATOR is * good enough for read-only traversals, so such traversals can use @@ -271,7 +270,7 @@ public class ConcurrentLinkedDeque */ private transient volatile Node tail; - private final static Node PREV_TERMINATOR, NEXT_TERMINATOR; + private static final Node PREV_TERMINATOR, NEXT_TERMINATOR; static { PREV_TERMINATOR = new Node(null); @@ -401,7 +400,7 @@ public class ConcurrentLinkedDeque } } - private final static int HOPS = 2; + private static final int HOPS = 2; /** * Unlinks non-null node x. @@ -871,7 +870,7 @@ public class ConcurrentLinkedDeque /** * Inserts the specified element at the front of this deque. * - * @throws NullPointerException {@inheritDoc} + * @throws NullPointerException if the specified element is null */ public void addFirst(E e) { linkFirst(e); @@ -882,7 +881,7 @@ public class ConcurrentLinkedDeque * *

This method is equivalent to {@link #add}. * - * @throws NullPointerException {@inheritDoc} + * @throws NullPointerException if the specified element is null */ public void addLast(E e) { linkLast(e); @@ -892,7 +891,7 @@ public class ConcurrentLinkedDeque * Inserts the specified element at the front of this deque. * * @return {@code true} always - * @throws NullPointerException {@inheritDoc} + * @throws NullPointerException if the specified element is null */ public boolean offerFirst(E e) { linkFirst(e); @@ -905,7 +904,7 @@ public class ConcurrentLinkedDeque *

This method is equivalent to {@link #add}. * * @return {@code true} always - * @throws NullPointerException {@inheritDoc} + * @throws NullPointerException if the specified element is null */ public boolean offerLast(E e) { linkLast(e); @@ -940,7 +939,7 @@ public class ConcurrentLinkedDeque /** * @throws NoSuchElementException {@inheritDoc} */ - public E getLast() { + public E getLast() { return screenNullResult(peekLast()); } @@ -1016,7 +1015,7 @@ public class ConcurrentLinkedDeque * * @param o element to be removed from this deque, if present * @return {@code true} if the deque contained the specified element - * @throws NullPointerException if the specified element is {@code null} + * @throws NullPointerException if the specified element is null */ public boolean removeFirstOccurrence(Object o) { checkNotNull(o); @@ -1037,7 +1036,7 @@ public class ConcurrentLinkedDeque * * @param o element to be removed from this deque, if present * @return {@code true} if the deque contained the specified element - * @throws NullPointerException if the specified element is {@code null} + * @throws NullPointerException if the specified element is null */ public boolean removeLastOccurrence(Object o) { checkNotNull(o); @@ -1110,7 +1109,7 @@ public class ConcurrentLinkedDeque * * @param o element to be removed from this deque, if present * @return {@code true} if the deque contained the specified element - * @throws NullPointerException if the specified element is {@code null} + * @throws NullPointerException if the specified element is null */ public boolean remove(Object o) { return removeFirstOccurrence(o); @@ -1165,7 +1164,7 @@ public class ConcurrentLinkedDeque beginningOfTheEnd.lazySetPrev(p); // CAS piggyback if (p.casNext(null, beginningOfTheEnd)) { // Successful CAS is the linearization point - // for all elements to be added to this queue. + // for all elements to be added to this deque. if (!casTail(t, last)) { // Try a little harder to update tail, // since we may be adding many elements. @@ -1251,12 +1250,12 @@ public class ConcurrentLinkedDeque * Returns an iterator over the elements in this deque in proper sequence. * The elements will be returned in order from first (head) to last (tail). * - *

The returned {@code Iterator} is a "weakly consistent" iterator that + *

The returned iterator is a "weakly consistent" iterator that * will never throw {@link java.util.ConcurrentModificationException - * ConcurrentModificationException}, - * and guarantees to traverse elements as they existed upon - * construction of the iterator, and may (but is not guaranteed to) - * reflect any modifications subsequent to construction. + * ConcurrentModificationException}, and guarantees to traverse + * elements as they existed upon construction of the iterator, and + * may (but is not guaranteed to) reflect any modifications + * subsequent to construction. * * @return an iterator over the elements in this deque in proper sequence */ @@ -1269,12 +1268,12 @@ public class ConcurrentLinkedDeque * sequential order. The elements will be returned in order from * last (tail) to first (head). * - *

The returned {@code Iterator} is a "weakly consistent" iterator that + *

The returned iterator is a "weakly consistent" iterator that * will never throw {@link java.util.ConcurrentModificationException - * ConcurrentModificationException}, - * and guarantees to traverse elements as they existed upon - * construction of the iterator, and may (but is not guaranteed to) - * reflect any modifications subsequent to construction. + * ConcurrentModificationException}, and guarantees to traverse + * elements as they existed upon construction of the iterator, and + * may (but is not guaranteed to) reflect any modifications + * subsequent to construction. * * @return an iterator over the elements in this deque in reverse order */ diff --git a/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java b/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java index 0d6381cd971e7c632f914a6aed936dee63a2fd36..6ff1b8a5119b9b25c837f4856424647ed95c9a83 100644 --- a/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java +++ b/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java @@ -65,8 +65,8 @@ import java.util.Queue; *

Iterators are weakly consistent, returning elements * reflecting the state of the queue at some point at or since the * creation of the iterator. They do not throw {@link - * ConcurrentModificationException}, and may proceed concurrently with - * other operations. Elements contained in the queue since the creation + * java.util.ConcurrentModificationException}, and may proceed concurrently + * with other operations. Elements contained in the queue since the creation * of the iterator will be returned exactly once. * *

Beware that, unlike in most collections, the {@code size} method @@ -634,12 +634,12 @@ public class ConcurrentLinkedQueue extends AbstractQueue * Returns an iterator over the elements in this queue in proper sequence. * The elements will be returned in order from first (head) to last (tail). * - *

The returned {@code Iterator} is a "weakly consistent" iterator that + *

The returned iterator is a "weakly consistent" iterator that * will never throw {@link java.util.ConcurrentModificationException - * ConcurrentModificationException}, - * and guarantees to traverse elements as they existed upon - * construction of the iterator, and may (but is not guaranteed to) - * reflect any modifications subsequent to construction. + * ConcurrentModificationException}, and guarantees to traverse + * elements as they existed upon construction of the iterator, and + * may (but is not guaranteed to) reflect any modifications + * subsequent to construction. * * @return an iterator over the elements in this queue in proper sequence */ diff --git a/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java b/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java index d129564acebe71c2d82577f6511e76c11ee0624c..09f8dc6f5b2309bfb10f62bbc2c9bc5c829dd7e6 100644 --- a/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java +++ b/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java @@ -362,12 +362,12 @@ public class ConcurrentSkipListSet public E pollFirst() { Map.Entry e = m.pollFirstEntry(); - return e == null? null : e.getKey(); + return (e == null) ? null : e.getKey(); } public E pollLast() { Map.Entry e = m.pollLastEntry(); - return e == null? null : e.getKey(); + return (e == null) ? null : e.getKey(); } diff --git a/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java b/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java index 97d27cbe6a43143f393265cc04cbfb5b51011845..73b9df32269d23cdd41e5c7b369a3bd43e05a4ea 100644 --- a/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java +++ b/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java @@ -547,7 +547,7 @@ public class CopyOnWriteArrayList * @param fromIndex index of first element to be removed * @param toIndex index after last element to be removed * @throws IndexOutOfBoundsException if fromIndex or toIndex out of range - * (@code{fromIndex < 0 || toIndex > size() || toIndex < fromIndex}) + * ({@code{fromIndex < 0 || toIndex > size() || toIndex < fromIndex}) */ private void removeRange(int fromIndex, int toIndex) { final ReentrantLock lock = this.lock; @@ -989,7 +989,7 @@ public class CopyOnWriteArrayList } private static class COWIterator implements ListIterator { - /** Snapshot of the array **/ + /** Snapshot of the array */ private final Object[] snapshot; /** Index of element to be returned by subsequent call to next. */ private int cursor; diff --git a/src/share/classes/java/util/concurrent/CopyOnWriteArraySet.java b/src/share/classes/java/util/concurrent/CopyOnWriteArraySet.java index 9114d45fb9a054eedb603198783367b5583780d8..1d2de1d85c9073d564470fd896cb62b24711a332 100644 --- a/src/share/classes/java/util/concurrent/CopyOnWriteArraySet.java +++ b/src/share/classes/java/util/concurrent/CopyOnWriteArraySet.java @@ -59,24 +59,23 @@ import java.util.*; * copy-on-write set to maintain a set of Handler objects that * perform some action upon state updates. * - *

+ *  
 {@code
  * class Handler { void handle(); ... }
  *
  * class X {
- *    private final CopyOnWriteArraySet<Handler> handlers
- *       = new CopyOnWriteArraySet<Handler>();
- *    public void addHandler(Handler h) { handlers.add(h); }
+ *   private final CopyOnWriteArraySet handlers
+ *     = new CopyOnWriteArraySet();
+ *   public void addHandler(Handler h) { handlers.add(h); }
  *
- *    private long internalState;
- *    private synchronized void changeState() { internalState = ...; }
+ *   private long internalState;
+ *   private synchronized void changeState() { internalState = ...; }
  *
- *    public void update() {
- *       changeState();
- *       for (Handler handler : handlers)
- *          handler.handle();
- *    }
- * }
- * 
+ * public void update() { + * changeState(); + * for (Handler handler : handlers) + * handler.handle(); + * } + * }}
* *

This class is a member of the * diff --git a/src/share/classes/java/util/concurrent/CountDownLatch.java b/src/share/classes/java/util/concurrent/CountDownLatch.java index ec39cea44d83d78626c9500cb3feb28298bb835a..1c8a0253c149a137a913aa74dfe060bb11b9424b 100644 --- a/src/share/classes/java/util/concurrent/CountDownLatch.java +++ b/src/share/classes/java/util/concurrent/CountDownLatch.java @@ -175,7 +175,7 @@ public class CountDownLatch { } protected int tryAcquireShared(int acquires) { - return getState() == 0? 1 : -1; + return (getState() == 0) ? 1 : -1; } protected boolean tryReleaseShared(int releases) { diff --git a/src/share/classes/java/util/concurrent/DelayQueue.java b/src/share/classes/java/util/concurrent/DelayQueue.java index 6ce3471b18c2bb5569a181b21f57bbdf0147af33..ecb9eefc6e26be12cf3b65e0d19cb061a311df7c 100644 --- a/src/share/classes/java/util/concurrent/DelayQueue.java +++ b/src/share/classes/java/util/concurrent/DelayQueue.java @@ -482,12 +482,14 @@ public class DelayQueue extends AbstractQueue /** * Returns an iterator over all the elements (both expired and * unexpired) in this queue. The iterator does not return the - * elements in any particular order. The returned - * Iterator is a "weakly consistent" iterator that will - * never throw {@link ConcurrentModificationException}, and - * guarantees to traverse elements as they existed upon - * construction of the iterator, and may (but is not guaranteed - * to) reflect any modifications subsequent to construction. + * elements in any particular order. + * + *

The returned iterator is a "weakly consistent" iterator that + * will never throw {@link java.util.ConcurrentModificationException + * ConcurrentModificationException}, and guarantees to traverse + * elements as they existed upon construction of the iterator, and + * may (but is not guaranteed to) reflect any modifications + * subsequent to construction. * * @return an iterator over the elements in this queue */ diff --git a/src/share/classes/java/util/concurrent/Exchanger.java b/src/share/classes/java/util/concurrent/Exchanger.java index c4563a8ae9b695c10eac43e63bcf1fceb1dcaaa8..8648278b75566f5363986e84551a16a8c1acff8b 100644 --- a/src/share/classes/java/util/concurrent/Exchanger.java +++ b/src/share/classes/java/util/concurrent/Exchanger.java @@ -355,7 +355,9 @@ public class Exchanger { else if (y == null && // Try to occupy slot.compareAndSet(null, me)) { if (index == 0) // Blocking wait for slot 0 - return timed? awaitNanos(me, slot, nanos): await(me, slot); + return timed ? + awaitNanos(me, slot, nanos) : + await(me, slot); Object v = spinWait(me, slot); // Spin wait for non-0 if (v != CANCEL) return v; @@ -597,8 +599,8 @@ public class Exchanger { * dormant until one of two things happens: *

*

If the current thread: *

    @@ -616,7 +618,7 @@ public class Exchanger { */ public V exchange(V x) throws InterruptedException { if (!Thread.interrupted()) { - Object v = doExchange(x == null? NULL_ITEM : x, false, 0); + Object v = doExchange((x == null) ? NULL_ITEM : x, false, 0); if (v == NULL_ITEM) return null; if (v != CANCEL) @@ -671,7 +673,7 @@ public class Exchanger { public V exchange(V x, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { if (!Thread.interrupted()) { - Object v = doExchange(x == null? NULL_ITEM : x, + Object v = doExchange((x == null) ? NULL_ITEM : x, true, unit.toNanos(timeout)); if (v == NULL_ITEM) return null; diff --git a/src/share/classes/java/util/concurrent/Executor.java b/src/share/classes/java/util/concurrent/Executor.java index 85b3277f43d57e38ca1668422c7253cf31289697..5e67fbcdd08fe60aa75f4281d7fc8b2f4b42796d 100644 --- a/src/share/classes/java/util/concurrent/Executor.java +++ b/src/share/classes/java/util/concurrent/Executor.java @@ -79,37 +79,37 @@ package java.util.concurrent; * serializes the submission of tasks to a second executor, * illustrating a composite executor. * - *
    + *  
     {@code
      * class SerialExecutor implements Executor {
    - *     final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
    - *     final Executor executor;
    - *     Runnable active;
    - *
    - *     SerialExecutor(Executor executor) {
    - *         this.executor = executor;
    - *     }
    - *
    - *     public synchronized void execute(final Runnable r) {
    - *         tasks.offer(new Runnable() {
    - *             public void run() {
    - *                 try {
    - *                     r.run();
    - *                 } finally {
    - *                     scheduleNext();
    - *                 }
    - *             }
    - *         });
    - *         if (active == null) {
    - *             scheduleNext();
    + *   final Queue tasks = new ArrayDeque();
    + *   final Executor executor;
    + *   Runnable active;
    + *
    + *   SerialExecutor(Executor executor) {
    + *     this.executor = executor;
    + *   }
    + *
    + *   public synchronized void execute(final Runnable r) {
    + *     tasks.offer(new Runnable() {
    + *       public void run() {
    + *         try {
    + *           r.run();
    + *         } finally {
    + *           scheduleNext();
      *         }
    + *       }
    + *     });
    + *     if (active == null) {
    + *       scheduleNext();
      *     }
    + *   }
      *
    - *     protected synchronized void scheduleNext() {
    - *         if ((active = tasks.poll()) != null) {
    - *             executor.execute(active);
    - *         }
    + *   protected synchronized void scheduleNext() {
    + *     if ((active = tasks.poll()) != null) {
    + *       executor.execute(active);
      *     }
    - * }
    + * } + * }}
    * * The Executor implementations provided in this package * implement {@link ExecutorService}, which is a more extensive diff --git a/src/share/classes/java/util/concurrent/ExecutorCompletionService.java b/src/share/classes/java/util/concurrent/ExecutorCompletionService.java index 4d37c999018f6bf4b1ab469498cac82e68c0fff9..9908a8cfcdd2e45098a7692ebfe92247406d54a0 100644 --- a/src/share/classes/java/util/concurrent/ExecutorCompletionService.java +++ b/src/share/classes/java/util/concurrent/ExecutorCompletionService.java @@ -197,7 +197,8 @@ public class ExecutorCompletionService implements CompletionService { return completionQueue.poll(); } - public Future poll(long timeout, TimeUnit unit) throws InterruptedException { + public Future poll(long timeout, TimeUnit unit) + throws InterruptedException { return completionQueue.poll(timeout, unit); } diff --git a/src/share/classes/java/util/concurrent/Executors.java b/src/share/classes/java/util/concurrent/Executors.java index efa2f78f86f34533a0b154370bbabb2284f31586..75a490086ae6c828c3dc83dbc7ab475c33f66803 100644 --- a/src/share/classes/java/util/concurrent/Executors.java +++ b/src/share/classes/java/util/concurrent/Executors.java @@ -83,7 +83,7 @@ public class Executors { * * @param nThreads the number of threads in the pool * @return the newly created thread pool - * @throws IllegalArgumentException if nThreads <= 0 + * @throws IllegalArgumentException if {@code nThreads <= 0} */ public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, @@ -108,7 +108,7 @@ public class Executors { * @param threadFactory the factory to use when creating new threads * @return the newly created thread pool * @throws NullPointerException if threadFactory is null - * @throws IllegalArgumentException if nThreads <= 0 + * @throws IllegalArgumentException if {@code nThreads <= 0} */ public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { return new ThreadPoolExecutor(nThreads, nThreads, @@ -242,7 +242,7 @@ public class Executors { * @param corePoolSize the number of threads to keep in the pool, * even if they are idle. * @return a newly created scheduled thread pool - * @throws IllegalArgumentException if corePoolSize < 0 + * @throws IllegalArgumentException if {@code corePoolSize < 0} */ public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); @@ -256,7 +256,7 @@ public class Executors { * @param threadFactory the factory to use when the executor * creates a new thread. * @return a newly created scheduled thread pool - * @throws IllegalArgumentException if corePoolSize < 0 + * @throws IllegalArgumentException if {@code corePoolSize < 0} * @throws NullPointerException if threadFactory is null */ public static ScheduledExecutorService newScheduledThreadPool( @@ -562,8 +562,8 @@ public class Executors { DefaultThreadFactory() { SecurityManager s = System.getSecurityManager(); - group = (s != null)? s.getThreadGroup() : - Thread.currentThread().getThreadGroup(); + group = (s != null) ? s.getThreadGroup() : + Thread.currentThread().getThreadGroup(); namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-"; @@ -669,7 +669,7 @@ public class Executors { FinalizableDelegatedExecutorService(ExecutorService executor) { super(executor); } - protected void finalize() { + protected void finalize() { super.shutdown(); } } diff --git a/src/share/classes/java/util/concurrent/Future.java b/src/share/classes/java/util/concurrent/Future.java index 9d3d1ff741b72dd6153c95da0b47c01071c96f94..4abd3f4e1741ad577f05f56f0c6f3f64cacf5d31 100644 --- a/src/share/classes/java/util/concurrent/Future.java +++ b/src/share/classes/java/util/concurrent/Future.java @@ -47,21 +47,21 @@ package java.util.concurrent; * computation has completed, the computation cannot be cancelled. * If you would like to use a Future for the sake * of cancellability but not provide a usable result, you can - * declare types of the form Future<?> and + * declare types of the form {@code Future} and * return null as a result of the underlying task. * *

    * Sample Usage (Note that the following classes are all * made-up.)

    - *

    + *  
     {@code
      * interface ArchiveSearcher { String search(String target); }
      * class App {
      *   ExecutorService executor = ...
      *   ArchiveSearcher searcher = ...
      *   void showSearch(final String target)
      *       throws InterruptedException {
    - *     Future<String> future
    - *       = executor.submit(new Callable<String>() {
    + *     Future future
    + *       = executor.submit(new Callable() {
      *         public String call() {
      *             return searcher.search(target);
      *         }});
    @@ -70,20 +70,18 @@ package java.util.concurrent;
      *       displayText(future.get()); // use future
      *     } catch (ExecutionException ex) { cleanup(); return; }
      *   }
    - * }
    - * 
    + * }}
    * * The {@link FutureTask} class is an implementation of Future that * implements Runnable, and so may be executed by an Executor. * For example, the above construction with submit could be replaced by: - *
    - *     FutureTask<String> future =
    - *       new FutureTask<String>(new Callable<String>() {
    + *  
     {@code
    + *     FutureTask future =
    + *       new FutureTask(new Callable() {
      *         public String call() {
      *           return searcher.search(target);
      *       }});
    - *     executor.execute(future);
    - * 
    + * executor.execute(future);}
    * *

    Memory consistency effects: Actions taken by the asynchronous computation * happen-before diff --git a/src/share/classes/java/util/concurrent/FutureTask.java b/src/share/classes/java/util/concurrent/FutureTask.java index c77b6d3ced4205eafabc77f82da4a94dcbd0a4dd..dd7a51edf712686fa929d2a249893bed12f9ec38 100644 --- a/src/share/classes/java/util/concurrent/FutureTask.java +++ b/src/share/classes/java/util/concurrent/FutureTask.java @@ -85,7 +85,7 @@ public class FutureTask implements RunnableFuture { * @param result the result to return on successful completion. If * you don't need a particular result, consider using * constructions of the form: - * Future<?> f = new FutureTask<Object>(runnable, null) + * {@code Future f = new FutureTask(runnable, null)} * @throws NullPointerException if runnable is null */ public FutureTask(Runnable runnable, V result) { diff --git a/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java b/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java index 13901e842f72a910e1d4c42aab9770741e6b9e36..8051ccaa8483f71f0f873515a27f1880b051ab6f 100644 --- a/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java +++ b/src/share/classes/java/util/concurrent/LinkedBlockingDeque.java @@ -1004,12 +1004,13 @@ public class LinkedBlockingDeque /** * Returns an iterator over the elements in this deque in proper sequence. * The elements will be returned in order from first (head) to last (tail). - * The returned {@code Iterator} is a "weakly consistent" iterator that + * + *

    The returned iterator is a "weakly consistent" iterator that * will never throw {@link java.util.ConcurrentModificationException - * ConcurrentModificationException}, - * and guarantees to traverse elements as they existed upon - * construction of the iterator, and may (but is not guaranteed to) - * reflect any modifications subsequent to construction. + * ConcurrentModificationException}, and guarantees to traverse + * elements as they existed upon construction of the iterator, and + * may (but is not guaranteed to) reflect any modifications + * subsequent to construction. * * @return an iterator over the elements in this deque in proper sequence */ @@ -1021,12 +1022,13 @@ public class LinkedBlockingDeque * Returns an iterator over the elements in this deque in reverse * sequential order. The elements will be returned in order from * last (tail) to first (head). - * The returned {@code Iterator} is a "weakly consistent" iterator that + * + *

    The returned iterator is a "weakly consistent" iterator that * will never throw {@link java.util.ConcurrentModificationException - * ConcurrentModificationException}, - * and guarantees to traverse elements as they existed upon - * construction of the iterator, and may (but is not guaranteed to) - * reflect any modifications subsequent to construction. + * ConcurrentModificationException}, and guarantees to traverse + * elements as they existed upon construction of the iterator, and + * may (but is not guaranteed to) reflect any modifications + * subsequent to construction. */ public Iterator descendingIterator() { return new DescendingItr(); diff --git a/src/share/classes/java/util/concurrent/RecursiveAction.java b/src/share/classes/java/util/concurrent/RecursiveAction.java index 40bcc88f0f8fe4a29fa48d8dd514b74a6ecdb5ff..e13bc4b55781dd332a23163e8d4c4ae7d306af0a 100644 --- a/src/share/classes/java/util/concurrent/RecursiveAction.java +++ b/src/share/classes/java/util/concurrent/RecursiveAction.java @@ -159,7 +159,9 @@ public abstract class RecursiveAction extends ForkJoinTask { protected abstract void compute(); /** - * Always returns null. + * Always returns {@code null}. + * + * @return {@code null} always */ public final Void getRawResult() { return null; } diff --git a/src/share/classes/java/util/concurrent/ScheduledExecutorService.java b/src/share/classes/java/util/concurrent/ScheduledExecutorService.java index a8d2f4041831f29b625998e7d48176779927fa32..e9d5d150afc99067c534d7405449507e6f8aa9f1 100644 --- a/src/share/classes/java/util/concurrent/ScheduledExecutorService.java +++ b/src/share/classes/java/util/concurrent/ScheduledExecutorService.java @@ -72,24 +72,23 @@ import java.util.*; * Here is a class with a method that sets up a ScheduledExecutorService * to beep every ten seconds for an hour: * - *

    + *  
     {@code
      * import static java.util.concurrent.TimeUnit.*;
      * class BeeperControl {
    - *    private final ScheduledExecutorService scheduler =
    - *       Executors.newScheduledThreadPool(1);
    + *   private final ScheduledExecutorService scheduler =
    + *     Executors.newScheduledThreadPool(1);
      *
    - *    public void beepForAnHour() {
    - *        final Runnable beeper = new Runnable() {
    - *                public void run() { System.out.println("beep"); }
    - *            };
    - *        final ScheduledFuture<?> beeperHandle =
    - *            scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
    - *        scheduler.schedule(new Runnable() {
    - *                public void run() { beeperHandle.cancel(true); }
    - *            }, 60 * 60, SECONDS);
    - *    }
    - * }
    - * 
    + * public void beepForAnHour() { + * final Runnable beeper = new Runnable() { + * public void run() { System.out.println("beep"); } + * }; + * final ScheduledFuture beeperHandle = + * scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS); + * scheduler.schedule(new Runnable() { + * public void run() { beeperHandle.cancel(true); } + * }, 60 * 60, SECONDS); + * } + * }}
    * * @since 1.5 * @author Doug Lea diff --git a/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java b/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java index 67c23fe99d79351d2bf83318761f4baf521ac3e2..46961b7aa40a43bf01bd9c0107b1ea618e4d6cb5 100644 --- a/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java +++ b/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java @@ -62,8 +62,8 @@ import java.util.*; * time of cancellation. * *

    Successive executions of a task scheduled via - * scheduleAtFixedRate or - * scheduleWithFixedDelay do not overlap. While different + * {@code scheduleAtFixedRate} or + * {@code scheduleWithFixedDelay} do not overlap. While different * executions may be performed by different threads, the effects of * prior executions happen-before @@ -436,7 +436,7 @@ public class ScheduledThreadPoolExecutor * @throws NullPointerException if {@code threadFactory} is null */ public ScheduledThreadPoolExecutor(int corePoolSize, - ThreadFactory threadFactory) { + ThreadFactory threadFactory) { super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, new DelayedWorkQueue(), threadFactory); } @@ -453,7 +453,7 @@ public class ScheduledThreadPoolExecutor * @throws NullPointerException if {@code handler} is null */ public ScheduledThreadPoolExecutor(int corePoolSize, - RejectedExecutionHandler handler) { + RejectedExecutionHandler handler) { super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, new DelayedWorkQueue(), handler); } @@ -473,8 +473,8 @@ public class ScheduledThreadPoolExecutor * {@code handler} is null */ public ScheduledThreadPoolExecutor(int corePoolSize, - ThreadFactory threadFactory, - RejectedExecutionHandler handler) { + ThreadFactory threadFactory, + RejectedExecutionHandler handler) { super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, new DelayedWorkQueue(), threadFactory, handler); } diff --git a/src/share/classes/java/util/concurrent/Semaphore.java b/src/share/classes/java/util/concurrent/Semaphore.java index 96a4719148d7397f8469ab773beb1e1be2671959..56c233fb3a7ba7ede0fe838fa78f8a5c7d495185 100644 --- a/src/share/classes/java/util/concurrent/Semaphore.java +++ b/src/share/classes/java/util/concurrent/Semaphore.java @@ -223,7 +223,7 @@ public class Semaphore implements java.io.Serializable { /** * NonFair version */ - final static class NonfairSync extends Sync { + static final class NonfairSync extends Sync { private static final long serialVersionUID = -2694183684443567898L; NonfairSync(int permits) { @@ -238,7 +238,7 @@ public class Semaphore implements java.io.Serializable { /** * Fair version */ - final static class FairSync extends Sync { + static final class FairSync extends Sync { private static final long serialVersionUID = 2014338818796000944L; FairSync(int permits) { @@ -282,7 +282,7 @@ public class Semaphore implements java.io.Serializable { * else {@code false} */ public Semaphore(int permits, boolean fair) { - sync = (fair)? new FairSync(permits) : new NonfairSync(permits); + sync = fair ? new FairSync(permits) : new NonfairSync(permits); } /** diff --git a/src/share/classes/java/util/concurrent/ThreadLocalRandom.java b/src/share/classes/java/util/concurrent/ThreadLocalRandom.java index c8a67dd651022703ce4bddcf8235fbbbedec4b2f..69f5fbcb40481b1350ba7921f8c7a9f7e260096e 100644 --- a/src/share/classes/java/util/concurrent/ThreadLocalRandom.java +++ b/src/share/classes/java/util/concurrent/ThreadLocalRandom.java @@ -63,9 +63,9 @@ import java.util.Random; */ public class ThreadLocalRandom extends Random { // same constants as Random, but must be redeclared because private - private final static long multiplier = 0x5DEECE66DL; - private final static long addend = 0xBL; - private final static long mask = (1L << 48) - 1; + private static final long multiplier = 0x5DEECE66DL; + private static final long addend = 0xBL; + private static final long mask = (1L << 48) - 1; /** * The random seed. We can't use super.seed. diff --git a/src/share/classes/java/util/concurrent/TimeUnit.java b/src/share/classes/java/util/concurrent/TimeUnit.java index 5a18a5b01c01c45c0675213f35d44be898199b35..236e553bc6c6b773971bcee742822c0645200476 100644 --- a/src/share/classes/java/util/concurrent/TimeUnit.java +++ b/src/share/classes/java/util/concurrent/TimeUnit.java @@ -53,12 +53,12 @@ package java.util.concurrent; * java.util.concurrent.locks.Lock lock} is not available: * *

      Lock lock = ...;
    - *  if ( lock.tryLock(50L, TimeUnit.MILLISECONDS) ) ...
    + *  if (lock.tryLock(50L, TimeUnit.MILLISECONDS)) ...
      * 
    * while this code will timeout in 50 seconds: *
      *  Lock lock = ...;
    - *  if ( lock.tryLock(50L, TimeUnit.SECONDS) ) ...
    + *  if (lock.tryLock(50L, TimeUnit.SECONDS)) ...
      * 
    * * Note however, that there is no guarantee that a particular timeout @@ -291,7 +291,8 @@ public enum TimeUnit { abstract int excessNanos(long d, long m); /** - * Performs a timed Object.wait using this time unit. + * Performs a timed {@link Object#wait(long, int) Object.wait} + * using this time unit. * This is a convenience method that converts timeout arguments * into the form required by the Object.wait method. * @@ -299,21 +300,22 @@ public enum TimeUnit { * method (see {@link BlockingQueue#poll BlockingQueue.poll}) * using: * - *
      public synchronized Object poll(long timeout, TimeUnit unit) throws InterruptedException {
    -     *    while (empty) {
    -     *      unit.timedWait(this, timeout);
    -     *      ...
    -     *    }
    -     *  }
    + *
     {@code
    +     * public synchronized Object poll(long timeout, TimeUnit unit)
    +     *     throws InterruptedException {
    +     *   while (empty) {
    +     *     unit.timedWait(this, timeout);
    +     *     ...
    +     *   }
    +     * }}
    * * @param obj the object to wait on * @param timeout the maximum time to wait. If less than * or equal to zero, do not wait at all. - * @throws InterruptedException if interrupted while waiting. - * @see Object#wait(long, int) + * @throws InterruptedException if interrupted while waiting */ public void timedWait(Object obj, long timeout) - throws InterruptedException { + throws InterruptedException { if (timeout > 0) { long ms = toMillis(timeout); int ns = excessNanos(timeout, ms); @@ -322,17 +324,18 @@ public enum TimeUnit { } /** - * Performs a timed Thread.join using this time unit. + * Performs a timed {@link Thread#join(long, int) Thread.join} + * using this time unit. * This is a convenience method that converts time arguments into the * form required by the Thread.join method. + * * @param thread the thread to wait for * @param timeout the maximum time to wait. If less than * or equal to zero, do not wait at all. - * @throws InterruptedException if interrupted while waiting. - * @see Thread#join(long, int) + * @throws InterruptedException if interrupted while waiting */ public void timedJoin(Thread thread, long timeout) - throws InterruptedException { + throws InterruptedException { if (timeout > 0) { long ms = toMillis(timeout); int ns = excessNanos(timeout, ms); @@ -341,13 +344,14 @@ public enum TimeUnit { } /** - * Performs a Thread.sleep using this unit. + * Performs a {@link Thread#sleep(long, int) Thread.sleep} using + * this time unit. * This is a convenience method that converts time arguments into the * form required by the Thread.sleep method. + * * @param timeout the minimum time to sleep. If less than * or equal to zero, do not sleep at all. - * @throws InterruptedException if interrupted while sleeping. - * @see Thread#sleep + * @throws InterruptedException if interrupted while sleeping */ public void sleep(long timeout) throws InterruptedException { if (timeout > 0) { diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java b/src/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java index 9073254b12264bf163b55716d1fb8ec7818db4f6..7ea3a8012d5f40712be2a7804adecdebd6ac01b5 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java @@ -55,7 +55,7 @@ import java.lang.reflect.*; * @author Doug Lea * @param The type of the object holding the updatable field */ -public abstract class AtomicIntegerFieldUpdater { +public abstract class AtomicIntegerFieldUpdater { /** * Creates and returns an updater for objects with the given field. * The Class argument is needed to check that reflective types and @@ -279,7 +279,7 @@ public abstract class AtomicIntegerFieldUpdater { sun.reflect.misc.ReflectUtil.ensureMemberAccess( caller, tclass, null, modifiers); sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass); - } catch(Exception ex) { + } catch (Exception ex) { throw new RuntimeException(ex); } diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java b/src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java index 8a81dbc9a8834e59a5eba639c40bca989a6f2cd2..22a1d5eecbea767bc38f5891d91a6e8b23c9bef4 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java @@ -55,7 +55,7 @@ import java.lang.reflect.*; * @author Doug Lea * @param The type of the object holding the updatable field */ -public abstract class AtomicLongFieldUpdater { +public abstract class AtomicLongFieldUpdater { /** * Creates and returns an updater for objects with the given field. * The Class argument is needed to check that reflective types and @@ -278,7 +278,7 @@ public abstract class AtomicLongFieldUpdater { sun.reflect.misc.ReflectUtil.ensureMemberAccess( caller, tclass, null, modifiers); sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass); - } catch(Exception ex) { + } catch (Exception ex) { throw new RuntimeException(ex); } @@ -331,7 +331,7 @@ public abstract class AtomicLongFieldUpdater { if (cclass.isInstance(obj)) { return; } - throw new RuntimeException ( + throw new RuntimeException( new IllegalAccessException("Class " + cclass.getName() + " can not access a protected member of class " + @@ -361,7 +361,7 @@ public abstract class AtomicLongFieldUpdater { sun.reflect.misc.ReflectUtil.ensureMemberAccess( caller, tclass, null, modifiers); sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass); - } catch(Exception ex) { + } catch (Exception ex) { throw new RuntimeException(ex); } @@ -387,7 +387,7 @@ public abstract class AtomicLongFieldUpdater { public boolean compareAndSet(T obj, long expect, long update) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); - synchronized(this) { + synchronized (this) { long v = unsafe.getLong(obj, offset); if (v != expect) return false; @@ -402,7 +402,7 @@ public abstract class AtomicLongFieldUpdater { public void set(T obj, long newValue) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); - synchronized(this) { + synchronized (this) { unsafe.putLong(obj, offset, newValue); } } @@ -413,7 +413,7 @@ public abstract class AtomicLongFieldUpdater { public long get(T obj) { if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj); - synchronized(this) { + synchronized (this) { return unsafe.getLong(obj, offset); } } @@ -422,7 +422,7 @@ public abstract class AtomicLongFieldUpdater { if (cclass.isInstance(obj)) { return; } - throw new RuntimeException ( + throw new RuntimeException( new IllegalAccessException("Class " + cclass.getName() + " can not access a protected member of class " + diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java b/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java index ec2083294707cb00d7f5abd6b768516b20d5364f..c58fd30139f487bb7392a11d8ad04a913e6cc37a 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java @@ -45,13 +45,13 @@ import java.lang.reflect.*; * independently subject to atomic updates. For example, a tree node * might be declared as * - *
    + *  
     {@code
      * class Node {
      *   private volatile Node left, right;
      *
    - *   private static final AtomicReferenceFieldUpdater<Node, Node> leftUpdater =
    + *   private static final AtomicReferenceFieldUpdater leftUpdater =
      *     AtomicReferenceFieldUpdater.newUpdater(Node.class, Node.class, "left");
    - *   private static AtomicReferenceFieldUpdater<Node, Node> rightUpdater =
    + *   private static AtomicReferenceFieldUpdater rightUpdater =
      *     AtomicReferenceFieldUpdater.newUpdater(Node.class, Node.class, "right");
      *
      *   Node getLeft() { return left;  }
    @@ -59,8 +59,7 @@ import java.lang.reflect.*;
      *     return leftUpdater.compareAndSet(this, expect, update);
      *   }
      *   // ... and so on
    - * }
    - * 
    + * }}
    * *

    Note that the guarantees of the {@code compareAndSet} * method in this class are weaker than in other atomic classes. @@ -74,7 +73,7 @@ import java.lang.reflect.*; * @param The type of the object holding the updatable field * @param The type of the field */ -public abstract class AtomicReferenceFieldUpdater { +public abstract class AtomicReferenceFieldUpdater { /** * Creates and returns an updater for objects with the given field. @@ -291,7 +290,7 @@ public abstract class AtomicReferenceFieldUpdater { if (cclass.isInstance(obj)) { return; } - throw new RuntimeException ( + throw new RuntimeException( new IllegalAccessException("Class " + cclass.getName() + " can not access a protected member of class " + diff --git a/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java b/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java index c45c2cef1f4739f085ffdc86aada4f3f25dbbecf..605276e27b517b60c40b4dd3b0e0fed03653d14c 100644 --- a/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java +++ b/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java @@ -990,7 +990,8 @@ public abstract class AbstractQueuedLongSynchronizer * can represent anything you like. * @throws InterruptedException if the current thread is interrupted */ - public final void acquireInterruptibly(long arg) throws InterruptedException { + public final void acquireInterruptibly(long arg) + throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (!tryAcquire(arg)) @@ -1014,7 +1015,8 @@ public abstract class AbstractQueuedLongSynchronizer * @return {@code true} if acquired; {@code false} if timed out * @throws InterruptedException if the current thread is interrupted */ - public final boolean tryAcquireNanos(long arg, long nanosTimeout) throws InterruptedException { + public final boolean tryAcquireNanos(long arg, long nanosTimeout) + throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); return tryAcquire(arg) || @@ -1070,7 +1072,8 @@ public abstract class AbstractQueuedLongSynchronizer * you like. * @throws InterruptedException if the current thread is interrupted */ - public final void acquireSharedInterruptibly(long arg) throws InterruptedException { + public final void acquireSharedInterruptibly(long arg) + throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (tryAcquireShared(arg) < 0) @@ -1093,7 +1096,8 @@ public abstract class AbstractQueuedLongSynchronizer * @return {@code true} if acquired; {@code false} if timed out * @throws InterruptedException if the current thread is interrupted */ - public final boolean tryAcquireSharedNanos(long arg, long nanosTimeout) throws InterruptedException { + public final boolean tryAcquireSharedNanos(long arg, long nanosTimeout) + throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); return tryAcquireShared(arg) >= 0 || @@ -1841,7 +1845,8 @@ public abstract class AbstractQueuedLongSynchronizer *

  • If interrupted while blocked in step 4, throw InterruptedException. * */ - public final long awaitNanos(long nanosTimeout) throws InterruptedException { + public final long awaitNanos(long nanosTimeout) + throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); Node node = addConditionWaiter(); @@ -1885,7 +1890,8 @@ public abstract class AbstractQueuedLongSynchronizer *
  • If timed out while blocked in step 4, return false, else true. * */ - public final boolean awaitUntil(Date deadline) throws InterruptedException { + public final boolean awaitUntil(Date deadline) + throws InterruptedException { if (deadline == null) throw new NullPointerException(); long abstime = deadline.getTime(); @@ -1928,7 +1934,8 @@ public abstract class AbstractQueuedLongSynchronizer *
  • If timed out while blocked in step 4, return false, else true. * */ - public final boolean await(long time, TimeUnit unit) throws InterruptedException { + public final boolean await(long time, TimeUnit unit) + throws InterruptedException { if (unit == null) throw new NullPointerException(); long nanosTimeout = unit.toNanos(time); @@ -2084,7 +2091,7 @@ public abstract class AbstractQueuedLongSynchronizer /** * CAS waitStatus field of a node. */ - private final static boolean compareAndSetWaitStatus(Node node, + private static final boolean compareAndSetWaitStatus(Node node, int expect, int update) { return unsafe.compareAndSwapInt(node, waitStatusOffset, @@ -2094,7 +2101,7 @@ public abstract class AbstractQueuedLongSynchronizer /** * CAS next field of a node. */ - private final static boolean compareAndSetNext(Node node, + private static final boolean compareAndSetNext(Node node, Node expect, Node update) { return unsafe.compareAndSwapObject(node, nextOffset, expect, update); diff --git a/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java b/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java index d17c5d08d0ea11723e93fdd1c24d8c53d9acc035..8075aea7dea47df3fa62fd0b2e2d95ea76dc6a6c 100644 --- a/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java +++ b/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java @@ -265,7 +265,7 @@ import sun.misc.Unsafe; * boolean isSignalled() { return getState() != 0; } * * protected int tryAcquireShared(int ignore) { - * return isSignalled()? 1 : -1; + * return isSignalled() ? 1 : -1; * } * * protected boolean tryReleaseShared(int ignore) { @@ -1213,7 +1213,8 @@ public abstract class AbstractQueuedSynchronizer * can represent anything you like. * @throws InterruptedException if the current thread is interrupted */ - public final void acquireInterruptibly(int arg) throws InterruptedException { + public final void acquireInterruptibly(int arg) + throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (!tryAcquire(arg)) @@ -1237,7 +1238,8 @@ public abstract class AbstractQueuedSynchronizer * @return {@code true} if acquired; {@code false} if timed out * @throws InterruptedException if the current thread is interrupted */ - public final boolean tryAcquireNanos(int arg, long nanosTimeout) throws InterruptedException { + public final boolean tryAcquireNanos(int arg, long nanosTimeout) + throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); return tryAcquire(arg) || @@ -1293,7 +1295,8 @@ public abstract class AbstractQueuedSynchronizer * you like. * @throws InterruptedException if the current thread is interrupted */ - public final void acquireSharedInterruptibly(int arg) throws InterruptedException { + public final void acquireSharedInterruptibly(int arg) + throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (tryAcquireShared(arg) < 0) @@ -1316,7 +1319,8 @@ public abstract class AbstractQueuedSynchronizer * @return {@code true} if acquired; {@code false} if timed out * @throws InterruptedException if the current thread is interrupted */ - public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout) throws InterruptedException { + public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout) + throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); return tryAcquireShared(arg) >= 0 || @@ -2062,7 +2066,8 @@ public abstract class AbstractQueuedSynchronizer *
  • If interrupted while blocked in step 4, throw InterruptedException. * */ - public final long awaitNanos(long nanosTimeout) throws InterruptedException { + public final long awaitNanos(long nanosTimeout) + throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); Node node = addConditionWaiter(); @@ -2106,7 +2111,8 @@ public abstract class AbstractQueuedSynchronizer *
  • If timed out while blocked in step 4, return false, else true. * */ - public final boolean awaitUntil(Date deadline) throws InterruptedException { + public final boolean awaitUntil(Date deadline) + throws InterruptedException { if (deadline == null) throw new NullPointerException(); long abstime = deadline.getTime(); @@ -2149,7 +2155,8 @@ public abstract class AbstractQueuedSynchronizer *
  • If timed out while blocked in step 4, return false, else true. * */ - public final boolean await(long time, TimeUnit unit) throws InterruptedException { + public final boolean await(long time, TimeUnit unit) + throws InterruptedException { if (unit == null) throw new NullPointerException(); long nanosTimeout = unit.toNanos(time); @@ -2305,7 +2312,7 @@ public abstract class AbstractQueuedSynchronizer /** * CAS waitStatus field of a node. */ - private final static boolean compareAndSetWaitStatus(Node node, + private static final boolean compareAndSetWaitStatus(Node node, int expect, int update) { return unsafe.compareAndSwapInt(node, waitStatusOffset, @@ -2315,7 +2322,7 @@ public abstract class AbstractQueuedSynchronizer /** * CAS next field of a node. */ - private final static boolean compareAndSetNext(Node node, + private static final boolean compareAndSetNext(Node node, Node expect, Node update) { return unsafe.compareAndSwapObject(node, nextOffset, expect, update); diff --git a/src/share/classes/java/util/concurrent/locks/LockSupport.java b/src/share/classes/java/util/concurrent/locks/LockSupport.java index 9751f418c17270ced5511dcf844f7c2470b4f107..9c966406b313d0ab39c0c60cc83a127bceb34a9f 100644 --- a/src/share/classes/java/util/concurrent/locks/LockSupport.java +++ b/src/share/classes/java/util/concurrent/locks/LockSupport.java @@ -200,8 +200,8 @@ public class LockSupport { *
  • Some other thread invokes {@link #unpark unpark} with the * current thread as the target; or * - *
  • Some other thread {@linkplain Thread#interrupt interrupts} the current - * thread; or + *
  • Some other thread {@linkplain Thread#interrupt interrupts} + * the current thread; or * *
  • The specified waiting time elapses; or * diff --git a/src/share/classes/java/util/concurrent/locks/ReentrantLock.java b/src/share/classes/java/util/concurrent/locks/ReentrantLock.java index 9cc3bf4d011159dae01f1ebd73090c1a1002100e..4cbc562b82015113a30083570f71c442ea966e44 100644 --- a/src/share/classes/java/util/concurrent/locks/ReentrantLock.java +++ b/src/share/classes/java/util/concurrent/locks/ReentrantLock.java @@ -116,7 +116,7 @@ public class ReentrantLock implements Lock, java.io.Serializable { * into fair and nonfair versions below. Uses AQS state to * represent the number of holds on the lock. */ - static abstract class Sync extends AbstractQueuedSynchronizer { + abstract static class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = -5179523762034025860L; /** @@ -200,7 +200,7 @@ public class ReentrantLock implements Lock, java.io.Serializable { /** * Sync object for non-fair locks */ - final static class NonfairSync extends Sync { + static final class NonfairSync extends Sync { private static final long serialVersionUID = 7316153563782823691L; /** @@ -222,7 +222,7 @@ public class ReentrantLock implements Lock, java.io.Serializable { /** * Sync object for fair locks */ - final static class FairSync extends Sync { + static final class FairSync extends Sync { private static final long serialVersionUID = -3000897897090466540L; final void lock() { @@ -269,7 +269,7 @@ public class ReentrantLock implements Lock, java.io.Serializable { * @param fair {@code true} if this lock should use a fair ordering policy */ public ReentrantLock(boolean fair) { - sync = (fair)? new FairSync() : new NonfairSync(); + sync = fair ? new FairSync() : new NonfairSync(); } /** @@ -440,7 +440,8 @@ public class ReentrantLock implements Lock, java.io.Serializable { * @throws NullPointerException if the time unit is null * */ - public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { + public boolean tryLock(long timeout, TimeUnit unit) + throws InterruptedException { return sync.tryAcquireNanos(1, unit.toNanos(timeout)); } diff --git a/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java b/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java index b327b65c4de00b85693c4dc6a0a37eb63aefdbbd..39b9c0e894dfaf8080e20ba2d9a2cb8b2da14035 100644 --- a/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java +++ b/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java @@ -155,7 +155,7 @@ import java.util.*; * } * // Downgrade by acquiring read lock before releasing write lock * rwl.readLock().lock(); - * } finally { + * } finally { * rwl.writeLock().unlock(); // Unlock write, still hold read * } * } @@ -215,7 +215,8 @@ import java.util.*; * @author Doug Lea * */ -public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializable { +public class ReentrantReadWriteLock + implements ReadWriteLock, java.io.Serializable { private static final long serialVersionUID = -6992448646407690164L; /** Inner class providing readlock */ private final ReentrantReadWriteLock.ReadLock readerLock; @@ -251,7 +252,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab * Synchronization implementation for ReentrantReadWriteLock. * Subclassed into fair and nonfair versions. */ - static abstract class Sync extends AbstractQueuedSynchronizer { + abstract static class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 6317671515068378041L; /* @@ -618,7 +619,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab final Thread getOwner() { // Must read state before owner to ensure memory consistency - return ((exclusiveCount(getState()) == 0)? + return ((exclusiveCount(getState()) == 0) ? null : getExclusiveOwnerThread()); } @@ -669,7 +670,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab /** * Nonfair version of Sync */ - final static class NonfairSync extends Sync { + static final class NonfairSync extends Sync { private static final long serialVersionUID = -8159625535654395037L; final boolean writerShouldBlock() { return false; // writers can always barge @@ -689,7 +690,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab /** * Fair version of Sync */ - final static class FairSync extends Sync { + static final class FairSync extends Sync { private static final long serialVersionUID = -2274990926593161451L; final boolean writerShouldBlock() { return hasQueuedPredecessors(); @@ -702,7 +703,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab /** * The lock returned by method {@link ReentrantReadWriteLock#readLock}. */ - public static class ReadLock implements Lock, java.io.Serializable { + public static class ReadLock implements Lock, java.io.Serializable { private static final long serialVersionUID = -5992448646407690164L; private final Sync sync; @@ -867,7 +868,8 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab * @throws NullPointerException if the time unit is null * */ - public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { + public boolean tryLock(long timeout, TimeUnit unit) + throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); } @@ -908,7 +910,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab /** * The lock returned by method {@link ReentrantReadWriteLock#writeLock}. */ - public static class WriteLock implements Lock, java.io.Serializable { + public static class WriteLock implements Lock, java.io.Serializable { private static final long serialVersionUID = -4992448646407690164L; private final Sync sync; @@ -1108,7 +1110,8 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab * @throws NullPointerException if the time unit is null * */ - public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { + public boolean tryLock(long timeout, TimeUnit unit) + throws InterruptedException { return sync.tryAcquireNanos(1, unit.toNanos(timeout)); } diff --git a/src/share/classes/javax/security/auth/Policy.java b/src/share/classes/javax/security/auth/Policy.java index 6c508b2ce95eb5cd68ae57ee9e21c0250893796d..88264b3fc49e9d1f17b5f8bd7f9c43a901ca9d7c 100644 --- a/src/share/classes/javax/security/auth/Policy.java +++ b/src/share/classes/javax/security/auth/Policy.java @@ -25,6 +25,9 @@ package javax.security.auth; +import java.security.Security; +import sun.security.util.Debug; + /** *

    This is an abstract class for representing the system policy for * Subject-based authorization. A subclass implementation @@ -159,6 +162,10 @@ public abstract class Policy { private static Policy policy; private static ClassLoader contextClassLoader; + // true if a custom (not com.sun.security.auth.PolicyFile) system-wide + // policy object is set + private static boolean isCustomPolicy; + static { contextClassLoader = java.security.AccessController.doPrivileged (new java.security.PrivilegedAction() { @@ -234,6 +241,8 @@ public abstract class Policy { contextClassLoader).newInstance(); } }); + isCustomPolicy = + !finalClass.equals("com.sun.security.auth.PolicyFile"); } catch (Exception e) { throw new SecurityException (sun.security.util.ResourcesMgr.getString @@ -265,6 +274,46 @@ public abstract class Policy { java.lang.SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(new AuthPermission("setPolicy")); Policy.policy = policy; + // all non-null policy objects are assumed to be custom + isCustomPolicy = policy != null ? true : false; + } + + /** + * Returns true if a custom (not com.sun.security.auth.PolicyFile) + * system-wide policy object has been set or installed. This method is + * called by SubjectDomainCombiner to provide backwards compatibility for + * developers that provide their own javax.security.auth.Policy + * implementations. + * + * @return true if a custom (not com.sun.security.auth.PolicyFile) + * system-wide policy object has been set; false otherwise + */ + static boolean isCustomPolicySet(Debug debug) { + if (policy != null) { + if (debug != null && isCustomPolicy) { + debug.println("Providing backwards compatibility for " + + "javax.security.auth.policy implementation: " + + policy.toString()); + } + return isCustomPolicy; + } + // check if custom policy has been set using auth.policy.provider prop + String policyClass = java.security.AccessController.doPrivileged + (new java.security.PrivilegedAction() { + public String run() { + return Security.getProperty("auth.policy.provider"); + } + }); + if (policyClass != null + && !policyClass.equals("com.sun.security.auth.PolicyFile")) { + if (debug != null) { + debug.println("Providing backwards compatibility for " + + "javax.security.auth.policy implementation: " + + policyClass); + } + return true; + } + return false; } /** diff --git a/src/share/classes/javax/security/auth/SubjectDomainCombiner.java b/src/share/classes/javax/security/auth/SubjectDomainCombiner.java index 00d57f6c6daa59684d91a6a69842995cd2f72bcd..9dc82fc0153a37f72c6114847a4ecec21e569f68 100644 --- a/src/share/classes/javax/security/auth/SubjectDomainCombiner.java +++ b/src/share/classes/javax/security/auth/SubjectDomainCombiner.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved. * 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,8 +26,6 @@ package javax.security.auth; import java.security.AccessController; -import java.security.AccessControlContext; -import java.security.AllPermission; import java.security.Permission; import java.security.Permissions; import java.security.PermissionCollection; @@ -35,10 +33,8 @@ import java.security.Policy; import java.security.Principal; import java.security.PrivilegedAction; import java.security.ProtectionDomain; -import java.lang.ClassLoader; import java.security.Security; import java.util.Set; -import java.util.Iterator; import java.util.WeakHashMap; import java.lang.ref.WeakReference; @@ -61,7 +57,8 @@ public class SubjectDomainCombiner implements java.security.DomainCombiner { "\t[SubjectDomainCombiner]"); // Note: check only at classloading time, not dynamically during combine() - private static final boolean useJavaxPolicy = compatPolicy(); + private static final boolean useJavaxPolicy = + javax.security.auth.Policy.isCustomPolicySet(debug); // Relevant only when useJavaxPolicy is true private static final boolean allowCaching = @@ -202,8 +199,8 @@ public class SubjectDomainCombiner implements java.security.DomainCombiner { return null; } - // maintain backwards compatibility for people who provide - // their own javax.security.auth.Policy implementations + // maintain backwards compatibility for developers who provide + // their own custom javax.security.auth.Policy implementations if (useJavaxPolicy) { return combineJavaxPolicy(currentDomains, assignedDomains); } @@ -476,8 +473,7 @@ public class SubjectDomainCombiner implements java.security.DomainCombiner { String s = AccessController.doPrivileged (new PrivilegedAction() { public String run() { - return java.security.Security.getProperty - ("cache.auth.policy"); + return Security.getProperty("cache.auth.policy"); } }); if (s != null) { @@ -488,29 +484,6 @@ public class SubjectDomainCombiner implements java.security.DomainCombiner { return true; } - // maintain backwards compatibility for people who provide - // their own javax.security.auth.Policy implementations - private static boolean compatPolicy() { - javax.security.auth.Policy javaxPolicy = AccessController.doPrivileged - (new PrivilegedAction() { - public javax.security.auth.Policy run() { - return javax.security.auth.Policy.getPolicy(); - } - }); - - if (!(javaxPolicy instanceof com.sun.security.auth.PolicyFile)) { - if (debug != null) { - debug.println("Providing backwards compatibility for " + - "javax.security.auth.policy implementation: " + - javaxPolicy.toString()); - } - - return true; - } else { - return false; - } - } - private static void printInputDomains(ProtectionDomain[] currentDomains, ProtectionDomain[] assignedDomains) { if (currentDomains == null || currentDomains.length == 0) { diff --git a/src/share/classes/javax/swing/GroupLayout.java b/src/share/classes/javax/swing/GroupLayout.java index 7628076a99473e2a368b816f09d82aea90967220..9219932776ed301462aa613e838a81df0d352019 100644 --- a/src/share/classes/javax/swing/GroupLayout.java +++ b/src/share/classes/javax/swing/GroupLayout.java @@ -653,6 +653,10 @@ public class GroupLayout implements LayoutManager2 { */ public ParallelGroup createParallelGroup(Alignment alignment, boolean resizable){ + if (alignment == null) { + throw new IllegalArgumentException("alignment must be non null"); + } + if (alignment == Alignment.BASELINE) { return new BaselineGroup(resizable); } diff --git a/src/share/classes/javax/swing/JComponent.java b/src/share/classes/javax/swing/JComponent.java index 6f017402ec7e01e9d8f6b1bc480a35ae7c38e0e8..78fddfcb11bb877c93da708b0fb05fa7d65ca947 100644 --- a/src/share/classes/javax/swing/JComponent.java +++ b/src/share/classes/javax/swing/JComponent.java @@ -4734,6 +4734,8 @@ public abstract class JComponent extends Container implements Serializable, * Notifies this component that it now has a parent component. * When this method is invoked, the chain of parent components is * set up with KeyboardAction event listeners. + * This method is called by the toolkit internally and should + * not be called directly by programs. * * @see #registerKeyboardAction */ @@ -4750,6 +4752,8 @@ public abstract class JComponent extends Container implements Serializable, * Notifies this component that it no longer has a parent component. * When this method is invoked, any KeyboardActions * set up in the the chain of parent components are removed. + * This method is called by the toolkit internally and should + * not be called directly by programs. * * @see #registerKeyboardAction */ diff --git a/src/share/classes/javax/swing/Popup.java b/src/share/classes/javax/swing/Popup.java index a77d574d72ecb4d45d77603ecad34d236913ee20..83cd7d6d789c6e9462fc241799e783f86a57adb4 100644 --- a/src/share/classes/javax/swing/Popup.java +++ b/src/share/classes/javax/swing/Popup.java @@ -156,7 +156,8 @@ public class Popup { component.setLocation(ownerX, ownerY); component.getContentPane().add(contents, BorderLayout.CENTER); - contents.invalidate(); + component.invalidate(); + component.validate(); if(component.isVisible()) { // Do not call pack() if window is not visible to // avoid early native peer creation diff --git a/src/share/classes/javax/swing/text/DefaultHighlighter.java b/src/share/classes/javax/swing/text/DefaultHighlighter.java index d90128b82ac17f81f6503b5334405eba9d8a5dde..dc68ae474fd60305ae2e796cc0ad6ef44b1a93ae 100644 --- a/src/share/classes/javax/swing/text/DefaultHighlighter.java +++ b/src/share/classes/javax/swing/text/DefaultHighlighter.java @@ -113,6 +113,14 @@ public class DefaultHighlighter extends LayeredHighlighter { * @exception BadLocationException if the specified location is invalid */ public Object addHighlight(int p0, int p1, Highlighter.HighlightPainter p) throws BadLocationException { + if (p0 < 0) { + throw new BadLocationException("Invalid start offset", p0); + } + + if (p1 < p0) { + throw new BadLocationException("Invalid end offset", p1); + } + Document doc = component.getDocument(); HighlightInfo i = (getDrawsLayeredHighlights() && (p instanceof LayeredHighlighter.LayerPainter)) ? @@ -217,6 +225,14 @@ public class DefaultHighlighter extends LayeredHighlighter { * @exception BadLocationException if the specified location is invalid */ public void changeHighlight(Object tag, int p0, int p1) throws BadLocationException { + if (p0 < 0) { + throw new BadLocationException("Invalid beginning of the range", p0); + } + + if (p1 < p0) { + throw new BadLocationException("Invalid end of the range", p1); + } + Document doc = component.getDocument(); if (tag instanceof LayeredHighlightInfo) { LayeredHighlightInfo lhi = (LayeredHighlightInfo)tag; diff --git a/src/share/classes/sun/awt/UngrabEvent.java b/src/share/classes/sun/awt/UngrabEvent.java index e27e04068304e6aabdaebbd2be39de5a8ab1911a..7c1b8ecf9f515092238f9c7841c4dcf982bec1dd 100644 --- a/src/share/classes/sun/awt/UngrabEvent.java +++ b/src/share/classes/sun/awt/UngrabEvent.java @@ -40,8 +40,10 @@ import java.awt.Component; *

    To listen for this event, install AWTEventListener with {@value sun.awt.SunToolkit#GRAB_EVENT_MASK} */ public class UngrabEvent extends AWTEvent { + private final static int UNGRAB_EVENT_ID = 1998; + public UngrabEvent(Component source) { - super(source, 0xffff); + super(source, UNGRAB_EVENT_ID); } public String toString() { diff --git a/src/share/classes/sun/launcher/LauncherHelper.java b/src/share/classes/sun/launcher/LauncherHelper.java index cba795968c69c0875894aed1da6f67ebe74ac60f..dbaebc0ee862d9a465cc4b7ae77cef0e8987425f 100644 --- a/src/share/classes/sun/launcher/LauncherHelper.java +++ b/src/share/classes/sun/launcher/LauncherHelper.java @@ -44,8 +44,16 @@ import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.math.BigDecimal; +import java.math.MathContext; +import java.math.RoundingMode; import java.util.ResourceBundle; import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Properties; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; @@ -59,6 +67,17 @@ public enum LauncherHelper { private static StringBuilder outBuf = new StringBuilder(); private static ResourceBundle javarb = null; + + private static final String INDENT = " "; + private static final String VM_SETTINGS = "VM settings:"; + private static final String PROP_SETTINGS = "Property settings:"; + private static final String LOCALE_SETTINGS = "Locale settings:"; + + private static final long K = 1024; + private static final long M = K * K; + private static final long G = M * K; + private static final long T = G * K; + private static synchronized ResourceBundle getLauncherResourceBundle() { if (javarb == null) { javarb = ResourceBundle.getBundle(defaultBundleName); @@ -66,6 +85,184 @@ public enum LauncherHelper { return javarb; } + /* + * A method called by the launcher to print out the standard settings, + * by default -XshowSettings is equivalent to -XshowSettings:all, + * Specific information may be gotten by using suboptions with possible + * values vm, properties and locale. + * + * printToStderr: choose between stdout and stderr + * + * optionFlag: specifies which options to print default is all other + * possible values are vm, properties, locale. + * + * maxHeapSize: in bytes, as set by the launcher, a zero-value indicates + * this code should determine this value, using a suitable method. + * + * stackSize: in bytes, as set by the launcher, a zero-value indicates + * this code determine this value, using a suitable method. + */ + static void showSettings(boolean printToStderr, String optionFlag, + long maxHeapSize, long stackSize, boolean isServer) { + + PrintStream ostream = (printToStderr) ? System.err : System.out; + String opts[] = optionFlag.split(":"); + String optStr = (opts.length > 1 && opts[1] != null) + ? opts[1].trim() + : "all"; + switch (optStr) { + case "vm": + printVmSettings(ostream, maxHeapSize, stackSize, isServer); + break; + case "properties": + printProperties(ostream); + break; + case "locale": + printLocale(ostream); + break; + default: + printVmSettings(ostream, maxHeapSize, stackSize, isServer); + printProperties(ostream); + printLocale(ostream); + break; + } + } + + /* + * prints the main vm settings subopt/section + */ + private static void printVmSettings(PrintStream ostream, long maxHeapSize, + long stackSize, boolean isServer) { + + ostream.println(VM_SETTINGS); + if (stackSize != 0L) { + ostream.println(INDENT + "Stack Size: " + scaleValue(stackSize)); + } + if (maxHeapSize != 0L) { + ostream.println(INDENT + "Max. Heap Size: " + scaleValue(maxHeapSize)); + } else { + ostream.println(INDENT + "Max. Heap Size (Estimated): " + + scaleValue(Runtime.getRuntime().maxMemory())); + } + ostream.println(INDENT + "Ergonomics Machine Class: " + + ((isServer) ? "server" : "client")); + ostream.println(INDENT + "Using VM: " + + System.getProperty("java.vm.name")); + ostream.println(); + } + + /* + * scale the incoming values to a human readable form, represented as + * K, M, G and T, see java.c parse_size for the scaled values and + * suffixes. + */ + + private static String scaleValue(double v) { + MathContext mc2 = new MathContext(3, RoundingMode.HALF_EVEN); + + if (v >= K && v < M) { + return (new BigDecimal(v / K, mc2)).toPlainString() + "K"; + } else if (v >= M && v < G) { + return (new BigDecimal(v / M, mc2)).toPlainString() + "M"; + } else if (v >= G && v < T) { + return (new BigDecimal(v / G, mc2)).toPlainString() + "G"; + } else if (v >= T) { + return (new BigDecimal(v / T, mc2)).toPlainString() + "T"; + } else { + return String.format("%.0f", v); + } + } + + /* + * prints the properties subopt/section + */ + private static void printProperties(PrintStream ostream) { + Properties p = System.getProperties(); + ostream.println(PROP_SETTINGS); + List sortedPropertyKeys = new ArrayList<>(); + sortedPropertyKeys.addAll(p.stringPropertyNames()); + Collections.sort(sortedPropertyKeys); + for (String x : sortedPropertyKeys) { + printPropertyValue(ostream, x, p.getProperty(x)); + } + ostream.println(); + } + + private static boolean isPath(String key) { + return key.endsWith(".dirs") || key.endsWith(".path"); + } + + private static void printPropertyValue(PrintStream ostream, + String key, String value) { + ostream.print(INDENT + key + " = "); + if (key.equals("line.separator")) { + byte[] bytes = value.getBytes(); + for (byte b : bytes) { + switch (b) { + case 0xd: + ostream.print("CR "); + break; + case 0xa: + ostream.print("LF "); + break; + default: + ostream.printf("0x%02X", b & 0xff); + break; + } + } + ostream.println(); + return; + } + if (!isPath(key)) { + ostream.println(value); + return; + } + // pretty print the path values as a list + String[] values = value.split(System.getProperty("path.separator")); + int len = values.length; + for (int i = 0 ; i < len ; i++) { + if (i == 0) { // first line treated specially + ostream.println(values[i]); + } else { // following lines prefix with indents + ostream.print(INDENT + INDENT); + ostream.println(values[i]); + } + } + } + + /* + * prints the locale subopt/section + */ + private static void printLocale(PrintStream ostream) { + Locale locale = Locale.getDefault(); + ostream.println(LOCALE_SETTINGS); + ostream.println(INDENT + "default locale = " + locale.getDisplayLanguage()); + printLocales(ostream); + ostream.println(); + } + + private static void printLocales(PrintStream ostream) { + Locale[] locales = Locale.getAvailableLocales(); + final int len = locales == null ? 0 : locales.length; + if (len < 1 ) { + return; + } + ostream.print(INDENT + "available locales = "); + final int last = len - 1 ; + for (int i = 0; i < last ; i++) { + ostream.print(locales[i]); + if (i != last) { + ostream.print(", "); + } + // print columns of 8 + if ((i + 1) % 8 == 0) { + ostream.println(); + ostream.print(INDENT + INDENT); + } + } + ostream.println(locales[last]); + } + /** * A private helper method to get a localized message and also * apply any arguments that we might pass. diff --git a/src/share/classes/sun/launcher/resources/launcher.properties b/src/share/classes/sun/launcher/resources/launcher.properties index e89d147a5bba82b96edc51d297343ec426729607..17ba48a13842ea68a03ea9231f69fc344b550e7e 100644 --- a/src/share/classes/sun/launcher/resources/launcher.properties +++ b/src/share/classes/sun/launcher/resources/launcher.properties @@ -1,5 +1,5 @@ # -# Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. # 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,7 +97,15 @@ java.launcher.X.usage=\ \ -Xcheck:jni perform additional checks for JNI functions\n\ \ -Xshare:off do not attempt to use shared class data\n\ \ -Xshare:auto use shared class data if possible (default)\n\ -\ -Xshare:on require using shared class data, otherwise fail.\n\n\ +\ -Xshare:on require using shared class data, otherwise fail.\n\ +\ -XshowSettings show all settings and continue\n\ +\ -XshowSettings:all\n\ +\ show all settings and continue\n\ +\ -XshowSettings:vm show all vm related settings and continue\n\ +\ -XshowSettings:properties\n\ +\ show all property settings and continue\n\ +\ -XshowSettings:locale\n\ +\ show all locale related settings and continue\n\n\ The -X options are non-standard and subject to change without notice.\n java.launcher.cls.error1=\ diff --git a/src/share/classes/sun/misc/FpUtils.java b/src/share/classes/sun/misc/FpUtils.java index 72ac47eee368e02c825fa9953f442410887dd6e0..21ea7c29a4431a7afb964fd03c57d2e345f6d5fa 100644 --- a/src/share/classes/sun/misc/FpUtils.java +++ b/src/share/classes/sun/misc/FpUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2010 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,9 +29,9 @@ import sun.misc.FloatConsts; import sun.misc.DoubleConsts; /** - * The class FpUtils contains static utility methods for - * manipulating and inspecting float and - * double floating-point numbers. These methods include + * The class {@code FpUtils} contains static utility methods for + * manipulating and inspecting {@code float} and + * {@code double} floating-point numbers. These methods include * functionality recommended or required by the IEEE 754 * floating-point standard. * @@ -136,7 +136,7 @@ public class FpUtils { // tests for exception cases. /** - * Returns unbiased exponent of a double. + * Returns unbiased exponent of a {@code double}. */ public static int getExponent(double d){ /* @@ -149,7 +149,7 @@ public class FpUtils { } /** - * Returns unbiased exponent of a float. + * Returns unbiased exponent of a {@code float}. */ public static int getExponent(float f){ /* @@ -185,15 +185,15 @@ public class FpUtils { * Returns the first floating-point argument with the sign of the * second floating-point argument. Note that unlike the {@link * FpUtils#copySign(double, double) copySign} method, this method - * does not require NaN sign arguments to be treated + * does not require NaN {@code sign} arguments to be treated * as positive values; implementations are permitted to treat some * NaN arguments as positive and other NaN arguments as negative * to allow greater performance. * * @param magnitude the parameter providing the magnitude of the result * @param sign the parameter providing the sign of the result - * @return a value with the magnitude of magnitude - * and the sign of sign. + * @return a value with the magnitude of {@code magnitude} + * and the sign of {@code sign}. * @author Joseph D. Darcy */ public static double rawCopySign(double magnitude, double sign) { @@ -208,15 +208,15 @@ public class FpUtils { * Returns the first floating-point argument with the sign of the * second floating-point argument. Note that unlike the {@link * FpUtils#copySign(float, float) copySign} method, this method - * does not require NaN sign arguments to be treated + * does not require NaN {@code sign} arguments to be treated * as positive values; implementations are permitted to treat some * NaN arguments as positive and other NaN arguments as negative * to allow greater performance. * * @param magnitude the parameter providing the magnitude of the result * @param sign the parameter providing the sign of the result - * @return a value with the magnitude of magnitude - * and the sign of sign. + * @return a value with the magnitude of {@code magnitude} + * and the sign of {@code sign}. * @author Joseph D. Darcy */ public static float rawCopySign(float magnitude, float sign) { @@ -230,129 +230,129 @@ public class FpUtils { /* ***************************************************************** */ /** - * Returns true if the argument is a finite - * floating-point value; returns false otherwise (for + * Returns {@code true} if the argument is a finite + * floating-point value; returns {@code false} otherwise (for * NaN and infinity arguments). * - * @param d the double value to be tested - * @return true if the argument is a finite - * floating-point value, false otherwise. + * @param d the {@code double} value to be tested + * @return {@code true} if the argument is a finite + * floating-point value, {@code false} otherwise. */ public static boolean isFinite(double d) { return Math.abs(d) <= DoubleConsts.MAX_VALUE; } /** - * Returns true if the argument is a finite - * floating-point value; returns false otherwise (for + * Returns {@code true} if the argument is a finite + * floating-point value; returns {@code false} otherwise (for * NaN and infinity arguments). * - * @param f the float value to be tested - * @return true if the argument is a finite - * floating-point value, false otherwise. + * @param f the {@code float} value to be tested + * @return {@code true} if the argument is a finite + * floating-point value, {@code false} otherwise. */ public static boolean isFinite(float f) { return Math.abs(f) <= FloatConsts.MAX_VALUE; } /** - * Returns true if the specified number is infinitely - * large in magnitude, false otherwise. + * Returns {@code true} if the specified number is infinitely + * large in magnitude, {@code false} otherwise. * *

    Note that this method is equivalent to the {@link * Double#isInfinite(double) Double.isInfinite} method; the * functionality is included in this class for convenience. * * @param d the value to be tested. - * @return true if the value of the argument is positive - * infinity or negative infinity; false otherwise. + * @return {@code true} if the value of the argument is positive + * infinity or negative infinity; {@code false} otherwise. */ public static boolean isInfinite(double d) { return Double.isInfinite(d); } /** - * Returns true if the specified number is infinitely - * large in magnitude, false otherwise. + * Returns {@code true} if the specified number is infinitely + * large in magnitude, {@code false} otherwise. * *

    Note that this method is equivalent to the {@link * Float#isInfinite(float) Float.isInfinite} method; the * functionality is included in this class for convenience. * * @param f the value to be tested. - * @return true if the argument is positive infinity or - * negative infinity; false otherwise. + * @return {@code true} if the argument is positive infinity or + * negative infinity; {@code false} otherwise. */ public static boolean isInfinite(float f) { return Float.isInfinite(f); } /** - * Returns true if the specified number is a - * Not-a-Number (NaN) value, false otherwise. + * Returns {@code true} if the specified number is a + * Not-a-Number (NaN) value, {@code false} otherwise. * *

    Note that this method is equivalent to the {@link * Double#isNaN(double) Double.isNaN} method; the functionality is * included in this class for convenience. * * @param d the value to be tested. - * @return true if the value of the argument is NaN; - * false otherwise. + * @return {@code true} if the value of the argument is NaN; + * {@code false} otherwise. */ public static boolean isNaN(double d) { return Double.isNaN(d); } /** - * Returns true if the specified number is a - * Not-a-Number (NaN) value, false otherwise. + * Returns {@code true} if the specified number is a + * Not-a-Number (NaN) value, {@code false} otherwise. * *

    Note that this method is equivalent to the {@link * Float#isNaN(float) Float.isNaN} method; the functionality is * included in this class for convenience. * * @param f the value to be tested. - * @return true if the argument is NaN; - * false otherwise. + * @return {@code true} if the argument is NaN; + * {@code false} otherwise. */ public static boolean isNaN(float f) { return Float.isNaN(f); } /** - * Returns true if the unordered relation holds + * Returns {@code true} if the unordered relation holds * between the two arguments. When two floating-point values are * unordered, one value is neither less than, equal to, nor * greater than the other. For the unordered relation to be true, - * at least one argument must be a NaN. + * at least one argument must be a {@code NaN}. * * @param arg1 the first argument * @param arg2 the second argument - * @return true if at least one argument is a NaN, - * false otherwise. + * @return {@code true} if at least one argument is a NaN, + * {@code false} otherwise. */ public static boolean isUnordered(double arg1, double arg2) { return isNaN(arg1) || isNaN(arg2); } /** - * Returns true if the unordered relation holds + * Returns {@code true} if the unordered relation holds * between the two arguments. When two floating-point values are * unordered, one value is neither less than, equal to, nor * greater than the other. For the unordered relation to be true, - * at least one argument must be a NaN. + * at least one argument must be a {@code NaN}. * * @param arg1 the first argument * @param arg2 the second argument - * @return true if at least one argument is a NaN, - * false otherwise. + * @return {@code true} if at least one argument is a NaN, + * {@code false} otherwise. */ public static boolean isUnordered(float arg1, float arg2) { return isNaN(arg1) || isNaN(arg2); } /** - * Returns unbiased exponent of a double; for + * Returns unbiased exponent of a {@code double}; for * subnormal values, the number is treated as if it were * normalized. That is for all finite, non-zero, positive numbers * x, scalb(x, -ilogb(x)) is @@ -378,7 +378,6 @@ public class FpUtils { return (1<<30); // 2^30 else // infinite value return (1<<28); // 2^28 - // break; case DoubleConsts.MIN_EXPONENT-1: // zero or subnormal if(d == 0.0) { @@ -414,18 +413,16 @@ public class FpUtils { exponent < DoubleConsts.MIN_EXPONENT); return exponent; } - // break; default: assert( exponent >= DoubleConsts.MIN_EXPONENT && exponent <= DoubleConsts.MAX_EXPONENT); return exponent; - // break; } } /** - * Returns unbiased exponent of a float; for + * Returns unbiased exponent of a {@code float}; for * subnormal values, the number is treated as if it were * normalized. That is for all finite, non-zero, positive numbers * x, scalb(x, -ilogb(x)) is @@ -451,7 +448,6 @@ public class FpUtils { return (1<<30); // 2^30 else // infinite value return (1<<28); // 2^28 - // break; case FloatConsts.MIN_EXPONENT-1: // zero or subnormal if(f == 0.0f) { @@ -487,13 +483,11 @@ public class FpUtils { exponent < FloatConsts.MIN_EXPONENT); return exponent; } - // break; default: assert( exponent >= FloatConsts.MIN_EXPONENT && exponent <= FloatConsts.MAX_EXPONENT); return exponent; - // break; } } @@ -534,22 +528,22 @@ public class FpUtils { */ /** - * Return d × - * 2scale_factor rounded as if performed + * Return {@code d} × + * 2{@code scale_factor} rounded as if performed * by a single correctly rounded floating-point multiply to a * member of the double value set. See §4.2.3 * of the Java * Language Specification for a discussion of floating-point * value sets. If the exponent of the result is between the - * double's minimum exponent and maximum exponent, + * {@code double}'s minimum exponent and maximum exponent, * the answer is calculated exactly. If the exponent of the - * result would be larger than doubles's maximum + * result would be larger than {@code doubles}'s maximum * exponent, an infinity is returned. Note that if the result is - * subnormal, precision may be lost; that is, when scalb(x, - * n) is subnormal, scalb(scalb(x, n), -n) may + * subnormal, precision may be lost; that is, when {@code scalb(x, + * n)} is subnormal, {@code scalb(scalb(x, n), -n)} may * not equal x. When the result is non-NaN, the result has - * the same sign as d. + * the same sign as {@code d}. * *

    * Special cases: @@ -562,8 +556,8 @@ public class FpUtils { *

* * @param d number to be scaled by a power of two. - * @param scale_factor power of 2 used to scale d - * @return d * 2scale_factor + * @param scale_factor power of 2 used to scale {@code d} + * @return {@code d * }2{@code scale_factor} * @author Joseph D. Darcy */ public static double scalb(double d, int scale_factor) { @@ -644,22 +638,22 @@ public class FpUtils { } /** - * Return f × - * 2scale_factor rounded as if performed + * Return {@code f} × + * 2{@code scale_factor} rounded as if performed * by a single correctly rounded floating-point multiply to a * member of the float value set. See §4.2.3 * of the Java * Language Specification for a discussion of floating-point * value set. If the exponent of the result is between the - * float's minimum exponent and maximum exponent, the + * {@code float}'s minimum exponent and maximum exponent, the * answer is calculated exactly. If the exponent of the result - * would be larger than float's maximum exponent, an + * would be larger than {@code float}'s maximum exponent, an * infinity is returned. Note that if the result is subnormal, - * precision may be lost; that is, when scalb(x, n) - * is subnormal, scalb(scalb(x, n), -n) may not equal + * precision may be lost; that is, when {@code scalb(x, n)} + * is subnormal, {@code scalb(scalb(x, n), -n)} may not equal * x. When the result is non-NaN, the result has the same - * sign as f. + * sign as {@code f}. * *

* Special cases: @@ -672,8 +666,8 @@ public class FpUtils { * * * @param f number to be scaled by a power of two. - * @param scale_factor power of 2 used to scale f - * @return f * 2scale_factor + * @param scale_factor power of 2 used to scale {@code f} + * @return {@code f * }2{@code scale_factor} * @author Joseph D. Darcy */ public static float scalb(float f, int scale_factor) { @@ -709,34 +703,34 @@ public class FpUtils { *

    *
  • If either argument is a NaN, then NaN is returned. * - *
  • If both arguments are signed zeros, direction + *
  • If both arguments are signed zeros, {@code direction} * is returned unchanged (as implied by the requirement of * returning the second argument if the arguments compare as * equal). * - *
  • If start is - * ±Double.MIN_VALUE and direction + *
  • If {@code start} is + * ±{@code Double.MIN_VALUE} and {@code direction} * has a value such that the result should have a smaller - * magnitude, then a zero with the same sign as start + * magnitude, then a zero with the same sign as {@code start} * is returned. * - *
  • If start is infinite and - * direction has a value such that the result should - * have a smaller magnitude, Double.MAX_VALUE with the - * same sign as start is returned. + *
  • If {@code start} is infinite and + * {@code direction} has a value such that the result should + * have a smaller magnitude, {@code Double.MAX_VALUE} with the + * same sign as {@code start} is returned. * - *
  • If start is equal to ± - * Double.MAX_VALUE and direction has a + *
  • If {@code start} is equal to ± + * {@code Double.MAX_VALUE} and {@code direction} has a * value such that the result should have a larger magnitude, an - * infinity with same sign as start is returned. + * infinity with same sign as {@code start} is returned. *
* * @param start starting floating-point value * @param direction value indicating which of - * start's neighbors or start should + * {@code start}'s neighbors or {@code start} should * be returned - * @return The floating-point number adjacent to start in the - * direction of direction. + * @return The floating-point number adjacent to {@code start} in the + * direction of {@code direction}. * @author Joseph D. Darcy */ public static double nextAfter(double start, double direction) { @@ -809,34 +803,34 @@ public class FpUtils { *
    *
  • If either argument is a NaN, then NaN is returned. * - *
  • If both arguments are signed zeros, a float - * zero with the same sign as direction is returned + *
  • If both arguments are signed zeros, a {@code float} + * zero with the same sign as {@code direction} is returned * (as implied by the requirement of returning the second argument * if the arguments compare as equal). * - *
  • If start is - * ±Float.MIN_VALUE and direction + *
  • If {@code start} is + * ±{@code Float.MIN_VALUE} and {@code direction} * has a value such that the result should have a smaller - * magnitude, then a zero with the same sign as start + * magnitude, then a zero with the same sign as {@code start} * is returned. * - *
  • If start is infinite and - * direction has a value such that the result should - * have a smaller magnitude, Float.MAX_VALUE with the - * same sign as start is returned. + *
  • If {@code start} is infinite and + * {@code direction} has a value such that the result should + * have a smaller magnitude, {@code Float.MAX_VALUE} with the + * same sign as {@code start} is returned. * - *
  • If start is equal to ± - * Float.MAX_VALUE and direction has a + *
  • If {@code start} is equal to ± + * {@code Float.MAX_VALUE} and {@code direction} has a * value such that the result should have a larger magnitude, an - * infinity with same sign as start is returned. + * infinity with same sign as {@code start} is returned. *
* * @param start starting floating-point value * @param direction value indicating which of - * start's neighbors or start should + * {@code start}'s neighbors or {@code start} should * be returned - * @return The floating-point number adjacent to start in the - * direction of direction. + * @return The floating-point number adjacent to {@code start} in the + * direction of {@code direction}. * @author Joseph D. Darcy */ public static float nextAfter(float start, double direction) { @@ -900,12 +894,12 @@ public class FpUtils { } /** - * Returns the floating-point value adjacent to d in + * Returns the floating-point value adjacent to {@code d} in * the direction of positive infinity. This method is - * semantically equivalent to nextAfter(d, - * Double.POSITIVE_INFINITY); however, a nextUp + * semantically equivalent to {@code nextAfter(d, + * Double.POSITIVE_INFINITY)}; however, a {@code nextUp} * implementation may run faster than its equivalent - * nextAfter call. + * {@code nextAfter} call. * *

Special Cases: *

    @@ -915,7 +909,7 @@ public class FpUtils { * positive infinity. * *
  • If the argument is zero, the result is - * Double.MIN_VALUE + * {@code Double.MIN_VALUE} * *
* @@ -935,12 +929,12 @@ public class FpUtils { } /** - * Returns the floating-point value adjacent to f in + * Returns the floating-point value adjacent to {@code f} in * the direction of positive infinity. This method is - * semantically equivalent to nextAfter(f, - * Double.POSITIVE_INFINITY); however, a nextUp + * semantically equivalent to {@code nextAfter(f, + * Double.POSITIVE_INFINITY)}; however, a {@code nextUp} * implementation may run faster than its equivalent - * nextAfter call. + * {@code nextAfter} call. * *

Special Cases: *

    @@ -950,7 +944,7 @@ public class FpUtils { * positive infinity. * *
  • If the argument is zero, the result is - * Float.MIN_VALUE + * {@code Float.MIN_VALUE} * *
* @@ -970,12 +964,12 @@ public class FpUtils { } /** - * Returns the floating-point value adjacent to d in + * Returns the floating-point value adjacent to {@code d} in * the direction of negative infinity. This method is - * semantically equivalent to nextAfter(d, - * Double.NEGATIVE_INFINITY); however, a - * nextDown implementation may run faster than its - * equivalent nextAfter call. + * semantically equivalent to {@code nextAfter(d, + * Double.NEGATIVE_INFINITY)}; however, a + * {@code nextDown} implementation may run faster than its + * equivalent {@code nextAfter} call. * *

Special Cases: *

    @@ -985,7 +979,7 @@ public class FpUtils { * negative infinity. * *
  • If the argument is zero, the result is - * -Double.MIN_VALUE + * {@code -Double.MIN_VALUE} * *
* @@ -1007,12 +1001,12 @@ public class FpUtils { } /** - * Returns the floating-point value adjacent to f in + * Returns the floating-point value adjacent to {@code f} in * the direction of negative infinity. This method is - * semantically equivalent to nextAfter(f, - * Float.NEGATIVE_INFINITY); however, a - * nextDown implementation may run faster than its - * equivalent nextAfter call. + * semantically equivalent to {@code nextAfter(f, + * Float.NEGATIVE_INFINITY)}; however, a + * {@code nextDown} implementation may run faster than its + * equivalent {@code nextAfter} call. * *

Special Cases: *

    @@ -1022,7 +1016,7 @@ public class FpUtils { * negative infinity. * *
  • If the argument is zero, the result is - * -Float.MIN_VALUE + * {@code -Float.MIN_VALUE} * *
* @@ -1046,13 +1040,13 @@ public class FpUtils { /** * Returns the first floating-point argument with the sign of the * second floating-point argument. For this method, a NaN - * sign argument is always treated as if it were + * {@code sign} argument is always treated as if it were * positive. * * @param magnitude the parameter providing the magnitude of the result * @param sign the parameter providing the sign of the result - * @return a value with the magnitude of magnitude - * and the sign of sign. + * @return a value with the magnitude of {@code magnitude} + * and the sign of {@code sign}. * @author Joseph D. Darcy * @since 1.5 */ @@ -1063,13 +1057,13 @@ public class FpUtils { /** * Returns the first floating-point argument with the sign of the * second floating-point argument. For this method, a NaN - * sign argument is always treated as if it were + * {@code sign} argument is always treated as if it were * positive. * * @param magnitude the parameter providing the magnitude of the result * @param sign the parameter providing the sign of the result - * @return a value with the magnitude of magnitude - * and the sign of sign. + * @return a value with the magnitude of {@code magnitude} + * and the sign of {@code sign}. * @author Joseph D. Darcy */ public static float copySign(float magnitude, float sign) { @@ -1078,8 +1072,8 @@ public class FpUtils { /** * Returns the size of an ulp of the argument. An ulp of a - * double value is the positive distance between this - * floating-point value and the double value next + * {@code double} value is the positive distance between this + * floating-point value and the {@code double} value next * larger in magnitude. Note that for non-NaN x, * ulp(-x) == ulp(x). * @@ -1089,8 +1083,8 @@ public class FpUtils { *
  • If the argument is positive or negative infinity, then the * result is positive infinity. *
  • If the argument is positive or negative zero, then the result is - * Double.MIN_VALUE. - *
  • If the argument is ±Double.MAX_VALUE, then + * {@code Double.MIN_VALUE}. + *
  • If the argument is ±{@code Double.MAX_VALUE}, then * the result is equal to 2971. * * @@ -1105,11 +1099,9 @@ public class FpUtils { switch(exp) { case DoubleConsts.MAX_EXPONENT+1: // NaN or infinity return Math.abs(d); - // break; case DoubleConsts.MIN_EXPONENT-1: // zero or subnormal return Double.MIN_VALUE; - // break default: assert exp <= DoubleConsts.MAX_EXPONENT && exp >= DoubleConsts.MIN_EXPONENT; @@ -1126,14 +1118,13 @@ public class FpUtils { return Double.longBitsToDouble(1L << (exp - (DoubleConsts.MIN_EXPONENT - (DoubleConsts.SIGNIFICAND_WIDTH-1)) )); } - // break } } /** * Returns the size of an ulp of the argument. An ulp of a - * float value is the positive distance between this - * floating-point value and the float value next + * {@code float} value is the positive distance between this + * floating-point value and the {@code float} value next * larger in magnitude. Note that for non-NaN x, * ulp(-x) == ulp(x). * @@ -1143,8 +1134,8 @@ public class FpUtils { *
  • If the argument is positive or negative infinity, then the * result is positive infinity. *
  • If the argument is positive or negative zero, then the result is - * Float.MIN_VALUE. - *
  • If the argument is ±Float.MAX_VALUE, then + * {@code Float.MIN_VALUE}. + *
  • If the argument is ±{@code Float.MAX_VALUE}, then * the result is equal to 2104. * * @@ -1159,11 +1150,9 @@ public class FpUtils { switch(exp) { case FloatConsts.MAX_EXPONENT+1: // NaN or infinity return Math.abs(f); - // break; case FloatConsts.MIN_EXPONENT-1: // zero or subnormal return FloatConsts.MIN_VALUE; - // break default: assert exp <= FloatConsts.MAX_EXPONENT && exp >= FloatConsts.MIN_EXPONENT; @@ -1180,7 +1169,6 @@ public class FpUtils { return Float.intBitsToFloat(1 << (exp - (FloatConsts.MIN_EXPONENT - (FloatConsts.SIGNIFICAND_WIDTH-1)) )); } - // break } } diff --git a/src/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java b/src/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java index 2e06969253cab1fa7642133d6b7bd510a3d72aa6..047bb61e865b482f298c54609cd378357c15e944 100644 --- a/src/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java +++ b/src/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java @@ -235,8 +235,6 @@ abstract class AsynchronousSocketChannelImpl if (remoteAddress == null) throw new NotYetConnectedException(); - if (timeout < 0L) - throw new IllegalArgumentException("Negative timeout"); boolean hasSpaceToRead = isScatteringRead || dst.hasRemaining(); boolean shutdown = false; @@ -342,8 +340,6 @@ abstract class AsynchronousSocketChannelImpl if (isOpen()) { if (remoteAddress == null) throw new NotYetConnectedException(); - if (timeout < 0L) - throw new IllegalArgumentException("Negative timeout"); // check and update state synchronized (writeLock) { if (writeKilled) diff --git a/src/share/classes/sun/nio/ch/FileChannelImpl.java b/src/share/classes/sun/nio/ch/FileChannelImpl.java index e37fe799d84b3c8f5dc0d610becc0f1ea6503be0..32d0be649d3fb8616e27239c017bdc9b5488affa 100644 --- a/src/share/classes/sun/nio/ch/FileChannelImpl.java +++ b/src/share/classes/sun/nio/ch/FileChannelImpl.java @@ -39,13 +39,12 @@ import sun.security.action.GetPropertyAction; public class FileChannelImpl extends FileChannel { - - // Used to make native read and write calls - private static final FileDispatcher nd; - // Memory allocation size for mapping buffers private static final long allocationGranularity; + // Used to make native read and write calls + private final FileDispatcher nd; + // File descriptor private final FileDescriptor fd; @@ -63,22 +62,29 @@ public class FileChannelImpl private final Object positionLock = new Object(); private FileChannelImpl(FileDescriptor fd, boolean readable, - boolean writable, Object parent) + boolean writable, boolean append, Object parent) { this.fd = fd; this.readable = readable; this.writable = writable; this.parent = parent; + this.nd = new FileDispatcherImpl(append); } - // Invoked by getChannel() methods - // of java.io.File{Input,Output}Stream and RandomAccessFile - // + // Used by FileInputStream.getChannel() and RandomAccessFile.getChannel() public static FileChannel open(FileDescriptor fd, boolean readable, boolean writable, Object parent) { - return new FileChannelImpl(fd, readable, writable, parent); + return new FileChannelImpl(fd, readable, writable, false, parent); + } + + // Used by FileOutputStream.getChannel + public static FileChannel open(FileDescriptor fd, + boolean readable, boolean writable, + boolean append, Object parent) + { + return new FileChannelImpl(fd, readable, writable, append, parent); } private void ensureOpen() throws IOException { @@ -704,6 +710,9 @@ public class FileChannelImpl private static class Unmapper implements Runnable { + // may be required to close file + private static final NativeDispatcher nd = new FileDispatcherImpl(); + // keep track of mapped buffer usage static volatile int count; static volatile long totalSize; @@ -1119,7 +1128,6 @@ public class FileChannelImpl static { Util.load(); allocationGranularity = initIDs(); - nd = new FileDispatcherImpl(); } } diff --git a/src/share/classes/sun/security/rsa/RSASignature.java b/src/share/classes/sun/security/rsa/RSASignature.java index 74a42c0a3f5bfb6497dc151816285cf9e527f4fc..c510413a2151733b3a4cd1104be3360147b5ffad 100644 --- a/src/share/classes/sun/security/rsa/RSASignature.java +++ b/src/share/classes/sun/security/rsa/RSASignature.java @@ -185,6 +185,11 @@ public abstract class RSASignature extends SignatureSpi { // verify the data and return the result. See JCA doc protected boolean engineVerify(byte[] sigBytes) throws SignatureException { + if (sigBytes.length != RSACore.getByteLength(publicKey)) { + throw new SignatureException("Signature length not correct: got " + + sigBytes.length + " but was expecting " + + RSACore.getByteLength(publicKey)); + } byte[] digest = getDigestValue(); try { byte[] decrypted = RSACore.rsa(sigBytes, publicKey); diff --git a/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java b/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java index b9528df5146a86df15e14c4a3ec509d9f0c9848f..1c0d6921091962a28f1194aa53f0d8402c06d4d3 100644 --- a/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java +++ b/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java @@ -103,7 +103,8 @@ final class RSAClientKeyExchange extends HandshakeMessage { String s = ((protocolVersion.v >= ProtocolVersion.TLS12.v) ? "SunTls12RsaPremasterSecret" : "SunTlsRsaPremasterSecret"); KeyGenerator kg = JsseJce.getKeyGenerator(s); - kg.init(new TlsRsaPremasterSecretParameterSpec(major, minor)); + kg.init(new TlsRsaPremasterSecretParameterSpec(major, minor), + generator); preMaster = kg.generateKey(); Cipher cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1); diff --git a/src/share/classes/sun/security/tools/JarSigner.java b/src/share/classes/sun/security/tools/JarSigner.java index 89b9c7e75d739af18b5393a5b892cc239032acd2..03809d37812182380d614733938569d2c8a36b52 100644 --- a/src/share/classes/sun/security/tools/JarSigner.java +++ b/src/share/classes/sun/security/tools/JarSigner.java @@ -658,7 +658,9 @@ public class JarSigner { boolean inScope = (inStoreOrScope & IN_SCOPE) != 0; notSignedByAlias |= (inStoreOrScope & NOT_ALIAS) != 0; - aliasNotInStore |= isSigned && (!inStore && !inScope); + if (keystore != null) { + aliasNotInStore |= isSigned && (!inStore && !inScope); + } // Only used when -verbose provided StringBuffer sb = null; @@ -723,7 +725,7 @@ public class JarSigner { if (signatureRelated(name)) { // Entries inside META-INF and other unsigned // entries are grouped separately. - label = "-" + label.substring(1); + label = "-" + label; } // The label finally contains 2 parts separated by '|': @@ -752,7 +754,7 @@ public class JarSigner { List files = s.getValue(); String key = s.getKey(); if (key.charAt(0) == '-') { // the signature-related group - key = ' ' + key.substring(1); + key = key.substring(1); } int pipe = key.indexOf('|'); if (verbose.equals("all")) { @@ -889,7 +891,7 @@ public class JarSigner { * Note: no newline character at the end */ String printCert(String tab, Certificate c, boolean checkValidityPeriod, - long now) { + long now, boolean checkUsage) { StringBuilder certStr = new StringBuilder(); String space = rb.getString("SPACE"); @@ -959,24 +961,26 @@ public class JarSigner { } certStr.append("]"); - boolean[] bad = new boolean[3]; - checkCertUsage(x509Cert, bad); - if (bad[0] || bad[1] || bad[2]) { - String x = ""; - if (bad[0]) { - x ="KeyUsage"; - } - if (bad[1]) { - if (x.length() > 0) x = x + ", "; - x = x + "ExtendedKeyUsage"; - } - if (bad[2]) { - if (x.length() > 0) x = x + ", "; - x = x + "NetscapeCertType"; - } - certStr.append("\n").append(tab) + if (checkUsage) { + boolean[] bad = new boolean[3]; + checkCertUsage(x509Cert, bad); + if (bad[0] || bad[1] || bad[2]) { + String x = ""; + if (bad[0]) { + x ="KeyUsage"; + } + if (bad[1]) { + if (x.length() > 0) x = x + ", "; + x = x + "ExtendedKeyUsage"; + } + if (bad[2]) { + if (x.length() > 0) x = x + ", "; + x = x + "NetscapeCertType"; + } + certStr.append("\n").append(tab) .append(MessageFormat.format(rb.getString( ".{0}.extension.does.not.support.code.signing."), x)); + } } } return certStr.toString(); @@ -1335,7 +1339,7 @@ public class JarSigner { certUrl); } System.out.println(rb.getString("TSA.certificate.") + - printCert("", tsaCert, false, 0)); + printCert("", tsaCert, false, 0, false)); } if (signingMechanism != null) { System.out.println( @@ -1544,10 +1548,13 @@ public class JarSigner { s.append(printTimestamp(tab, timestamp)); s.append('\n'); } - // display the certificate(s) + // display the certificate(s). The first one is end-enity cert and + // its KeyUsage should be checked. + boolean first = true; for (Certificate c : certs) { - s.append(printCert(tab, c, true, now)); + s.append(printCert(tab, c, true, now, first)); s.append('\n'); + first = false; } try { CertPath cp = certificateFactory.generateCertPath(certs); @@ -1847,7 +1854,7 @@ public class JarSigner { // We don't meant to print anything, the next call // checks validity and keyUsage etc - printCert("", certChain[0], true, 0); + printCert("", certChain[0], true, 0, true); try { CertPath cp = certificateFactory.generateCertPath(Arrays.asList(certChain)); diff --git a/src/share/classes/sun/security/tools/policytool/PolicyTool.java b/src/share/classes/sun/security/tools/policytool/PolicyTool.java index e04316317a880e7daa6d9302b7659678d22dc613..f310504a2047b1dbc2ad6a80fe32bf9cd182197b 100644 --- a/src/share/classes/sun/security/tools/policytool/PolicyTool.java +++ b/src/share/classes/sun/security/tools/policytool/PolicyTool.java @@ -49,7 +49,7 @@ import javax.security.auth.x500.X500Principal; /** * PolicyTool may be used by users and administrators to configure the * overall java security policy (currently stored in the policy file). - * Using PolicyTool administators may add and remove policies from + * Using PolicyTool administrators may add and remove policies from * the policy file.

    * * @see java.security.Policy @@ -1343,11 +1343,6 @@ class ToolDialog extends Dialog { PolicyTool.rb.getString ("Actions."); - /* gridbag index for display OverWriteFile (OW) components */ - public static final int OW_LABEL = 0; - public static final int OW_OK_BUTTON = 1; - public static final int OW_CANCEL_BUTTON = 2; - /* gridbag index for display PolicyEntry (PE) components */ public static final int PE_CODEBASE_LABEL = 0; public static final int PE_CODEBASE_TEXTFIELD = 1; @@ -1522,44 +1517,6 @@ class ToolDialog extends Dialog { return null; } - /** - * ask user if they want to overwrite an existing file - */ - void displayOverWriteFileDialog(String filename, int nextEvent) { - - // find where the PolicyTool gui is - Point location = tw.getLocationOnScreen(); - setBounds(location.x + 75, location.y + 100, 400, 150); - setLayout(new GridBagLayout()); - - // ask the user if they want to over write the existing file - MessageFormat form = new MessageFormat(PolicyTool.rb.getString - ("OK.to.overwrite.existing.file.filename.")); - Object[] source = {filename}; - Label label = new Label(form.format(source)); - tw.addNewComponent(this, label, OW_LABEL, - 0, 0, 2, 1, 0.0, 0.0, GridBagConstraints.BOTH, - tw.TOP_PADDING); - - // OK button - Button button = new Button(PolicyTool.rb.getString("OK")); - button.addActionListener(new OverWriteFileOKButtonListener - (tool, tw, this, filename, nextEvent)); - tw.addNewComponent(this, button, OW_OK_BUTTON, - 0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL, - tw.TOP_PADDING); - - // Cancel button - // -- if the user hits cancel, do NOT go on to the next event - button = new Button(PolicyTool.rb.getString("Cancel")); - button.addActionListener(new CancelButtonListener(this)); - tw.addNewComponent(this, button, OW_CANCEL_BUTTON, - 1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL, - tw.TOP_PADDING); - - setVisible(true); - } - /** * pop up a dialog so the user can enter info to add a new PolicyEntry * - if edit is TRUE, then the user is editing an existing entry @@ -2339,47 +2296,39 @@ class ToolDialog extends Dialog { return; // get the entered filename - String filename = new String(fd.getDirectory() + fd.getFile()); + File saveAsFile = new File(fd.getDirectory(), fd.getFile()); + String filename = saveAsFile.getPath(); fd.dispose(); - // see if the file already exists - File saveAsFile = new File(filename); - if (saveAsFile.exists()) { - // display a dialog box for the user to enter policy info - ToolDialog td = new ToolDialog - (PolicyTool.rb.getString("Overwrite.File"), tool, tw, true); - td.displayOverWriteFileDialog(filename, nextEvent); - } else { - try { - // save the policy entries to a file - tool.savePolicy(filename); + try { + // save the policy entries to a file + tool.savePolicy(filename); - // display status - MessageFormat form = new MessageFormat(PolicyTool.rb.getString - ("Policy.successfully.written.to.filename")); - Object[] source = {filename}; - tw.displayStatusDialog(null, form.format(source)); + // display status + MessageFormat form = new MessageFormat(PolicyTool.rb.getString + ("Policy.successfully.written.to.filename")); + Object[] source = {filename}; + tw.displayStatusDialog(null, form.format(source)); - // display the new policy filename - TextField newFilename = (TextField)tw.getComponent - (tw.MW_FILENAME_TEXTFIELD); - newFilename.setText(filename); - tw.setVisible(true); + // display the new policy filename + TextField newFilename = (TextField)tw.getComponent + (tw.MW_FILENAME_TEXTFIELD); + newFilename.setText(filename); + tw.setVisible(true); - // now continue with the originally requested command - // (QUIT, NEW, or OPEN) - userSaveContinue(tool, tw, this, nextEvent); + // now continue with the originally requested command + // (QUIT, NEW, or OPEN) + userSaveContinue(tool, tw, this, nextEvent); - } catch (FileNotFoundException fnfe) { - if (filename == null || filename.equals("")) { - tw.displayErrorDialog(null, new FileNotFoundException - (PolicyTool.rb.getString("null.filename"))); - } else { - tw.displayErrorDialog(null, fnfe); - } - } catch (Exception ee) { - tw.displayErrorDialog(null, ee); + } catch (FileNotFoundException fnfe) { + if (filename == null || filename.equals("")) { + tw.displayErrorDialog(null, new FileNotFoundException + (PolicyTool.rb.getString("null.filename"))); + } else { + tw.displayErrorDialog(null, fnfe); } + } catch (Exception ee) { + tw.displayErrorDialog(null, ee); } } @@ -2494,7 +2443,7 @@ class ToolDialog extends Dialog { return; // get the entered filename - String policyFile = new String(fd.getDirectory() + fd.getFile()); + String policyFile = new File(fd.getDirectory(), fd.getFile()).getPath(); try { // open the policy file @@ -2861,67 +2810,6 @@ class MainWindowListener implements ActionListener { } } -/** - * Event handler for OverWriteFileOKButton button - */ -class OverWriteFileOKButtonListener implements ActionListener { - - private PolicyTool tool; - private ToolWindow tw; - private ToolDialog td; - private String filename; - private int nextEvent; - - OverWriteFileOKButtonListener(PolicyTool tool, ToolWindow tw, - ToolDialog td, String filename, int nextEvent) { - this.tool = tool; - this.tw = tw; - this.td = td; - this.filename = filename; - this.nextEvent = nextEvent; - } - - public void actionPerformed(ActionEvent e) { - try { - // save the policy entries to a file - tool.savePolicy(filename); - - // display status - MessageFormat form = new MessageFormat - (PolicyTool.rb.getString - ("Policy.successfully.written.to.filename")); - Object[] source = {filename}; - tw.displayStatusDialog(null, form.format(source)); - - // display the new policy filename - TextField newFilename = (TextField)tw.getComponent - (tw.MW_FILENAME_TEXTFIELD); - newFilename.setText(filename); - tw.setVisible(true); - - // now continue with the originally requested command - // (QUIT, NEW, or OPEN) - td.setVisible(false); - td.dispose(); - td.userSaveContinue(tool, tw, td, nextEvent); - - } catch (FileNotFoundException fnfe) { - if (filename == null || filename.equals("")) { - tw.displayErrorDialog(null, new FileNotFoundException - (PolicyTool.rb.getString("null.filename"))); - } else { - tw.displayErrorDialog(null, fnfe); - } - td.setVisible(false); - td.dispose(); - } catch (Exception ee) { - tw.displayErrorDialog(null, ee); - td.setVisible(false); - td.dispose(); - } - } -} - /** * Event handler for AddEntryDoneButton button * diff --git a/src/share/classes/sun/security/util/ManifestEntryVerifier.java b/src/share/classes/sun/security/util/ManifestEntryVerifier.java index 3952ccee86dbc85b3d145b787e8948e6cad9c38d..2fe98e500357c12b313c57deba8df4b6b786a320 100644 --- a/src/share/classes/sun/security/util/ManifestEntryVerifier.java +++ b/src/share/classes/sun/security/util/ManifestEntryVerifier.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -185,7 +185,10 @@ public class ManifestEntryVerifier { Hashtable sigFileSigners) throws JarException { - if (skip) return null; + // MANIFEST.MF should not be skipped. It has signers. + if (skip && !entry.getName().equals(JarFile.MANIFEST_NAME)) { + return null; + } if (signers != null) return signers; diff --git a/src/share/classes/sun/security/util/SignatureFileVerifier.java b/src/share/classes/sun/security/util/SignatureFileVerifier.java index b0a334ee49804f2bb0473b21ab5b3b585aa4d27e..d3ce9013e1570a1bdf90a597e605f9fcf6526fdc 100644 --- a/src/share/classes/sun/security/util/SignatureFileVerifier.java +++ b/src/share/classes/sun/security/util/SignatureFileVerifier.java @@ -265,6 +265,9 @@ public class SignatureFileVerifier { debug.println("processSignature unsigned name = "+name); } } + + // MANIFEST.MF is always regarded as signed + updateSigners(newSigners, signers, JarFile.MANIFEST_NAME); } /** diff --git a/src/share/demo/nio/zipfs/Demo.java b/src/share/demo/nio/zipfs/Demo.java index 99669d1fdf224dd6518f9a8553b51e376a75d1a0..fd2ba7311b10082c5bbda04d1e49ef1db9600549 100644 --- a/src/share/demo/nio/zipfs/Demo.java +++ b/src/share/demo/nio/zipfs/Demo.java @@ -45,12 +45,7 @@ import static java.nio.file.StandardCopyOption.*; /* * ZipFileSystem usage demo * - * java [-cp .../zipfs.jar:./] Demo action ZipfileName [...] - * - * To deploy the provider, either copy the zipfs.jar into JDK/JRE - * extensions directory or add - * /demo/nio/ZipFileSystem/zipfs.jar - * into your class path as showed above. + * java Demo action ZipfileName [...] * * @author Xueming Shen */ @@ -153,14 +148,11 @@ public class Demo { Action action = Action.valueOf(args[0]); Map env = env = new HashMap<>(); if (action == Action.create) - env.put("createNew", true); + env.put("create", "true"); if (action == Action.tlist || action == Action.twalk) env.put("buildDirTree", true); + FileSystem fs = FileSystems.newFileSystem(Paths.get(args[1]), env, null); - FileSystem fs = FileSystems.newFileSystem( - URI.create("zip" + Paths.get(args[1]).toUri().toString().substring(4)), - env, - null); try { FileSystem fs2; Path path, src, dst; @@ -207,19 +199,13 @@ public class Demo { src.copyTo(dst, COPY_ATTRIBUTES); break; case zzmove: - fs2 = FileSystems.newFileSystem( - URI.create("zip" + Paths.get(args[2]).toUri().toString().substring(4)), - env, - null); + fs2 = FileSystems.newFileSystem(Paths.get(args[2]), env, null); //sf1.getPath(args[3]).moveTo(fs2.getPath(args[3])); z2zmove(fs, fs2, args[3]); fs2.close(); break; case zzcopy: - fs2 = FileSystems.newFileSystem( - URI.create("zip" + Paths.get(args[2]).toUri().toString().substring(4)), - env, - null); + fs2 = FileSystems.newFileSystem(Paths.get(args[2]), env, null); //sf1.getPath(args[3]).copyTo(fs2.getPath(args[3])); z2zcopy(fs, fs2, args[3]); fs2.close(); diff --git a/src/share/demo/nio/zipfs/README.txt b/src/share/demo/nio/zipfs/README.txt index d5517bf7baeb481e4c601863944fee63c733421e..9a216e48d704aa4f8dbcab7812df5ebb8d4018cd 100644 --- a/src/share/demo/nio/zipfs/README.txt +++ b/src/share/demo/nio/zipfs/README.txt @@ -1,10 +1,6 @@ ZipFileSystem is a file system provider that treats the contents of a zip or JAR file as a java.nio.file.FileSystem. -To deploy the provider you must copy zipfs.jar into your extensions -directory or else add /demo/nio/zipfs/zipfs.jar -to your class path. - The factory methods defined by the java.nio.file.FileSystems class can be used to create a FileSystem, eg: @@ -15,9 +11,9 @@ used to create a FileSystem, eg: -or - // locate file system by URI + // locate file system by the legacy JAR URL syntax Map env = Collections.emptyMap(); - URI uri = URI.create("zip:///mydir/foo.jar"); + URI uri = URI.create("jar:file:/mydir/foo.jar"); FileSystem fs = FileSystems.newFileSystem(uri, env); Once a FileSystem is created then classes in the java.nio.file package @@ -26,4 +22,6 @@ can be used to access files in the zip/JAR file, eg: Path mf = fs.getPath("/META-INF/MANIFEST.MF"); InputStream in = mf.newInputStream(); +See Demo.java for more interesting usages. + diff --git a/src/share/demo/nio/zipfs/META-INF/services/java.nio.file.spi.FileSystemProvider b/src/share/demo/nio/zipfs/src/META-INF/services/java.nio.file.spi.FileSystemProvider similarity index 50% rename from src/share/demo/nio/zipfs/META-INF/services/java.nio.file.spi.FileSystemProvider rename to src/share/demo/nio/zipfs/src/META-INF/services/java.nio.file.spi.FileSystemProvider index ace131aa0fd72ee57c88e85000f1f54840b5c138..58ee3a6b9727d7215c65474d48a1eb7239da1ebf 100644 --- a/src/share/demo/nio/zipfs/META-INF/services/java.nio.file.spi.FileSystemProvider +++ b/src/share/demo/nio/zipfs/src/META-INF/services/java.nio.file.spi.FileSystemProvider @@ -1,3 +1,2 @@ com.sun.nio.zipfs.ZipFileSystemProvider -com.sun.nio.zipfs.JarFileSystemProvider diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/JarFileSystemProvider.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/JarFileSystemProvider.java similarity index 100% rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/JarFileSystemProvider.java rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/JarFileSystemProvider.java diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipCoder.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipCoder.java similarity index 100% rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipCoder.java rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipCoder.java diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipConstants.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipConstants.java similarity index 100% rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipConstants.java rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipConstants.java diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipDirectoryStream.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipDirectoryStream.java similarity index 100% rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipDirectoryStream.java rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipDirectoryStream.java diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributeView.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileAttributeView.java similarity index 100% rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributeView.java rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileAttributeView.java diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributes.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileAttributes.java similarity index 100% rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileAttributes.java rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileAttributes.java diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileStore.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileStore.java similarity index 100% rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileStore.java rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileStore.java diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystem.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java similarity index 99% rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystem.java rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java index eddc5ac938229cfb040d3de799f6e9e6fdf934fa..21094011c01be0c31af45821ee912b9a0a425610 100644 --- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystem.java +++ b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java @@ -91,11 +91,11 @@ public class ZipFileSystem extends FileSystem { throws IOException { // configurable env setup + this.createNew = "true".equals(env.get("create")); + this.nameEncoding = env.containsKey("encoding") ? + (String)env.get("encoding") : "UTF-8"; this.buildDirTree = TRUE.equals(env.get("buildDirTreea")); this.useTempFile = TRUE.equals(env.get("useTempFile")); - this.createNew = TRUE.equals(env.get("createNew")); - this.nameEncoding = env.containsKey("nameEncoding") ? - (String)env.get("nameEncoding") : "UTF-8"; this.defaultDir = env.containsKey("default.dir") ? (String)env.get("default.dir") : "/"; if (this.defaultDir.charAt(0) != '/') @@ -1176,7 +1176,9 @@ public class ZipFileSystem extends FileSystem { } else { os.write(buf, 0, LOCHDR); // write out the loc header locoff += LOCHDR; - size += LOCNAM(buf) + LOCEXT(buf) + LOCSIZ(buf); + // use e.csize, LOCSIZ(buf) is zero if FLAG_DATADESCR is on + // size += LOCNAM(buf) + LOCEXT(buf) + LOCSIZ(buf); + size += LOCNAM(buf) + LOCEXT(buf) + e.csize; written = LOCHDR + size; } int n; diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystemProvider.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystemProvider.java similarity index 88% rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystemProvider.java rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystemProvider.java index 08c3a17648c2f0e3e2e72d8b678b940968be6923..cf39b07cae7540cb0cf95c366d3e6cf10409a0d8 100644 --- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipFileSystemProvider.java +++ b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystemProvider.java @@ -63,7 +63,7 @@ public class ZipFileSystemProvider extends FileSystemProvider { @Override public String getScheme() { - return "zip"; + return "jar"; } protected Path uriToPath(URI uri) { @@ -72,10 +72,14 @@ public class ZipFileSystemProvider extends FileSystemProvider { throw new IllegalArgumentException("URI scheme is not '" + getScheme() + "'"); } try { - return Paths.get(new URI("file", uri.getHost(), uri.getPath(), null)) - .toAbsolutePath(); + // only support legacy JAR URL syntax jar:{uri}!/{entry} for now + String spec = uri.getSchemeSpecificPart(); + int sep = spec.indexOf("!/"); + if (sep != -1) + spec = spec.substring(0, sep); + return Paths.get(new URI(spec)).toAbsolutePath(); } catch (URISyntaxException e) { - throw new AssertionError(e); //never thrown + throw new IllegalArgumentException(e.getMessage(), e); } } @@ -119,14 +123,14 @@ public class ZipFileSystemProvider extends FileSystemProvider { @Override public Path getPath(URI uri) { - FileSystem fs = getFileSystem(uri); - String fragment = uri.getFragment(); - if (fragment == null) { + + String spec = uri.getSchemeSpecificPart(); + int sep = spec.indexOf("!/"); + if (sep == -1) throw new IllegalArgumentException("URI: " + uri - + " does not contain path fragment ex. zip:///c:/foo.zip#/BAR"); - } - return fs.getPath(fragment); + + " does not contain path info ex. jar:file:/c:/foo.zip!/BAR"); + return getFileSystem(uri).getPath(spec.substring(sep + 1)); } @Override diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipInfo.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipInfo.java similarity index 98% rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipInfo.java rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipInfo.java index dd18cc9f4440044337b006ae815da5a29d9e709e..56954e1d9eab231dbdd1416837650b90ccfffcbc 100644 --- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipInfo.java +++ b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipInfo.java @@ -33,9 +33,7 @@ package com.sun.nio.zipfs; import java.nio.file.Paths; import java.util.Collections; -import java.util.Iterator; import java.util.Map; -import com.sun.nio.zipfs.ZipFileSystem.Entry; import static com.sun.nio.zipfs.ZipConstants.*; import static com.sun.nio.zipfs.ZipUtils.*; @@ -172,7 +170,7 @@ public class ZipInfo { static void printExtra(byte[] extra, int off, int len) { int end = off + len; - while (off + 4 < end) { + while (off + 4 <= end) { int tag = SH(extra, off); int sz = SH(extra, off + 2); print(" [tag=0x%04x, sz=%d, data= ", tag, sz); diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipPath.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java similarity index 98% rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipPath.java rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java index 5fba2fafa9aef2c022b056e3418bd66153328b4c..a2c766f0da2f92666f533461c4332c984f2be13d 100644 --- a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipPath.java +++ b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java @@ -191,13 +191,12 @@ public class ZipPath extends Path { @Override public URI toUri() { - String zfPath = zfs.toString(); - if (File.separatorChar == '\\') // replace all separators by '/' - zfPath = "/" + zfPath.replace("\\", "/"); try { - return new URI("zip", "", - zfPath, - zfs.getString(toAbsolutePath().path)); + return new URI("jar", + zfs.getZipFile().toUri() + + "!" + + zfs.getString(toAbsolutePath().path), + null); } catch (Exception ex) { throw new AssertionError(ex); } diff --git a/src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipUtils.java b/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipUtils.java similarity index 100% rename from src/share/demo/nio/zipfs/com/sun/nio/zipfs/ZipUtils.java rename to src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipUtils.java diff --git a/src/share/demo/zipfs b/src/share/demo/zipfs new file mode 100644 index 0000000000000000000000000000000000000000..fd2ba7311b10082c5bbda04d1e49ef1db9600549 --- /dev/null +++ b/src/share/demo/zipfs @@ -0,0 +1,703 @@ +/* + * Copyright (c) 2010 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. + */ + +import java.io.*; +import java.nio.*; +import java.nio.channels.*; +import java.nio.file.*; +import java.nio.file.attribute.*; +import java.net.*; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +import static java.nio.file.StandardOpenOption.*; +import static java.nio.file.StandardCopyOption.*; + +/* + * ZipFileSystem usage demo + * + * java Demo action ZipfileName [...] + * + * @author Xueming Shen + */ + +public class Demo { + + static enum Action { + rename, // + // rename entry src to dst inside zipfile + + movein, // + // move an external src file into zipfile + // as entry dst + + moveout, // + // move a zipfile entry src out to dst + + copy, // + // copy entry src to dst inside zipfile + + copyin, // + // copy an external src file into zipfile + // as entry dst + + copyin_attrs, // + // copy an external src file into zipfile + // as entry dst, with attributes (timestamp) + + copyout, // + // copy zipfile entry src" out to file dst + + copyout_attrs, // + + zzmove, // + // move entry path/dir from zfsrc to zfdst + + zzcopy, // + // copy path from zipfile zfsrc to zipfile + // zfdst + + attrs, // + // printout the attributes of entry path + + attrsspace, // + // printout the storespace attrs of entry path + + setmtime, // + // set the lastModifiedTime of entry path + + setatime, // + setctime, // + + lsdir, // + // list dir's direct child files/dirs + + mkdir, // + + mkdirs, // + + rmdirs, // + + list, // + // recursively list all entries of dir + // via DirectoryStream + + tlist, // + // list with buildDirTree=true + + vlist, // + // recursively verbose list all entries of + // dir via DirectoryStream + + walk, // + // recursively walk all entries of dir + // via Files.walkFileTree + + twalk, // + // walk with buildDirTree=true + + extract, // + + update, // + + delete, // + + add, // + + create, // + // create a new zipfile if it doesn't exit + // and then add the file(s) into it. + + attrs2, // + // test different ways to print attrs + + prof, + } + + public static void main(String[] args) throws Throwable { + + Action action = Action.valueOf(args[0]); + Map env = env = new HashMap<>(); + if (action == Action.create) + env.put("create", "true"); + if (action == Action.tlist || action == Action.twalk) + env.put("buildDirTree", true); + FileSystem fs = FileSystems.newFileSystem(Paths.get(args[1]), env, null); + + try { + FileSystem fs2; + Path path, src, dst; + boolean isRename = false; + switch (action) { + case rename: + src = fs.getPath(args[2]); + dst = fs.getPath(args[3]); + src.moveTo(dst); + break; + case moveout: + src = fs.getPath(args[2]); + dst = Paths.get(args[3]); + src.moveTo(dst); + break; + case movein: + src = Paths.get(args[2]); + dst = fs.getPath(args[3]); + src.moveTo(dst); + break; + case copy: + src = fs.getPath(args[2]); + dst = fs.getPath(args[3]); + src.copyTo(dst); + break; + case copyout: + src = fs.getPath(args[2]); + dst = Paths.get(args[3]); + src.copyTo(dst); + break; + case copyin: + src = Paths.get(args[2]); + dst = fs.getPath(args[3]); + src.copyTo(dst); + break; + case copyin_attrs: + src = Paths.get(args[2]); + dst = fs.getPath(args[3]); + src.copyTo(dst, COPY_ATTRIBUTES); + break; + case copyout_attrs: + src = fs.getPath(args[2]); + dst = Paths.get(args[3]); + src.copyTo(dst, COPY_ATTRIBUTES); + break; + case zzmove: + fs2 = FileSystems.newFileSystem(Paths.get(args[2]), env, null); + //sf1.getPath(args[3]).moveTo(fs2.getPath(args[3])); + z2zmove(fs, fs2, args[3]); + fs2.close(); + break; + case zzcopy: + fs2 = FileSystems.newFileSystem(Paths.get(args[2]), env, null); + //sf1.getPath(args[3]).copyTo(fs2.getPath(args[3])); + z2zcopy(fs, fs2, args[3]); + fs2.close(); + break; + case attrs: + for (int i = 2; i < args.length; i++) { + path = fs.getPath(args[i]); + System.out.println(path); + System.out.println( + Attributes.readBasicFileAttributes(path).toString()); + } + break; + case setmtime: + DateFormat df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss"); + Date newDatetime = df.parse(args[2]); + for (int i = 3; i < args.length; i++) { + path = fs.getPath(args[i]); + path.setAttribute("lastModifiedTime", + FileTime.fromMillis(newDatetime.getTime())); + System.out.println( + Attributes.readBasicFileAttributes(path).toString()); + } + break; + case setctime: + df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss"); + newDatetime = df.parse(args[2]); + for (int i = 3; i < args.length; i++) { + path = fs.getPath(args[i]); + path.setAttribute("creationTime", + FileTime.fromMillis(newDatetime.getTime())); + System.out.println( + Attributes.readBasicFileAttributes(path).toString()); + } + break; + case setatime: + df = new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss"); + newDatetime = df.parse(args[2]); + for (int i = 3; i < args.length; i++) { + path = fs.getPath(args[i]); + path.setAttribute("lastAccessTime", + FileTime.fromMillis(newDatetime.getTime())); + System.out.println( + Attributes.readBasicFileAttributes(path).toString()); + } + break; + case attrsspace: + path = fs.getPath("/"); + FileStore fstore = path.getFileStore(); + //System.out.println(fstore.getFileStoreAttributeView(FileStoreSpaceAttributeView.class) + // .readAttributes()); + // or + System.out.printf("filestore[%s]%n", fstore.name()); + System.out.printf(" totalSpace: %d%n", + (Long)fstore.getAttribute("space:totalSpace")); + System.out.printf(" usableSpace: %d%n", + (Long)fstore.getAttribute("space:usableSpace")); + System.out.printf(" unallocSpace: %d%n", + (Long)fstore.getAttribute("space:unallocatedSpace")); + break; + case list: + case tlist: + if (args.length < 3) + list(fs.getPath("/"), false); + else + list(fs.getPath(args[2]), false); + break; + case vlist: + if (args.length < 3) + list(fs.getPath("/"), true); + else + list(fs.getPath(args[2]), true); + break; + case twalk: + case walk: + walk(fs.getPath((args.length > 2)? args[2] : "/")); + break; + case extract: + if (args.length == 2) { + extract(fs, "/"); + } else { + for (int i = 2; i < args.length; i++) { + extract(fs, args[i]); + } + } + break; + case delete: + for (int i = 2; i < args.length; i++) + fs.getPath(args[i]).delete(); + break; + case create: + case add: + case update: + for (int i = 2; i < args.length; i++) { + update(fs, args[i]); + } + break; + case lsdir: + path = fs.getPath(args[2]); + final String fStr = (args.length > 3)?args[3]:""; + DirectoryStream ds = path.newDirectoryStream( + new DirectoryStream.Filter() { + public boolean accept(Path path) { + return path.toString().contains(fStr); + } + }); + for (Path p : ds) + System.out.println(p); + break; + case mkdir: + fs.getPath(args[2]).createDirectory(); + break; + case mkdirs: + mkdirs(fs.getPath(args[2])); + break; + case attrs2: + for (int i = 2; i < args.length; i++) { + path = fs.getPath(args[i]); + System.out.printf("%n%s%n", path); + System.out.println("-------(1)---------"); + System.out.println( + Attributes.readBasicFileAttributes(path).toString()); + System.out.println("-------(2)---------"); + Map map = path.readAttributes("zip:*"); + for (Map.Entry e : map.entrySet()) { + System.out.printf(" %s : %s%n", e.getKey(), e.getValue()); + } + System.out.println("-------(3)---------"); + map = path.readAttributes("size,lastModifiedTime,isDirectory"); + for (Map.Entry e : map.entrySet()) { + System.out.printf(" %s : %s%n", e.getKey(), e.getValue()); + } + } + break; + case prof: + list(fs.getPath("/"), false); + while (true) { + Thread.sleep(10000); + //list(fs.getPath("/"), true); + System.out.println("sleeping..."); + } + } + } catch (Exception x) { + x.printStackTrace(); + } finally { + if (fs != null) + fs.close(); + } + } + + private static byte[] getBytes(String name) { + return name.getBytes(); + } + + private static String getString(byte[] name) { + return new String(name); + } + + private static void walk(Path path) throws IOException + { + Files.walkFileTree( + path, + new SimpleFileVisitor() { + private int indent = 0; + private void indent() { + int n = 0; + while (n++ < indent) + System.out.printf(" "); + } + + @Override + public FileVisitResult visitFile(Path file, + BasicFileAttributes attrs) + { + indent(); + System.out.printf("%s%n", file.getName().toString()); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult preVisitDirectory(Path dir, + BasicFileAttributes attrs) + { + indent(); + System.out.printf("[%s]%n", dir.toString()); + indent += 2; + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, + IOException ioe) + { + indent -= 2; + return FileVisitResult.CONTINUE; + } + }); + } + + private static void update(FileSystem fs, String path) throws Throwable{ + Path src = FileSystems.getDefault().getPath(path); + if (Boolean.TRUE.equals(src.getAttribute("isDirectory"))) { + DirectoryStream ds = src.newDirectoryStream(); + for (Path child : ds) + update(fs, child.toString()); + ds.close(); + } else { + Path dst = fs.getPath(path); + Path parent = dst.getParent(); + if (parent != null && parent.notExists()) + mkdirs(parent); + src.copyTo(dst, REPLACE_EXISTING); + } + } + + private static void extract(FileSystem fs, String path) throws Throwable{ + Path src = fs.getPath(path); + if (Boolean.TRUE.equals(src.getAttribute("isDirectory"))) { + DirectoryStream ds = src.newDirectoryStream(); + for (Path child : ds) + extract(fs, child.toString()); + ds.close(); + } else { + if (path.startsWith("/")) + path = path.substring(1); + Path dst = FileSystems.getDefault().getPath(path); + Path parent = dst.getParent(); + if (parent.notExists()) + mkdirs(parent); + src.copyTo(dst, REPLACE_EXISTING); + } + } + + // use DirectoryStream + private static void z2zcopy(FileSystem src, FileSystem dst, String path) + throws IOException + { + Path srcPath = src.getPath(path); + Path dstPath = dst.getPath(path); + + if (Boolean.TRUE.equals(srcPath.getAttribute("isDirectory"))) { + if (!dstPath.exists()) { + try { + mkdirs(dstPath); + } catch (FileAlreadyExistsException x) {} + } + DirectoryStream ds = srcPath.newDirectoryStream(); + for (Path child : ds) { + z2zcopy(src, dst, + path + (path.endsWith("/")?"":"/") + child.getName()); + } + ds.close(); + } else { + //System.out.println("copying..." + path); + srcPath.copyTo(dstPath); + } + } + + // use TreeWalk to move + private static void z2zmove(FileSystem src, FileSystem dst, String path) + throws IOException + { + final Path srcPath = src.getPath(path).toAbsolutePath(); + final Path dstPath = dst.getPath(path).toAbsolutePath(); + + Files.walkFileTree(srcPath, new SimpleFileVisitor() { + + @Override + public FileVisitResult visitFile(Path file, + BasicFileAttributes attrs) + { + Path dst = srcPath.relativize(file); + dst = dstPath.resolve(dst); + try { + Path parent = dstPath.getParent(); + if (parent != null && parent.notExists()) + mkdirs(parent); + file.moveTo(dst); + } catch (IOException x) { + x.printStackTrace(); + } + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult preVisitDirectory(Path dir, + BasicFileAttributes attrs) + { + Path dst = srcPath.relativize(dir); + dst = dstPath.resolve(dst); + try { + + if (dst.notExists()) + mkdirs(dst); + } catch (IOException x) { + x.printStackTrace(); + } + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, + IOException ioe) + throws IOException + { + try { + dir.delete(); + } catch (IOException x) { + //x.printStackTrace(); + } + return FileVisitResult.CONTINUE; + } + }); + + } + + private static void mkdirs(Path path) throws IOException { + path = path.toAbsolutePath(); + Path parent = path.getParent(); + if (parent != null) { + if (parent.notExists()) + mkdirs(parent); + } + path.createDirectory(); + } + + private static void rmdirs(Path path) throws IOException { + while (path != null && path.getNameCount() != 0) { + path.delete(); + path = path.getParent(); + } + } + + private static void list(Path path, boolean verbose ) throws IOException { + if (!"/".equals(path.toString())) { + System.out.printf(" %s%n", path.toString()); + if (verbose) + System.out.println(Attributes.readBasicFileAttributes(path).toString()); + } + if (path.notExists()) + return; + if (Attributes.readBasicFileAttributes(path).isDirectory()) { + DirectoryStream ds = path.newDirectoryStream(); + for (Path child : ds) + list(child, verbose); + ds.close(); + } + } + + // check the content of two paths are equal + private static void checkEqual(Path src, Path dst) throws IOException + { + //System.out.printf("checking <%s> vs <%s>...%n", + // src.toString(), dst.toString()); + + //streams + InputStream isSrc = src.newInputStream(); + InputStream isDst = dst.newInputStream(); + byte[] bufSrc = new byte[8192]; + byte[] bufDst = new byte[8192]; + + try { + int nSrc = 0; + while ((nSrc = isSrc.read(bufSrc)) != -1) { + int nDst = 0; + while (nDst < nSrc) { + int n = isDst.read(bufDst, nDst, nSrc - nDst); + if (n == -1) { + System.out.printf("checking <%s> vs <%s>...%n", + src.toString(), dst.toString()); + throw new RuntimeException("CHECK FAILED!"); + } + nDst += n; + } + while (--nSrc >= 0) { + if (bufSrc[nSrc] != bufDst[nSrc]) { + System.out.printf("checking <%s> vs <%s>...%n", + src.toString(), dst.toString()); + throw new RuntimeException("CHECK FAILED!"); + } + nSrc--; + } + } + } finally { + isSrc.close(); + isDst.close(); + } + + // channels + SeekableByteChannel chSrc = src.newByteChannel(); + SeekableByteChannel chDst = dst.newByteChannel(); + if (chSrc.size() != chDst.size()) { + System.out.printf("src[%s].size=%d, dst[%s].size=%d%n", + chSrc.toString(), chSrc.size(), + chDst.toString(), chDst.size()); + throw new RuntimeException("CHECK FAILED!"); + } + ByteBuffer bbSrc = ByteBuffer.allocate(8192); + ByteBuffer bbDst = ByteBuffer.allocate(8192); + + try { + int nSrc = 0; + while ((nSrc = chSrc.read(bbSrc)) != -1) { + int nDst = chDst.read(bbDst); + if (nSrc != nDst) { + System.out.printf("checking <%s> vs <%s>...%n", + src.toString(), dst.toString()); + throw new RuntimeException("CHECK FAILED!"); + } + while (--nSrc >= 0) { + if (bbSrc.get(nSrc) != bbDst.get(nSrc)) { + System.out.printf("checking <%s> vs <%s>...%n", + src.toString(), dst.toString()); + throw new RuntimeException("CHECK FAILED!"); + } + nSrc--; + } + bbSrc.flip(); + bbDst.flip(); + } + } catch (IOException x) { + x.printStackTrace(); + } finally { + chSrc.close(); + chDst.close(); + } + } + + private static void fchCopy(Path src, Path dst) throws IOException + { + Set read = new HashSet<>(); + read.add(READ); + Set openwrite = new HashSet<>(); + openwrite.add(CREATE_NEW); + openwrite.add(WRITE); + + FileChannel srcFc = src.getFileSystem() + .provider() + .newFileChannel(src, read); + FileChannel dstFc = dst.getFileSystem() + .provider() + .newFileChannel(dst, openwrite); + + try { + ByteBuffer bb = ByteBuffer.allocate(8192); + while (srcFc.read(bb) >= 0) { + bb.flip(); + dstFc.write(bb); + bb.clear(); + } + } finally { + srcFc.close(); + dstFc.close(); + } + } + + private static void chCopy(Path src, Path dst) throws IOException + { + Set read = new HashSet<>(); + read.add(READ); + Set openwrite = new HashSet<>(); + openwrite.add(CREATE_NEW); + openwrite.add(WRITE); + + SeekableByteChannel srcCh = src.newByteChannel(read); + SeekableByteChannel dstCh = dst.newByteChannel(openwrite); + + try { + ByteBuffer bb = ByteBuffer.allocate(8192); + while (srcCh.read(bb) >= 0) { + bb.flip(); + dstCh.write(bb); + bb.clear(); + } + } finally { + srcCh.close(); + dstCh.close(); + } + } + + private static void streamCopy(Path src, Path dst) throws IOException + { + InputStream isSrc = src.newInputStream(); + OutputStream osDst = dst.newOutputStream(); + byte[] buf = new byte[8192]; + try { + int n = 0; + while ((n = isSrc.read(buf)) != -1) { + osDst.write(buf, 0, n); + } + } finally { + isSrc.close(); + osDst.close(); + } + } +} diff --git a/src/share/native/java/io/RandomAccessFile.c b/src/share/native/java/io/RandomAccessFile.c index a8c3390b677a3acc62001ffbf09b77ce73e96aa0..437bab6b8318992c3aef42c12f20ecd1c14cfb2f 100644 --- a/src/share/native/java/io/RandomAccessFile.c +++ b/src/share/native/java/io/RandomAccessFile.c @@ -76,13 +76,13 @@ Java_java_io_RandomAccessFile_readBytes(JNIEnv *env, JNIEXPORT void JNICALL Java_java_io_RandomAccessFile_write(JNIEnv *env, jobject this, jint byte) { - writeSingle(env, this, byte, raf_fd); + writeSingle(env, this, byte, JNI_FALSE, raf_fd); } JNIEXPORT void JNICALL Java_java_io_RandomAccessFile_writeBytes(JNIEnv *env, jobject this, jbyteArray bytes, jint off, jint len) { - writeBytes(env, this, bytes, off, len, raf_fd); + writeBytes(env, this, bytes, off, len, JNI_FALSE, raf_fd); } JNIEXPORT jlong JNICALL diff --git a/src/share/native/java/io/io_util.c b/src/share/native/java/io/io_util.c index 986416e20d839c2126d738e031e7d61dd3292163..cef7d272ba24f8785f19c520bca331a5d1383429 100644 --- a/src/share/native/java/io/io_util.c +++ b/src/share/native/java/io/io_util.c @@ -127,7 +127,7 @@ readBytes(JNIEnv *env, jobject this, jbyteArray bytes, } void -writeSingle(JNIEnv *env, jobject this, jint byte, jfieldID fid) { +writeSingle(JNIEnv *env, jobject this, jint byte, jboolean append, jfieldID fid) { // Discard the 24 high-order bits of byte. See OutputStream#write(int) char c = (char) byte; jint n; @@ -136,7 +136,11 @@ writeSingle(JNIEnv *env, jobject this, jint byte, jfieldID fid) { JNU_ThrowIOException(env, "Stream Closed"); return; } - n = IO_Write(fd, &c, 1); + if (append == JNI_TRUE) { + n = IO_Append(fd, &c, 1); + } else { + n = IO_Write(fd, &c, 1); + } if (n == JVM_IO_ERR) { JNU_ThrowIOExceptionWithLastError(env, "Write error"); } else if (n == JVM_IO_INTR) { @@ -146,7 +150,7 @@ writeSingle(JNIEnv *env, jobject this, jint byte, jfieldID fid) { void writeBytes(JNIEnv *env, jobject this, jbyteArray bytes, - jint off, jint len, jfieldID fid) + jint off, jint len, jboolean append, jfieldID fid) { jint n; char stackBuf[BUF_SIZE]; @@ -185,7 +189,11 @@ writeBytes(JNIEnv *env, jobject this, jbyteArray bytes, JNU_ThrowIOException(env, "Stream Closed"); break; } - n = IO_Write(fd, buf+off, len); + if (append == JNI_TRUE) { + n = IO_Append(fd, buf+off, len); + } else { + n = IO_Write(fd, buf+off, len); + } if (n == JVM_IO_ERR) { JNU_ThrowIOExceptionWithLastError(env, "Write error"); break; diff --git a/src/share/native/java/io/io_util.h b/src/share/native/java/io/io_util.h index 436acdff16d21d73b2015d5692a44dbb3c3cd4c1..b98c5274a4818dd31f12e9a46b023f318699455e 100644 --- a/src/share/native/java/io/io_util.h +++ b/src/share/native/java/io/io_util.h @@ -41,9 +41,9 @@ extern jfieldID IO_handle_fdID; jint readSingle(JNIEnv *env, jobject this, jfieldID fid); jint readBytes(JNIEnv *env, jobject this, jbyteArray bytes, jint off, jint len, jfieldID fid); -void writeSingle(JNIEnv *env, jobject this, jint byte, jfieldID fid); +void writeSingle(JNIEnv *env, jobject this, jint byte, jboolean append, jfieldID fid); void writeBytes(JNIEnv *env, jobject this, jbyteArray bytes, jint off, - jint len, jfieldID fid); + jint len, jboolean append, jfieldID fid); void fileOpen(JNIEnv *env, jobject this, jstring path, jfieldID fid, int flags); void throwFileNotFoundException(JNIEnv *env, jstring path); diff --git a/src/share/native/java/util/zip/Deflater.c b/src/share/native/java/util/zip/Deflater.c index f0923c447ba1fb27149beabb6f1578f66534bebd..e12d540a5444865d1135e22bb1e74d3a119f7cbe 100644 --- a/src/share/native/java/util/zip/Deflater.c +++ b/src/share/native/java/util/zip/Deflater.c @@ -132,14 +132,17 @@ Java_java_util_zip_Deflater_deflateBytes(JNIEnv *env, jobject this, jlong addr, in_buf = (jbyte *) malloc(this_len); if (in_buf == 0) { - JNU_ThrowOutOfMemoryError(env, 0); + // Throw OOME only when length is not zero + if (this_len != 0) + JNU_ThrowOutOfMemoryError(env, 0); return 0; } (*env)->GetByteArrayRegion(env, this_buf, this_off, this_len, in_buf); out_buf = (jbyte *) malloc(len); if (out_buf == 0) { free(in_buf); - JNU_ThrowOutOfMemoryError(env, 0); + if (len != 0) + JNU_ThrowOutOfMemoryError(env, 0); return 0; } @@ -173,7 +176,8 @@ Java_java_util_zip_Deflater_deflateBytes(JNIEnv *env, jobject this, jlong addr, jboolean finish = (*env)->GetBooleanField(env, this, finishID); in_buf = (jbyte *) malloc(this_len); if (in_buf == 0) { - JNU_ThrowOutOfMemoryError(env, 0); + if (this_len != 0) + JNU_ThrowOutOfMemoryError(env, 0); return 0; } (*env)->GetByteArrayRegion(env, this_buf, this_off, this_len, in_buf); @@ -181,7 +185,8 @@ Java_java_util_zip_Deflater_deflateBytes(JNIEnv *env, jobject this, jlong addr, out_buf = (jbyte *) malloc(len); if (out_buf == 0) { free(in_buf); - JNU_ThrowOutOfMemoryError(env, 0); + if (len != 0) + JNU_ThrowOutOfMemoryError(env, 0); return 0; } diff --git a/src/share/native/java/util/zip/Inflater.c b/src/share/native/java/util/zip/Inflater.c index 78619f4ac0f0d7f9f1bd4ef9c2922251ae511f60..c1667a022e842defbeac6db191139172f2e36028 100644 --- a/src/share/native/java/util/zip/Inflater.c +++ b/src/share/native/java/util/zip/Inflater.c @@ -135,7 +135,8 @@ Java_java_util_zip_Inflater_inflateBytes(JNIEnv *env, jobject this, jlong addr, in_buf = (jbyte *) malloc(in_len); if (in_buf == 0) { - JNU_ThrowOutOfMemoryError(env, 0); + if (in_len != 0) + JNU_ThrowOutOfMemoryError(env, 0); return 0; } (*env)->GetByteArrayRegion(env, this_buf, this_off, in_len, in_buf); @@ -143,7 +144,8 @@ Java_java_util_zip_Inflater_inflateBytes(JNIEnv *env, jobject this, jlong addr, out_buf = (jbyte *) malloc(len); if (out_buf == 0) { free(in_buf); - JNU_ThrowOutOfMemoryError(env, 0); + if (len != 0) + JNU_ThrowOutOfMemoryError(env, 0); return 0; } diff --git a/src/solaris/classes/java/lang/ProcessImpl.java b/src/solaris/classes/java/lang/ProcessImpl.java index 5c291b138c31419097ea64e9f8a6b58d9090da6a..ed0c6397677007a2e6529dbe7f907115cfe3ddc3 100644 --- a/src/solaris/classes/java/lang/ProcessImpl.java +++ b/src/solaris/classes/java/lang/ProcessImpl.java @@ -111,7 +111,8 @@ final class ProcessImpl { else if (redirects[1] == Redirect.INHERIT) std_fds[1] = 1; else { - f1 = redirects[1].toFileOutputStream(); + f1 = new FileOutputStream(redirects[1].file(), + redirects[1].append()); std_fds[1] = fdAccess.get(f1.getFD()); } @@ -120,7 +121,8 @@ final class ProcessImpl { else if (redirects[2] == Redirect.INHERIT) std_fds[2] = 2; else { - f2 = redirects[2].toFileOutputStream(); + f2 = new FileOutputStream(redirects[2].file(), + redirects[2].append()); std_fds[2] = fdAccess.get(f2.getFD()); } } diff --git a/src/solaris/classes/sun/awt/X11/GtkFileDialogPeer.java b/src/solaris/classes/sun/awt/X11/GtkFileDialogPeer.java index 57a0492ddee0fc045174645bad2c478d07f82de1..f67efb57fb687b6982e343dd0f4f4c3082099827 100644 --- a/src/solaris/classes/sun/awt/X11/GtkFileDialogPeer.java +++ b/src/solaris/classes/sun/awt/X11/GtkFileDialogPeer.java @@ -42,11 +42,19 @@ class GtkFileDialogPeer extends XDialogPeer implements FileDialogPeer { private FileDialog fd; + // A pointer to the native GTK FileChooser widget + private volatile long widget = 0L; + public GtkFileDialogPeer(FileDialog fd) { super((Dialog) fd); this.fd = fd; } + private static native void initIDs(); + static { + initIDs(); + } + private native void run(String title, int mode, String dir, String file, FilenameFilter filter, boolean isMultipleMode); diff --git a/src/solaris/classes/sun/nio/ch/FileDispatcherImpl.java b/src/solaris/classes/sun/nio/ch/FileDispatcherImpl.java index 6f17340372e3692b443802073415c94ed2a757dd..f56d317cc91106563daa298ade43f6e6ddf8fa10 100644 --- a/src/solaris/classes/sun/nio/ch/FileDispatcherImpl.java +++ b/src/solaris/classes/sun/nio/ch/FileDispatcherImpl.java @@ -35,6 +35,13 @@ class FileDispatcherImpl extends FileDispatcher init(); } + FileDispatcherImpl(boolean append) { + /* append is ignored */ + } + + FileDispatcherImpl() { + } + int read(FileDescriptor fd, long address, int len) throws IOException { return read0(fd, address, len); } diff --git a/src/solaris/native/java/io/FileOutputStream_md.c b/src/solaris/native/java/io/FileOutputStream_md.c index 1d71052ec5651005840f82ce5b1b2db9fb8323ac..ffc2011797ddb9e02f5eeffecac77e1f7ce344a0 100644 --- a/src/solaris/native/java/io/FileOutputStream_md.c +++ b/src/solaris/native/java/io/FileOutputStream_md.c @@ -60,14 +60,14 @@ Java_java_io_FileOutputStream_open(JNIEnv *env, jobject this, } JNIEXPORT void JNICALL -Java_java_io_FileOutputStream_write(JNIEnv *env, jobject this, jint byte) { - writeSingle(env, this, byte, fos_fd); +Java_java_io_FileOutputStream_write(JNIEnv *env, jobject this, jint byte, jboolean append) { + writeSingle(env, this, byte, append, fos_fd); } JNIEXPORT void JNICALL Java_java_io_FileOutputStream_writeBytes(JNIEnv *env, - jobject this, jbyteArray bytes, jint off, jint len) { - writeBytes(env, this, bytes, off, len, fos_fd); + jobject this, jbyteArray bytes, jint off, jint len, jboolean append) { + writeBytes(env, this, bytes, off, len, append, fos_fd); } JNIEXPORT void JNICALL diff --git a/src/solaris/native/java/io/io_util_md.h b/src/solaris/native/java/io/io_util_md.h index 378fbcb1ebc24f4a3dbfcd4ceea7a2fb93ec1561..b5fe90e6a7387b89505703d44962010bdfca85d8 100644 --- a/src/solaris/native/java/io/io_util_md.h +++ b/src/solaris/native/java/io/io_util_md.h @@ -53,8 +53,9 @@ #define THIS_FD(obj) (*env)->GetIntField(env, obj, IO_fd_fdID) /* - * Route the routines through HPI + * Route the routines through VM */ +#define IO_Append JVM_Write #define IO_Write JVM_Write #define IO_Sync JVM_Sync #define IO_Read JVM_Read diff --git a/src/solaris/native/sun/awt/awt_MToolkit.c b/src/solaris/native/sun/awt/awt_MToolkit.c index 744646cf38ff5c3a77e4fbd00f5c442b4e8f4596..3a7c117b23bd1ff9acd6b789221f357b5a4a25c6 100644 --- a/src/solaris/native/sun/awt/awt_MToolkit.c +++ b/src/solaris/native/sun/awt/awt_MToolkit.c @@ -2773,11 +2773,6 @@ Java_sun_awt_motif_MToolkit_init(JNIEnv *env, jobject this, } } - /* - scrollBugWorkAround = - (strcmp(XServerVendor(awt_display), "Sun Microsystems, Inc.") == 0 - && XVendorRelease(awt_display) == 3400); - */ scrollBugWorkAround = TRUE; /* diff --git a/src/solaris/native/sun/awt/fontpath.c b/src/solaris/native/sun/awt/fontpath.c index e7236e4a6ff3cce8e197827f82db38f09685b40e..22157d35a4e3f6bc19749f6ee581c5f59ef36771 100644 --- a/src/solaris/native/sun/awt/fontpath.c +++ b/src/solaris/native/sun/awt/fontpath.c @@ -557,7 +557,8 @@ JNIEXPORT jstring JNICALL Java_sun_awt_X11FontManager_getFontPath #ifndef HEADLESS static int isSunXServer() { #ifdef __solaris__ - return (strcmp("Sun Microsystems, Inc.", ServerVendor(awt_display)) == 0 && + return ((strncmp(ServerVendor(awt_display), "Sun Microsystems, Inc.", 22) == 0) || + (strncmp(ServerVendor(awt_display), "Oracle Corporation", 18) == 0) && VendorRelease(awt_display) >= 6410); #else return 0; diff --git a/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c b/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c index 0c26096e58009cb3852cee3ed4b94865cfa40f6c..890284e570e423f7123035c75cd775f449e723ce 100644 --- a/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c +++ b/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.c @@ -4,13 +4,29 @@ #include #include "gtk2_interface.h" #include "sun_awt_X11_GtkFileDialogPeer.h" +#include "debug_assert.h" static JavaVM *jvm; -static GtkWidget *dialog = NULL; /* To cache some method IDs */ static jmethodID filenameFilterCallbackMethodID = NULL; static jmethodID setFileInternalMethodID = NULL; +static jfieldID widgetFieldID = NULL; + +JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_initIDs +(JNIEnv *env, jclass cx) +{ + filenameFilterCallbackMethodID = (*env)->GetMethodID(env, cx, + "filenameFilterCallback", "(Ljava/lang/String;)Z"); + DASSERT(filenameFilterCallbackMethodID != NULL); + + setFileInternalMethodID = (*env)->GetMethodID(env, cx, + "setFileInternal", "(Ljava/lang/String;[Ljava/lang/String;)V"); + DASSERT(setFileInternalMethodID != NULL); + + widgetFieldID = (*env)->GetFieldID(env, cx, "widget", "J"); + DASSERT(widgetFieldID != NULL); +} static gboolean filenameFilterCallback(const GtkFileFilterInfo * filter_info, gpointer obj) { @@ -20,30 +36,17 @@ static gboolean filenameFilterCallback(const GtkFileFilterInfo * filter_info, gp env = (JNIEnv *) JNU_GetEnv(jvm, JNI_VERSION_1_2); - if (filenameFilterCallbackMethodID == NULL) { - cx = (*env)->GetObjectClass(env, (jobject) obj); - if (cx == NULL) { - JNU_ThrowInternalError(env, "Could not get file filter class"); - return 0; - } - - filenameFilterCallbackMethodID = (*env)->GetMethodID(env, cx, - "filenameFilterCallback", "(Ljava/lang/String;)Z"); - if (filenameFilterCallbackMethodID == NULL) { - JNU_ThrowInternalError(env, - "Could not get filenameFilterCallback method id"); - return 0; - } - } - filename = (*env)->NewStringUTF(env, filter_info->filename); return (*env)->CallBooleanMethod(env, obj, filenameFilterCallbackMethodID, filename); } -static void quit(gboolean isSignalHandler) +static void quit(JNIEnv * env, jobject jpeer, gboolean isSignalHandler) { + GtkWidget * dialog = (GtkWidget*)jlong_to_ptr( + (*env)->GetLongField(env, jpeer, widgetFieldID)); + if (dialog != NULL) { // Callbacks from GTK signals are made within the GTK lock @@ -57,7 +60,8 @@ static void quit(gboolean isSignalHandler) fp_gtk_widget_destroy (dialog); fp_gtk_main_quit (); - dialog = NULL; + + (*env)->SetLongField(env, jpeer, widgetFieldID, 0); if (!isSignalHandler) { fp_gdk_threads_leave(); @@ -73,7 +77,7 @@ static void quit(gboolean isSignalHandler) JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_quit (JNIEnv * env, jobject jpeer) { - quit(FALSE); + quit(env, jpeer, FALSE); } /** @@ -132,24 +136,8 @@ static void handle_response(GtkWidget* aDialog, gint responseId, gpointer obj) if (responseId == GTK_RESPONSE_ACCEPT) { current_folder = fp_gtk_file_chooser_get_current_folder( - GTK_FILE_CHOOSER(dialog)); - filenames = fp_gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dialog)); - } - - if (setFileInternalMethodID == NULL) { - cx = (*env)->GetObjectClass(env, (jobject) obj); - if (cx == NULL) { - JNU_ThrowInternalError(env, "Could not get GTK peer class"); - return; - } - - setFileInternalMethodID = (*env)->GetMethodID(env, cx, - "setFileInternal", "(Ljava/lang/String;[Ljava/lang/String;)V"); - if (setFileInternalMethodID == NULL) { - JNU_ThrowInternalError(env, - "Could not get setFileInternalMethodID method id"); - return; - } + GTK_FILE_CHOOSER(aDialog)); + filenames = fp_gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(aDialog)); } jcurrent_folder = (*env)->NewStringUTF(env, current_folder); @@ -159,7 +147,7 @@ static void handle_response(GtkWidget* aDialog, gint responseId, gpointer obj) jfilenames); fp_g_free(current_folder); - quit(TRUE); + quit(env, (jobject)obj, TRUE); } /* @@ -172,6 +160,7 @@ Java_sun_awt_X11_GtkFileDialogPeer_run(JNIEnv * env, jobject jpeer, jstring jtitle, jint mode, jstring jdir, jstring jfile, jobject jfilter, jboolean multiple) { + GtkWidget *dialog = NULL; GtkFileFilter *filter; if (jvm == NULL) { @@ -233,8 +222,12 @@ Java_sun_awt_X11_GtkFileDialogPeer_run(JNIEnv * env, jobject jpeer, fp_g_signal_connect(G_OBJECT(dialog), "response", G_CALLBACK( handle_response), jpeer); + + (*env)->SetLongField(env, jpeer, widgetFieldID, ptr_to_jlong(dialog)); + fp_gtk_widget_show(dialog); fp_gtk_main(); fp_gdk_threads_leave(); } + diff --git a/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.h b/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.h index 91334b4ebeec3bfbe9ec58d0c8940f49297932e2..7c3c2338d10d4a85ed286520141b32db94d0962f 100644 --- a/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.h +++ b/src/solaris/native/sun/awt/sun_awt_X11_GtkFileDialogPeer.h @@ -9,6 +9,14 @@ extern "C" { #endif +/* + * Class: sun_awt_X11_GtkFileDialogPeer + * Method: initIDs + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_sun_awt_X11_GtkFileDialogPeer_initIDs +(JNIEnv *, jclass); + /* * Class: sun_awt_X11_GtkFileDialogPeer * Method: run diff --git a/src/solaris/native/sun/xawt/XWindow.c b/src/solaris/native/sun/xawt/XWindow.c index 4a66d4d7e6bf6c903a82271e8ac386ab9c64c9e0..d33c87f424c9393535c75fd8a758b711c6c27767 100644 --- a/src/solaris/native/sun/xawt/XWindow.c +++ b/src/solaris/native/sun/xawt/XWindow.c @@ -766,7 +766,9 @@ adjustKeySym(XEvent *event, KeySym *keysym) static Boolean isXsunServer(XEvent *event) { if( awt_ServerDetected ) return awt_IsXsun; - if( strncmp( ServerVendor( event->xkey.display ), "Sun Microsystems, Inc.", 32) ) { + if( (strncmp( ServerVendor( event->xkey.display ), "Sun Microsystems, Inc.", 22) != 0) && + (strncmp( ServerVendor( event->xkey.display ), "Oracle Corporation", 18) != 0) ) + { awt_ServerDetected = True; awt_IsXsun = False; return False; diff --git a/src/windows/classes/java/lang/ProcessImpl.java b/src/windows/classes/java/lang/ProcessImpl.java index c0a0daa09a8428bd9a2086cb0287a6eba454ee3c..b3357dd0c9d58dc5f2d0af2aba3fe8ae9e7c5178 100644 --- a/src/windows/classes/java/lang/ProcessImpl.java +++ b/src/windows/classes/java/lang/ProcessImpl.java @@ -35,6 +35,8 @@ import java.io.FileDescriptor; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.lang.ProcessBuilder.Redirect; +import java.security.AccessController; +import java.security.PrivilegedAction; /* This class is for the exclusive use of ProcessBuilder.start() to * create new processes. @@ -47,6 +49,35 @@ final class ProcessImpl extends Process { private static final sun.misc.JavaIOFileDescriptorAccess fdAccess = sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess(); + /** + * Open a file for writing. If {@code append} is {@code true} then the file + * is opened for atomic append directly and a FileOutputStream constructed + * with the resulting handle. This is because a FileOutputStream created + * to append to a file does not open the file in a manner that guarantees + * that writes by the child process will be atomic. + */ + private static FileOutputStream newFileOutputStream(File f, boolean append) + throws IOException + { + if (append) { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkWrite(f.getPath()); + long handle = openForAtomicAppend(f.getPath()); + final FileDescriptor fd = new FileDescriptor(); + fdAccess.setHandle(fd, handle); + return AccessController.doPrivileged( + new PrivilegedAction() { + public FileOutputStream run() { + return new FileOutputStream(fd); + } + } + ); + } else { + return new FileOutputStream(f); + } + } + // System-dependent portion of ProcessBuilder.start() static Process start(String cmdarray[], java.util.Map environment, @@ -82,7 +113,8 @@ final class ProcessImpl extends Process { else if (redirects[1] == Redirect.INHERIT) stdHandles[1] = fdAccess.getHandle(FileDescriptor.out); else { - f1 = redirects[1].toFileOutputStream(); + f1 = newFileOutputStream(redirects[1].file(), + redirects[1].append()); stdHandles[1] = fdAccess.getHandle(f1.getFD()); } @@ -91,7 +123,8 @@ final class ProcessImpl extends Process { else if (redirects[2] == Redirect.INHERIT) stdHandles[2] = fdAccess.getHandle(FileDescriptor.err); else { - f2 = redirects[2].toFileOutputStream(); + f2 = newFileOutputStream(redirects[2].file(), + redirects[2].append()); stdHandles[2] = fdAccess.getHandle(f2.getFD()); } } @@ -251,5 +284,15 @@ final class ProcessImpl extends Process { boolean redirectErrorStream) throws IOException; + /** + * Opens a file for atomic append. The file is created if it doesn't + * already exist. + * + * @param file the file to open or create + * @return the native HANDLE + */ + private static native long openForAtomicAppend(String path) + throws IOException; + private static native boolean closeHandle(long handle); } diff --git a/src/windows/classes/sun/nio/ch/FileDispatcherImpl.java b/src/windows/classes/sun/nio/ch/FileDispatcherImpl.java index 2cdc8f8fe9fcffc66ff034f13fcff1e41e9b5b0d..43f0745be4084fb6b04a4351b86e59ed02551fe1 100644 --- a/src/windows/classes/sun/nio/ch/FileDispatcherImpl.java +++ b/src/windows/classes/sun/nio/ch/FileDispatcherImpl.java @@ -35,6 +35,20 @@ class FileDispatcherImpl extends FileDispatcher Util.load(); } + /** + * Indicates if the dispatcher should first advance the file position + * to the end of file when writing. + */ + private final boolean append; + + FileDispatcherImpl(boolean append) { + this.append = append; + } + + FileDispatcherImpl() { + this(false); + } + int read(FileDescriptor fd, long address, int len) throws IOException { @@ -54,7 +68,7 @@ class FileDispatcherImpl extends FileDispatcher } int write(FileDescriptor fd, long address, int len) throws IOException { - return write0(fd, address, len); + return write0(fd, address, len, append); } int pwrite(FileDescriptor fd, long address, int len, @@ -66,7 +80,7 @@ class FileDispatcherImpl extends FileDispatcher } long writev(FileDescriptor fd, long address, int len) throws IOException { - return writev0(fd, address, len); + return writev0(fd, address, len, append); } int force(FileDescriptor fd, boolean metaData) throws IOException { @@ -116,13 +130,13 @@ class FileDispatcherImpl extends FileDispatcher static native long readv0(FileDescriptor fd, long address, int len) throws IOException; - static native int write0(FileDescriptor fd, long address, int len) + static native int write0(FileDescriptor fd, long address, int len, boolean append) throws IOException; static native int pwrite0(FileDescriptor fd, long address, int len, long position) throws IOException; - static native long writev0(FileDescriptor fd, long address, int len) + static native long writev0(FileDescriptor fd, long address, int len, boolean append) throws IOException; static native int force0(FileDescriptor fd, boolean metaData) diff --git a/src/windows/classes/sun/nio/fs/WindowsChannelFactory.java b/src/windows/classes/sun/nio/fs/WindowsChannelFactory.java index 3795a6f40d2e9552e10f6624e2886a7b0f1d7ba8..736ea7b1ea0562336af9af8fd90e2420f026ec3d 100644 --- a/src/windows/classes/sun/nio/fs/WindowsChannelFactory.java +++ b/src/windows/classes/sun/nio/fs/WindowsChannelFactory.java @@ -157,7 +157,7 @@ class WindowsChannelFactory { throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed"); FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor); - return FileChannelImpl.open(fdObj, flags.read, flags.write, null); + return FileChannelImpl.open(fdObj, flags.read, flags.write, flags.append, null); } /** @@ -230,7 +230,7 @@ class WindowsChannelFactory { if (flags.read) dwDesiredAccess |= GENERIC_READ; if (flags.write) - dwDesiredAccess |= (flags.append) ? FILE_APPEND_DATA : GENERIC_WRITE; + dwDesiredAccess |= GENERIC_WRITE; int dwShareMode = 0; if (flags.shareRead) diff --git a/src/windows/classes/sun/security/krb5/internal/tools/Ktab.java b/src/windows/classes/sun/security/krb5/internal/tools/Ktab.java index 9bcc935a1ca2f9fe5e9a9725d229aaf778a31933..216c3a30c1273b908801649438ce18d7bbc04a45 100644 --- a/src/windows/classes/sun/security/krb5/internal/tools/Ktab.java +++ b/src/windows/classes/sun/security/krb5/internal/tools/Ktab.java @@ -129,7 +129,7 @@ public class Ktab { ktab.deleteEntry(); break; default: - ktab.printHelp(); + ktab.error("A command must be provided"); } } @@ -232,7 +232,7 @@ public class Ktab { append = true; break; default: - printHelp(); + error("Unknown command: " + args[i]); break; } } else { // optional standalone arguments diff --git a/src/windows/native/java/io/FileOutputStream_md.c b/src/windows/native/java/io/FileOutputStream_md.c index 221ba504f5f22f3c7377e57c94b6bf48ee676833..23c754d466739bfa796cc3bf9003191707cb2a60 100644 --- a/src/windows/native/java/io/FileOutputStream_md.c +++ b/src/windows/native/java/io/FileOutputStream_md.c @@ -61,14 +61,15 @@ Java_java_io_FileOutputStream_open(JNIEnv *env, jobject this, } JNIEXPORT void JNICALL -Java_java_io_FileOutputStream_write(JNIEnv *env, jobject this, jint byte) { - writeSingle(env, this, byte, fos_fd); +Java_java_io_FileOutputStream_write(JNIEnv *env, jobject this, jint byte, jboolean append) { + writeSingle(env, this, byte, append, fos_fd); } JNIEXPORT void JNICALL Java_java_io_FileOutputStream_writeBytes(JNIEnv *env, - jobject this, jbyteArray bytes, jint off, jint len) { - writeBytes(env, this, bytes, off, len, fos_fd); + jobject this, jbyteArray bytes, jint off, jint len, jboolean append) +{ + writeBytes(env, this, bytes, off, len, append, fos_fd); } JNIEXPORT void JNICALL diff --git a/src/windows/native/java/io/io_util_md.c b/src/windows/native/java/io/io_util_md.c index 722913f775a3a2491bdc8382ac1165cc831d05ee..2679e7b951700986fc28fd75ceba546f71872f2a 100644 --- a/src/windows/native/java/io/io_util_md.c +++ b/src/windows/native/java/io/io_util_md.c @@ -225,14 +225,7 @@ pathToNTPath(JNIEnv *env, jstring path, jboolean throwFNFE) { jlong winFileHandleOpen(JNIEnv *env, jstring path, int flags) { - /* To implement O_APPEND, we use the strategy from - http://msdn2.microsoft.com/en-us/library/aa363858.aspx - "You can get atomic append by opening a file with - FILE_APPEND_DATA access and _without_ FILE_WRITE_DATA access. - If you do this then all writes will ignore the current file - pointer and be done at the end-of file." */ const DWORD access = - (flags & O_APPEND) ? (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA) : (flags & O_WRONLY) ? GENERIC_WRITE : (flags & O_RDWR) ? (GENERIC_READ | GENERIC_WRITE) : GENERIC_READ; @@ -307,7 +300,6 @@ handleStdinAvailable(jlong, long *); int handleAvailable(jlong fd, jlong *pbytes) { - jlong current, end; HANDLE h = (HANDLE)fd; DWORD type = 0; @@ -327,18 +319,17 @@ handleAvailable(jlong fd, jlong *pbytes) { } /* Handle is for regular file */ if (type == FILE_TYPE_DISK) { - long highPos = 0; - DWORD sizeLow = 0; - DWORD sizeHigh = 0; - DWORD lowPos = SetFilePointer(h, 0, &highPos, FILE_CURRENT); - if (lowPos == ((DWORD)-1)) { + jlong current, end; + + LARGE_INTEGER filesize; + current = handleLseek(fd, 0, SEEK_CUR); + if (current < 0) { return FALSE; } - current = (((jlong)highPos) << 32) | lowPos; - end = GetFileSize(h, &sizeHigh); - if (sizeLow == ((DWORD)-1)) { + if (GetFileSizeEx(h, &filesize) == 0) { return FALSE; } + end = long_to_jlong(filesize.QuadPart); *pbytes = end - current; return TRUE; } @@ -511,24 +502,42 @@ handleRead(jlong fd, void *buf, jint len) return read; } -JNIEXPORT -size_t -handleWrite(jlong fd, const void *buf, jint len) +static size_t writeInternal(jlong fd, const void *buf, jint len, jboolean append) { BOOL result = 0; DWORD written = 0; HANDLE h = (HANDLE)fd; if (h != INVALID_HANDLE_VALUE) { - result = WriteFile(h, /* File handle to write */ - buf, /* pointers to the buffers */ - len, /* number of bytes to write */ - &written, /* receives number of bytes written */ - NULL); /* no overlapped struct */ + OVERLAPPED ov; + LPOVERLAPPED lpOv; + if (append == JNI_TRUE) { + ov.Offset = (DWORD)0xFFFFFFFF; + ov.OffsetHigh = (DWORD)0xFFFFFFFF; + ov.hEvent = NULL; + lpOv = &ov; + } else { + lpOv = NULL; + } + result = WriteFile(h, /* File handle to write */ + buf, /* pointers to the buffers */ + len, /* number of bytes to write */ + &written, /* receives number of bytes written */ + lpOv); /* overlapped struct */ } if ((h == INVALID_HANDLE_VALUE) || (result == 0)) { return -1; } - return written; + return (size_t)written; +} + +JNIEXPORT +size_t handleWrite(jlong fd, const void *buf, jint len) { + return writeInternal(fd, buf, len, JNI_FALSE); +} + +JNIEXPORT +size_t handleAppend(jlong fd, const void *buf, jint len) { + return writeInternal(fd, buf, len, JNI_TRUE); } jint @@ -558,6 +567,7 @@ handleClose(JNIEnv *env, jobject this, jfieldID fid) jlong handleLseek(jlong fd, jlong offset, jint whence) { + LARGE_INTEGER pos, distance; DWORD lowPos = 0; long highPos = 0; DWORD op = FILE_CURRENT; @@ -573,13 +583,9 @@ handleLseek(jlong fd, jlong offset, jint whence) op = FILE_BEGIN; } - lowPos = (DWORD)offset; - highPos = (long)(offset >> 32); - lowPos = SetFilePointer(h, lowPos, &highPos, op); - if (lowPos == ((DWORD)-1)) { - if (GetLastError() != ERROR_SUCCESS) { - return -1; - } + distance.QuadPart = offset; + if (SetFilePointerEx(h, distance, &pos, op) == 0) { + return -1; } - return (((jlong)highPos) << 32) | lowPos; + return long_to_jlong(pos.QuadPart); } diff --git a/src/windows/native/java/io/io_util_md.h b/src/windows/native/java/io/io_util_md.h index 6b6b89b6397a998eb28b335dcc553df5c79ffae0..97a68c2febae0cdba5f5335b9a56ab4e42ad66c4 100644 --- a/src/windows/native/java/io/io_util_md.h +++ b/src/windows/native/java/io/io_util_md.h @@ -41,6 +41,7 @@ JNIEXPORT int handleSync(jlong fd); int handleSetLength(jlong fd, jlong length); JNIEXPORT size_t handleRead(jlong fd, void *buf, jint len); JNIEXPORT size_t handleWrite(jlong fd, const void *buf, jint len); +JNIEXPORT size_t handleAppend(jlong fd, const void *buf, jint len); jint handleClose(JNIEnv *env, jobject this, jfieldID fid); jlong handleLseek(jlong fd, jlong offset, jint whence); @@ -74,8 +75,9 @@ jlong winFileHandleOpen(JNIEnv *env, jstring path, int flags); #define THIS_FD(obj) (*env)->GetLongField(env, obj, IO_handle_fdID) /* - * Route the routines away from HPI layer + * Route the routines away from VM */ +#define IO_Append handleAppend #define IO_Write handleWrite #define IO_Sync handleSync #define IO_Read handleRead diff --git a/src/windows/native/java/lang/ProcessImpl_md.c b/src/windows/native/java/lang/ProcessImpl_md.c index e5fe23e71ec842515a3851557cbc77a11bbdadcb..afc5e7d2529acda414732ac0c78f4fac37e7aa20 100644 --- a/src/windows/native/java/lang/ProcessImpl_md.c +++ b/src/windows/native/java/lang/ProcessImpl_md.c @@ -315,3 +315,51 @@ Java_java_lang_ProcessImpl_closeHandle(JNIEnv *env, jclass ignored, jlong handle { return CloseHandle((HANDLE) handle); } + +/** + * Returns a copy of the Unicode characters of a string. Fow now this + * function doesn't handle long path names and other issues. + */ +static WCHAR* getPath(JNIEnv *env, jstring ps) { + WCHAR *pathbuf = NULL; + const jchar *chars = (*(env))->GetStringChars(env, ps, NULL); + if (chars != NULL) { + size_t pathlen = wcslen(chars); + pathbuf = (WCHAR*)malloc((pathlen + 6) * sizeof(WCHAR)); + if (pathbuf == NULL) { + JNU_ThrowOutOfMemoryError(env, NULL); + } else { + wcscpy(pathbuf, chars); + } + (*env)->ReleaseStringChars(env, ps, chars); + } + return pathbuf; +} + +JNIEXPORT jlong JNICALL +Java_java_lang_ProcessImpl_openForAtomicAppend(JNIEnv *env, jclass ignored, jstring path) +{ + const DWORD access = (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); + const DWORD sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; + const DWORD disposition = OPEN_ALWAYS; + const DWORD flagsAndAttributes = FILE_ATTRIBUTE_NORMAL; + HANDLE h; + WCHAR *pathbuf = getPath(env, path); + if (pathbuf == NULL) { + /* Exception already pending */ + return -1; + } + h = CreateFileW( + pathbuf, /* Wide char path name */ + access, /* Read and/or write permission */ + sharing, /* File sharing flags */ + NULL, /* Security attributes */ + disposition, /* creation disposition */ + flagsAndAttributes, /* flags and attributes */ + NULL); + free(pathbuf); + if (h == INVALID_HANDLE_VALUE) { + JNU_ThrowIOExceptionWithLastError(env, "CreateFileW"); + } + return ptr_to_jlong(h); +} diff --git a/src/windows/native/sun/nio/ch/FileDispatcherImpl.c b/src/windows/native/sun/nio/ch/FileDispatcherImpl.c index f4d0b17d63b94a599c4c07f2b6fe36fac26e1ae5..2a146c284facabd6c441aa8cd379554188918db9 100644 --- a/src/windows/native/sun/nio/ch/FileDispatcherImpl.c +++ b/src/windows/native/sun/nio/ch/FileDispatcherImpl.c @@ -184,18 +184,28 @@ Java_sun_nio_ch_FileDispatcherImpl_pread0(JNIEnv *env, jclass clazz, jobject fdo JNIEXPORT jint JNICALL Java_sun_nio_ch_FileDispatcherImpl_write0(JNIEnv *env, jclass clazz, jobject fdo, - jlong address, jint len) + jlong address, jint len, jboolean append) { BOOL result = 0; DWORD written = 0; HANDLE h = (HANDLE)(handleval(env, fdo)); if (h != INVALID_HANDLE_VALUE) { + OVERLAPPED ov; + LPOVERLAPPED lpOv; + if (append == JNI_TRUE) { + ov.Offset = (DWORD)0xFFFFFFFF; + ov.OffsetHigh = (DWORD)0xFFFFFFFF; + ov.hEvent = NULL; + lpOv = &ov; + } else { + lpOv = NULL; + } result = WriteFile(h, /* File handle to write */ (LPCVOID)address, /* pointers to the buffers */ len, /* number of bytes to write */ &written, /* receives number of bytes written */ - NULL); /* no overlapped struct */ + lpOv); /* overlapped struct */ } if ((h == INVALID_HANDLE_VALUE) || (result == 0)) { @@ -207,7 +217,7 @@ Java_sun_nio_ch_FileDispatcherImpl_write0(JNIEnv *env, jclass clazz, jobject fdo JNIEXPORT jlong JNICALL Java_sun_nio_ch_FileDispatcherImpl_writev0(JNIEnv *env, jclass clazz, jobject fdo, - jlong address, jint len) + jlong address, jint len, jboolean append) { BOOL result = 0; DWORD written = 0; @@ -219,7 +229,16 @@ Java_sun_nio_ch_FileDispatcherImpl_writev0(JNIEnv *env, jclass clazz, jobject fd int i = 0; DWORD num = 0; struct iovec *iovecp = (struct iovec *)jlong_to_ptr(address); - + OVERLAPPED ov; + LPOVERLAPPED lpOv; + if (append == JNI_TRUE) { + ov.Offset = (DWORD)0xFFFFFFFF; + ov.OffsetHigh = (DWORD)0xFFFFFFFF; + ov.hEvent = NULL; + lpOv = &ov; + } else { + lpOv = NULL; + } for(i=0; i 0) { totalWritten += written; } @@ -444,9 +463,10 @@ Java_sun_nio_ch_FileDispatcherImpl_closeByHandle(JNIEnv *env, jclass clazz, } JNIEXPORT jlong JNICALL -Java_sun_nio_ch_FileDispatcherImpl_duplicateHandle(JNIEnv *env, jclass this, jlong hFile) +Java_sun_nio_ch_FileDispatcherImpl_duplicateHandle(JNIEnv *env, jclass this, jlong handle) { HANDLE hProcess = GetCurrentProcess(); + HANDLE hFile = jlong_to_ptr(handle); HANDLE hResult; BOOL res = DuplicateHandle(hProcess, hFile, hProcess, &hResult, 0, FALSE, DUPLICATE_SAME_ACCESS); diff --git a/src/windows/native/sun/windows/awt_Component.cpp b/src/windows/native/sun/windows/awt_Component.cpp index 71307cb9e58b81de1eb24defea433100f8637fb7..fd75b8d52ee75fd5587764ee36e96cccf9e71676 100644 --- a/src/windows/native/sun/windows/awt_Component.cpp +++ b/src/windows/native/sun/windows/awt_Component.cpp @@ -6084,63 +6084,67 @@ void AwtComponent::SetParent(void * param) { void AwtComponent::_SetRectangularShape(void *param) { - JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); + if (!AwtToolkit::IsMainThread()) { + AwtToolkit::GetInstance().InvokeFunction(AwtComponent::_SetRectangularShape, param); + } else { + JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); - SetRectangularShapeStruct *data = (SetRectangularShapeStruct *)param; - jobject self = data->component; - jint x1 = data->x1; - jint x2 = data->x2; - jint y1 = data->y1; - jint y2 = data->y2; - jobject region = data->region; + SetRectangularShapeStruct *data = (SetRectangularShapeStruct *)param; + jobject self = data->component; + jint x1 = data->x1; + jint x2 = data->x2; + jint y1 = data->y1; + jint y2 = data->y2; + jobject region = data->region; - AwtComponent *c = NULL; + AwtComponent *c = NULL; - PDATA pData; - JNI_CHECK_PEER_GOTO(self, ret); + PDATA pData; + JNI_CHECK_PEER_GOTO(self, ret); - c = (AwtComponent *)pData; - if (::IsWindow(c->GetHWnd())) { - HRGN hRgn = NULL; - if (region || x1 || x2 || y1 || y2) { - // If all the params are zeros, the shape must be simply reset. - // Otherwise, convert it into a region. - RGNDATA *pRgnData = NULL; - RGNDATAHEADER *pRgnHdr; - - /* reserving memory for the worst case */ - size_t worstBufferSize = size_t(((x2 - x1) / 2 + 1) * (y2 - y1)); - pRgnData = (RGNDATA *) safe_Malloc(sizeof(RGNDATAHEADER) + - sizeof(RECT_T) * worstBufferSize); - pRgnHdr = (RGNDATAHEADER *) pRgnData; - - pRgnHdr->dwSize = sizeof(RGNDATAHEADER); - pRgnHdr->iType = RDH_RECTANGLES; - pRgnHdr->nRgnSize = 0; - pRgnHdr->rcBound.top = 0; - pRgnHdr->rcBound.left = 0; - pRgnHdr->rcBound.bottom = LONG(y2 - y1); - pRgnHdr->rcBound.right = LONG(x2 - x1); - - RECT_T * pRect = (RECT_T *) (((BYTE *) pRgnData) + sizeof(RGNDATAHEADER)); - pRgnHdr->nCount = RegionToYXBandedRectangles(env, x1, y1, x2, y2, region, &pRect, worstBufferSize); - - hRgn = ::ExtCreateRegion(NULL, - sizeof(RGNDATAHEADER) + sizeof(RECT_T) * pRgnHdr->nCount, pRgnData); - - free(pRgnData); - } + c = (AwtComponent *)pData; + if (::IsWindow(c->GetHWnd())) { + HRGN hRgn = NULL; + if (region || x1 || x2 || y1 || y2) { + // If all the params are zeros, the shape must be simply reset. + // Otherwise, convert it into a region. + RGNDATA *pRgnData = NULL; + RGNDATAHEADER *pRgnHdr; + + /* reserving memory for the worst case */ + size_t worstBufferSize = size_t(((x2 - x1) / 2 + 1) * (y2 - y1)); + pRgnData = (RGNDATA *) safe_Malloc(sizeof(RGNDATAHEADER) + + sizeof(RECT_T) * worstBufferSize); + pRgnHdr = (RGNDATAHEADER *) pRgnData; + + pRgnHdr->dwSize = sizeof(RGNDATAHEADER); + pRgnHdr->iType = RDH_RECTANGLES; + pRgnHdr->nRgnSize = 0; + pRgnHdr->rcBound.top = 0; + pRgnHdr->rcBound.left = 0; + pRgnHdr->rcBound.bottom = LONG(y2 - y1); + pRgnHdr->rcBound.right = LONG(x2 - x1); + + RECT_T * pRect = (RECT_T *) (((BYTE *) pRgnData) + sizeof(RGNDATAHEADER)); + pRgnHdr->nCount = RegionToYXBandedRectangles(env, x1, y1, x2, y2, region, &pRect, worstBufferSize); + + hRgn = ::ExtCreateRegion(NULL, + sizeof(RGNDATAHEADER) + sizeof(RECT_T) * pRgnHdr->nCount, pRgnData); + + free(pRgnData); + } - ::SetWindowRgn(c->GetHWnd(), hRgn, TRUE); - } + ::SetWindowRgn(c->GetHWnd(), hRgn, TRUE); + } ret: - env->DeleteGlobalRef(self); - if (region) { - env->DeleteGlobalRef(region); - } + env->DeleteGlobalRef(self); + if (region) { + env->DeleteGlobalRef(region); + } - delete data; + delete data; + } } void AwtComponent::_SetZOrder(void *param) { diff --git a/src/windows/native/sun/windows/awt_Robot.cpp b/src/windows/native/sun/windows/awt_Robot.cpp index bef6f13ede5e79ffb85d3d66d5e96a437be61a67..bab9f61b8b780c7b2460eec9890dc0dbfd76e862 100644 --- a/src/windows/native/sun/windows/awt_Robot.cpp +++ b/src/windows/native/sun/windows/awt_Robot.cpp @@ -194,9 +194,9 @@ inline jint AwtRobot::WinToJavaPixel(USHORT r, USHORT g, USHORT b) jint AwtRobot::GetRGBPixel( jint x, jint y) { - HDC hdc = GetDC(NULL); + HDC hdc = ::CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL); COLORREF ref = ::GetPixel( hdc, x, y ); - ReleaseDC(NULL,hdc); + ::DeleteDC(hdc); jint value = WinToJavaPixel(GetRValue(ref), GetGValue(ref), GetBValue(ref)); return value; } diff --git a/test/com/sun/jndi/ldap/InvalidLdapFilters.java b/test/com/sun/jndi/ldap/InvalidLdapFilters.java index 5cadd3ad5b29c46b163fc00572640eab9d5fb4de..e0e0e906a653593a583f9ded3bbe1e3cc6429eb6 100644 --- a/test/com/sun/jndi/ldap/InvalidLdapFilters.java +++ b/test/com/sun/jndi/ldap/InvalidLdapFilters.java @@ -48,6 +48,8 @@ * @run main/othervm InvalidLdapFilters valid (sn;lang-en:dn:2.4.6.8.10:=Barney) * @run main/othervm InvalidLdapFilters valid (&(objectClass=Person)(|(sn=Jensen)(cn=Bab*))) + * @run main/othervm InvalidLdapFilters valid + (orcluserapplnprovstatus;EMAIL_email=PROVISIONING_FAILURE) * @run main/othervm InvalidLdapFilters invalid "(&(cn=Robert Dean)))" * @run main/othervm InvalidLdapFilters invalid (&|(cn=Bob)) * @run main/othervm InvalidLdapFilters invalid (&&(cn=Bob)) diff --git a/test/demo/zipfs/Basic.java b/test/demo/zipfs/Basic.java index 91f8af274eeedec25d058756d47c6fd260999b65..8341b939273aed546195ad786c6d7225b739225a 100644 --- a/test/demo/zipfs/Basic.java +++ b/test/demo/zipfs/Basic.java @@ -40,24 +40,24 @@ public class Basic { boolean found = false; for (FileSystemProvider provider: FileSystemProvider.installedProviders()) { - if (provider.getScheme().equalsIgnoreCase("zip")) { + if (provider.getScheme().equalsIgnoreCase("jar")) { found = true; break; } } if (!found) - throw new RuntimeException("'zip' provider not installed"); + throw new RuntimeException("'jar' provider not installed"); // Test: FileSystems#newFileSystem(FileRef) Map env = new HashMap(); FileSystems.newFileSystem(zipfile, env, null).close(); // Test: FileSystems#newFileSystem(URI) - URI uri = URI.create("zip" + zipfile.toUri().toString().substring(4)); + URI uri = new URI("jar", zipfile.toUri().toString(), null); FileSystem fs = FileSystems.newFileSystem(uri, env, null); // Test: exercise toUri method - String expected = uri.toString() + "#/foo"; + String expected = uri.toString() + "!/foo"; String actual = fs.getPath("/foo").toUri().toString(); if (!actual.equals(expected)) { throw new RuntimeException("toUri returned '" + actual + diff --git a/test/demo/zipfs/ZipFSTester.java b/test/demo/zipfs/ZipFSTester.java index 76a8d7aeed3f5e6e62f759c02fa26391cc9049b3..8c5a104bac233a30910d122d1f12c1013273608f 100644 --- a/test/demo/zipfs/ZipFSTester.java +++ b/test/demo/zipfs/ZipFSTester.java @@ -58,7 +58,7 @@ public class ZipFSTester { // clone a fs and test on it Path tmpfsPath = getTempPath(); Map env = new HashMap(); - env.put("createNew", true); + env.put("create", "true"); FileSystem fs0 = newZipFileSystem(tmpfsPath, env); z2zcopy(fs, fs0, "/", 0); fs0.close(); // sync to file @@ -147,7 +147,7 @@ public class ZipFSTester { // create a new filesystem, copy everything from fs Map env = new HashMap(); - env.put("createNew", true); + env.put("create", "true"); FileSystem fs0 = newZipFileSystem(fs1Path, env); final FileSystem fs2 = newZipFileSystem(fs2Path, env); @@ -282,11 +282,7 @@ public class ZipFSTester { private static FileSystem newZipFileSystem(Path path, Map env) throws IOException { - return FileSystems.newFileSystem( - URI.create("zip" + - path.toUri().toString().substring(4)), - env, - null); + return FileSystems.newFileSystem(path, env, null); } private static Path getTempPath() throws IOException diff --git a/test/java/awt/Frame/ShapeNotSetSometimes/ShapeNotSetSometimes.java b/test/java/awt/Frame/ShapeNotSetSometimes/ShapeNotSetSometimes.java new file mode 100644 index 0000000000000000000000000000000000000000..751b38e338bb5241e73ad249a8d1c539fd2f3c09 --- /dev/null +++ b/test/java/awt/Frame/ShapeNotSetSometimes/ShapeNotSetSometimes.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 6988428 + @summary Tests whether shape is always set + @author anthony.petrov@oracle.com: area=awt.toplevel + @run main ShapeNotSetSometimes +*/ + + +import java.awt.*; +import java.awt.event.InputEvent; +import java.awt.geom.*; + + +public class ShapeNotSetSometimes { + + private Frame backgroundFrame; + private Frame window; + private static final Color BACKGROUND_COLOR = Color.BLUE; + private Shape shape; + private int[][] pointsToCheck; + + private static Robot robot; + + public ShapeNotSetSometimes() throws Exception { + EventQueue.invokeAndWait(new Runnable() { + public void run() { + initializeGUI(); + } + }); + } + + private void initializeGUI() { + backgroundFrame = new BackgroundFrame(); + backgroundFrame.setUndecorated(true); + backgroundFrame.setSize(300, 300); + backgroundFrame.setLocation(20, 400); + backgroundFrame.setVisible(true); + + shape = null; + String shape_name = null; + Area a; + GeneralPath gp; + shape_name = "Rounded-corners"; + a = new Area(); + a.add(new Area(new Rectangle2D.Float(50, 0, 100, 150))); + a.add(new Area(new Rectangle2D.Float(0, 50, 200, 50))); + a.add(new Area(new Ellipse2D.Float(0, 0, 100, 100))); + a.add(new Area(new Ellipse2D.Float(0, 50, 100, 100))); + a.add(new Area(new Ellipse2D.Float(100, 0, 100, 100))); + a.add(new Area(new Ellipse2D.Float(100, 50, 100, 100))); + shape = a; + pointsToCheck = new int[][] { + // inside shape + {106, 86}, {96, 38}, {76, 107}, {180, 25}, {24, 105}, + {196, 77}, {165, 50}, {14, 113}, {89, 132}, {167, 117}, + // outside shape + {165, 196}, {191, 163}, {146, 185}, {61, 170}, {148, 171}, + {82, 172}, {186, 11}, {199, 141}, {13, 173}, {187, 3} + }; + + window = new TestFrame(); + window.setUndecorated(true); + window.setSize(200, 200); + window.setLocation(70, 450); + window.setShape(shape); + window.setVisible(true); + + System.out.println("Checking " + window.getClass().getSuperclass().getName() + " with " + shape_name + " shape (" + window.getShape() + ")..."); + } + + class BackgroundFrame extends Frame { + + @Override + public void paint(Graphics g) { + + g.setColor(BACKGROUND_COLOR); + g.fillRect(0, 0, 300, 300); + + super.paint(g); + } + } + + class TestFrame extends Frame { + + @Override + public void paint(Graphics g) { + + g.setColor(Color.WHITE); + g.fillRect(0, 0, 200, 200); + + super.paint(g); + } + } + + public static void main(String[] args) throws Exception { + robot = new Robot(); + + for(int i = 0; i < 100; i++) { + System.out.println("Attempt " + i); + new ShapeNotSetSometimes().doTest(); + } + } + + private void doTest() throws Exception { + Point wls = backgroundFrame.getLocationOnScreen(); + + robot.mouseMove(wls.x + 5, wls.y + 5); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.delay(10); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.delay(500); + + EventQueue.invokeAndWait(new Runnable() { + public void run() { + window.requestFocus(); + } + }); + + robot.waitForIdle(); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + // ignore this one + } + + // check transparency + final int COUNT_TARGET = 10; + + // checking outside points only + for(int i = COUNT_TARGET; i < COUNT_TARGET * 2; i++) { + int x = pointsToCheck[i][0]; + int y = pointsToCheck[i][1]; + boolean inside = i < COUNT_TARGET; + Color c = robot.getPixelColor(window.getX() + x, window.getY() + y); + System.out.println("checking " + x + ", " + y + ", color = " + c); + if (inside && BACKGROUND_COLOR.equals(c) || !inside && !BACKGROUND_COLOR.equals(c)) { + System.out.println("window.getX() = " + window.getX() + ", window.getY() = " + window.getY()); + System.err.println("Checking for transparency failed: point: " + + (window.getX() + x) + ", " + (window.getY() + y) + + ", color = " + c + (inside ? " is of un" : " is not of ") + + "expected background color " + BACKGROUND_COLOR); + throw new RuntimeException("Test failed. The shape has not been applied."); + } + } + + EventQueue.invokeAndWait(new Runnable() { + public void run() { + backgroundFrame.dispose(); + window.dispose(); + } + }); + } +} diff --git a/test/java/awt/event/OtherEvents/UngrabID/UngrabID.java b/test/java/awt/event/OtherEvents/UngrabID/UngrabID.java new file mode 100644 index 0000000000000000000000000000000000000000..34a7b7690570f6082ba3d5615c7f393de869e7b8 --- /dev/null +++ b/test/java/awt/event/OtherEvents/UngrabID/UngrabID.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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. + */ + +/* + @test + @bug 6960516 + @summary check if the ungrab event has the ID < AWTEvent.RESERVED_ID_MAX + @author Andrei Dmitriev : area=awt.event + @run main UngrabID +*/ + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; + +public class UngrabID { + public static void main(String[] args){ + Frame f = new Frame("Dummy"); + sun.awt.UngrabEvent event = new sun.awt.UngrabEvent(f); + if (event.getID() > AWTEvent.RESERVED_ID_MAX) { + System.out.println( " Event ID : "+event.getID() + " " + event.toString()); + throw new RuntimeException(" Ungrab Event ID should be less than AWTEvent.RESERVED_ID_MAX ("+AWTEvent.RESERVED_ID_MAX+"). Actual value : "+event.getID() + " Event:" + event.toString()); + } + System.out.println("Test passed. "); + } +} diff --git a/test/java/io/FileInputStream/LargeFileAvailable.java b/test/java/io/FileInputStream/LargeFileAvailable.java new file mode 100644 index 0000000000000000000000000000000000000000..35c9ce47483bc234609a67ae3ba22ea5208b2542 --- /dev/null +++ b/test/java/io/FileInputStream/LargeFileAvailable.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 6402006 + * @summary Test if available returns correct value when reading + * a large file. + */ + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.channels.*; +import static java.nio.file.StandardOpenOption.*; + +public class LargeFileAvailable { + private static final long FILESIZE = 7405576182L; + public static void main(String args[]) throws Exception { + File file = createLargeFile(FILESIZE); + try (FileInputStream fis = new FileInputStream(file)) { + if (file.length() != FILESIZE) { + throw new RuntimeException("unexpected file size = " + file.length()); + } + + long bigSkip = 3110608882L; + long remaining = FILESIZE; + remaining -= skipBytes(fis, bigSkip, remaining); + remaining -= skipBytes(fis, 10L, remaining); + remaining -= skipBytes(fis, bigSkip, remaining); + if (fis.available() != (int) remaining) { + throw new RuntimeException("available() returns " + + fis.available() + + " but expected " + remaining); + } + } finally { + file.delete(); + } + } + + // Skip toSkip number of bytes and expect that the available() method + // returns avail number of bytes. + private static long skipBytes(InputStream is, long toSkip, long avail) + throws IOException { + long skip = is.skip(toSkip); + if (skip != toSkip) { + throw new RuntimeException("skip() returns " + skip + + " but expected " + toSkip); + } + long remaining = avail - skip; + int expected = remaining >= Integer.MAX_VALUE + ? Integer.MAX_VALUE + : (int) remaining; + + System.out.println("Skipped " + skip + " bytes " + + " available() returns " + expected + + " remaining=" + remaining); + if (is.available() != expected) { + throw new RuntimeException("available() returns " + + is.available() + " but expected " + expected); + } + return skip; + } + + private static File createLargeFile(long filesize) throws Exception { + // Create a large file as a sparse file if possible + File largefile = File.createTempFile("largefile", null); + // re-create as a sparse file + largefile.toPath().delete(); + try (FileChannel fc = + FileChannel.open(largefile.toPath(), + CREATE_NEW, WRITE, SPARSE)) { + ByteBuffer bb = ByteBuffer.allocate(1).put((byte)1); + bb.rewind(); + int rc = fc.write(bb, filesize-1); + if (rc != 1) { + throw new RuntimeException("Failed to write 1 byte to the large file"); + } + } + return largefile; + } +} diff --git a/test/java/io/Serializable/cloneArray/CloneArray.java b/test/java/io/Serializable/cloneArray/CloneArray.java new file mode 100644 index 0000000000000000000000000000000000000000..650ac3ccb9f8e7f7e473618fcda6d4e3460df239 --- /dev/null +++ b/test/java/io/Serializable/cloneArray/CloneArray.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 6990094 + * @summary Verify ObjectInputStream.cloneArray works on many kinds of arrays + * @author Stuart Marks, Joseph D. Darcy + */ + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamException; +import java.io.Serializable; + +public class CloneArray { + static Object replacement; + + static class Resolver implements Serializable { + private Object readResolve() throws ObjectStreamException { + return replacement; + } + } + + private static void test(Object rep) + throws IOException, ClassNotFoundException { + + try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + try(ObjectOutputStream oos = new ObjectOutputStream(baos)) { + oos.writeObject(new Resolver()); + oos.writeObject(new Resolver()); + } + + Object o1; + Object o2; + try(ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + ObjectInputStream ois = new ObjectInputStream(bais)) { + replacement = rep; + o1 = ois.readUnshared(); + o2 = ois.readUnshared(); + } + + if (o1 == o2) + throw new AssertionError("o1 and o2 must not be identical"); + } + } + + public static void main(String[] args) + throws IOException, ClassNotFoundException { + Object[] replacements = { + new byte[] {1}, + new char[] {'2'}, + new short[] {3}, + new int[] {4}, + new long[] {5}, + new float[] {6.0f}, + new double[] {7.0}, + new boolean[] {true}, + new Object[] {"A string."} + }; + + for(Object replacement : replacements) { + test(replacement); + } + } +} diff --git a/test/java/nio/channels/AsynchronousSocketChannel/Basic.java b/test/java/nio/channels/AsynchronousSocketChannel/Basic.java index e8f23f46866a4e333b3c68eb771ec3d3b1682591..b38e34efbc052bc83026e99db983014f608b9048 100644 --- a/test/java/nio/channels/AsynchronousSocketChannel/Basic.java +++ b/test/java/nio/channels/AsynchronousSocketChannel/Basic.java @@ -22,7 +22,7 @@ */ /* @test - * @bug 4607272 6842687 + * @bug 4607272 6842687 6878369 * @summary Unit test for AsynchronousSocketChannel * @run main/timeout=600 Basic */ @@ -712,52 +712,57 @@ public class Basic { } static void testTimeout() throws Exception { + System.out.println("-- timeouts --"); + testTimeout(Integer.MIN_VALUE, TimeUnit.SECONDS); + testTimeout(-1L, TimeUnit.SECONDS); + testTimeout(0L, TimeUnit.SECONDS); + testTimeout(2L, TimeUnit.SECONDS); + } + + static void testTimeout(final long timeout, final TimeUnit unit) throws Exception { Server server = new Server(); AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(); ch.connect(server.address()).get(); - System.out.println("-- timeout when reading --"); - ByteBuffer dst = ByteBuffer.allocate(512); final AtomicReference readException = new AtomicReference(); - // this read should timeout - ch.read(dst, 3, TimeUnit.SECONDS, (Void)null, - new CompletionHandler() - { + // this read should timeout if value is > 0 + ch.read(dst, timeout, unit, null, new CompletionHandler() { public void completed(Integer result, Void att) { - throw new RuntimeException("Should not complete"); + readException.set(new RuntimeException("Should not complete")); } public void failed(Throwable exc, Void att) { readException.set(exc); } }); - // wait for exception - while (readException.get() == null) { - Thread.sleep(100); - } - if (!(readException.get() instanceof InterruptedByTimeoutException)) - throw new RuntimeException("InterruptedByTimeoutException expected"); + if (timeout > 0L) { + // wait for exception + while (readException.get() == null) { + Thread.sleep(100); + } + if (!(readException.get() instanceof InterruptedByTimeoutException)) + throw new RuntimeException("InterruptedByTimeoutException expected"); - // after a timeout then further reading should throw unspecified runtime exception - boolean exceptionThrown = false; - try { - ch.read(dst); - } catch (RuntimeException x) { - exceptionThrown = true; + // after a timeout then further reading should throw unspecified runtime exception + boolean exceptionThrown = false; + try { + ch.read(dst); + } catch (RuntimeException x) { + exceptionThrown = true; + } + if (!exceptionThrown) + throw new RuntimeException("RuntimeException expected after timeout."); + } else { + Thread.sleep(1000); + Throwable exc = readException.get(); + if (exc != null) + throw new RuntimeException(exc); } - if (!exceptionThrown) - throw new RuntimeException("RuntimeException expected after timeout."); - - - System.out.println("-- timeout when writing --"); final AtomicReference writeException = new AtomicReference(); - final long timeout = 5; - final TimeUnit unit = TimeUnit.SECONDS; - // write bytes to fill socket buffer ch.write(genBuffer(), timeout, unit, ch, new CompletionHandler() @@ -769,24 +774,32 @@ public class Basic { writeException.set(exc); } }); + if (timeout > 0) { + // wait for exception + while (writeException.get() == null) { + Thread.sleep(100); + } + if (!(writeException.get() instanceof InterruptedByTimeoutException)) + throw new RuntimeException("InterruptedByTimeoutException expected"); - // wait for exception - while (writeException.get() == null) { - Thread.sleep(100); - } - if (!(writeException.get() instanceof InterruptedByTimeoutException)) - throw new RuntimeException("InterruptedByTimeoutException expected"); - - // after a timeout then further writing should throw unspecified runtime exception - exceptionThrown = false; - try { - ch.write(genBuffer()); - } catch (RuntimeException x) { - exceptionThrown = true; + // after a timeout then further writing should throw unspecified runtime exception + boolean exceptionThrown = false; + try { + ch.write(genBuffer()); + } catch (RuntimeException x) { + exceptionThrown = true; + } + if (!exceptionThrown) + throw new RuntimeException("RuntimeException expected after timeout."); + } else { + Thread.sleep(1000); + Throwable exc = writeException.get(); + if (exc != null) + throw new RuntimeException(exc); } - if (!exceptionThrown) - throw new RuntimeException("RuntimeException expected after timeout."); + // clean-up + server.accept().close(); ch.close(); server.close(); } diff --git a/test/java/nio/channels/FileChannel/AtomicAppend.java b/test/java/nio/channels/FileChannel/AtomicAppend.java new file mode 100644 index 0000000000000000000000000000000000000000..1420318d5d7efbf971814ecef816c9f6b5748e85 --- /dev/null +++ b/test/java/nio/channels/FileChannel/AtomicAppend.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 Check that appends are atomic + */ + +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.io.IOException; +import java.util.Random; +import java.util.concurrent.Executors; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import static java.nio.file.StandardOpenOption.*; + +public class AtomicAppend { + static final Random rand = new Random(); + + // Open file for appending, returning FileChannel + static FileChannel newFileChannel(File file) throws IOException { + if (rand.nextBoolean()) { + return new FileOutputStream(file, true).getChannel(); + } else { + return FileChannel.open(file.toPath(), APPEND); + } + } + + // Open file for append, returning OutputStream + static OutputStream newOutputStream(File file) throws IOException { + if (rand.nextBoolean()) { + return new FileOutputStream(file, true); + } else { + return file.toPath().newOutputStream(APPEND); + } + } + + // write a byte to the given channel + static void write(FileChannel fc, int b) throws IOException { + ByteBuffer buf = ByteBuffer.allocate(1); + buf.put((byte)b); + buf.flip(); + if (rand.nextBoolean()) { + ByteBuffer[] bufs = new ByteBuffer[1]; + bufs[0] = buf; + fc.write(bufs); + } else { + fc.write(buf); + } + } + + public static void main(String[] args) throws Throwable { + final int nThreads = 16; + final int writes = 1000; + final File file = File.createTempFile("foo", null); + try { + ExecutorService pool = Executors.newFixedThreadPool(nThreads); + for (int i = 0; i < nThreads; i++) + pool.execute(new Runnable() { public void run() { + try { + // randomly choose FileChannel or OutputStream + if (rand.nextBoolean()) { + try (FileChannel fc = newFileChannel(file)) { + for (int j=0; j newSize) { - if (c.position() != newSize) - throw new RuntimeException("Position greater than size"); - } else { - if (c.position() != position) - throw new RuntimeException("Truncate changed position"); + if (position > newSize) { + if (fc.position() != newSize) + throw new RuntimeException("Position greater than size"); + } else { + if (fc.position() != position) + throw new RuntimeException("Truncate changed position"); + }; } + } + } + + /** + * Test behavior of truncate method when file is opened for append + */ + static void appendTest(File blah) throws Exception { + for (int i=0; i<10; i++) { + long testSize = generator.nextInt(1000) + 10; + initTestFile(blah, testSize); + FileChannel fc = (i < 5) ? + new FileOutputStream(blah, true).getChannel() : + FileChannel.open(blah.toPath(), APPEND); + try (fc) { + // truncate file + long newSize = generator.nextInt((int)testSize); + fc.truncate(newSize); + if (fc.size() != newSize) + throw new RuntimeException("Truncate failed"); - c.close(); - fis.close(); + // write one byte + ByteBuffer buf = ByteBuffer.allocate(1); + buf.put((byte)'x'); + buf.flip(); + fc.write(buf); + if (fc.size() != (newSize+1)) + throw new RuntimeException("Unexpected size"); + } } - blah.delete(); } /** diff --git a/test/java/util/concurrent/BlockingQueue/Interrupt.java b/test/java/util/concurrent/BlockingQueue/Interrupt.java index 418515ded51fa1479fb893bf00f6564fe04ec90f..aafa92c42ed6c1df1b871717a31456feb256cf60 100644 --- a/test/java/util/concurrent/BlockingQueue/Interrupt.java +++ b/test/java/util/concurrent/BlockingQueue/Interrupt.java @@ -136,5 +136,5 @@ public class Interrupt { try {realMain(args);} catch (Throwable t) {unexpected(t);} System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); if (failed > 0) throw new AssertionError("Some tests failed");} - private static abstract class Fun {abstract void f() throws Throwable;} + private abstract static class Fun {abstract void f() throws Throwable;} } diff --git a/test/java/util/concurrent/BlockingQueue/LoopHelpers.java b/test/java/util/concurrent/BlockingQueue/LoopHelpers.java index f6bac816a7babe3f6b058ac3aa74ce76bb1979e2..5bf6d0dbbee5900c0abe3cfa9a55aa6d8313e645 100644 --- a/test/java/util/concurrent/BlockingQueue/LoopHelpers.java +++ b/test/java/util/concurrent/BlockingQueue/LoopHelpers.java @@ -79,9 +79,9 @@ class LoopHelpers { * Basically same as java.util.Random. */ public static class SimpleRandom { - private final static long multiplier = 0x5DEECE66DL; - private final static long addend = 0xBL; - private final static long mask = (1L << 48) - 1; + private static final long multiplier = 0x5DEECE66DL; + private static final long addend = 0xBL; + private static final long mask = (1L << 48) - 1; static final AtomicLong seq = new AtomicLong(1); private long seed = System.nanoTime() + seq.getAndIncrement(); diff --git a/test/java/util/concurrent/ConcurrentHashMap/LoopHelpers.java b/test/java/util/concurrent/ConcurrentHashMap/LoopHelpers.java index f6bac816a7babe3f6b058ac3aa74ce76bb1979e2..5bf6d0dbbee5900c0abe3cfa9a55aa6d8313e645 100644 --- a/test/java/util/concurrent/ConcurrentHashMap/LoopHelpers.java +++ b/test/java/util/concurrent/ConcurrentHashMap/LoopHelpers.java @@ -79,9 +79,9 @@ class LoopHelpers { * Basically same as java.util.Random. */ public static class SimpleRandom { - private final static long multiplier = 0x5DEECE66DL; - private final static long addend = 0xBL; - private final static long mask = (1L << 48) - 1; + private static final long multiplier = 0x5DEECE66DL; + private static final long addend = 0xBL; + private static final long mask = (1L << 48) - 1; static final AtomicLong seq = new AtomicLong(1); private long seed = System.nanoTime() + seq.getAndIncrement(); diff --git a/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java b/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java index e9ca263c91088e424d95d4ef06ae0ba246103c82..c6075c131b94a45119d763def02734e235fa6ad2 100644 --- a/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java +++ b/test/java/util/concurrent/ConcurrentHashMap/MapCheck.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile MapCheck.java + * @compile -source 1.5 MapCheck.java * @run main/timeout=240 MapCheck * @summary Times and checks basic map operations */ @@ -64,7 +64,7 @@ public class MapCheck { if (args.length > 0) { try { mapClass = Class.forName(args[0]); - } catch(ClassNotFoundException e) { + } catch (ClassNotFoundException e) { throw new RuntimeException("Class " + args[0] + " not found."); } } @@ -102,7 +102,7 @@ public class MapCheck { try { Map m = (Map)cl.newInstance(); return m; - } catch(Exception e) { + } catch (Exception e) { throw new RuntimeException("Can't instantiate " + cl + ": " + e); } } @@ -139,7 +139,7 @@ public class MapCheck { } } timer.finish(); - reallyAssert (sum == expect * iters); + reallyAssert(sum == expect * iters); } static void t2(String nm, int n, Map s, Object[] key, int expect) { @@ -149,7 +149,7 @@ public class MapCheck { if (s.remove(key[i]) != null) ++sum; } timer.finish(); - reallyAssert (sum == expect); + reallyAssert(sum == expect); } static void t3(String nm, int n, Map s, Object[] key, int expect) { @@ -159,7 +159,7 @@ public class MapCheck { if (s.put(key[i], absent[i & absentMask]) == null) ++sum; } timer.finish(); - reallyAssert (sum == expect); + reallyAssert(sum == expect); } static void t4(String nm, int n, Map s, Object[] key, int expect) { @@ -169,7 +169,7 @@ public class MapCheck { if (s.containsKey(key[i])) ++sum; } timer.finish(); - reallyAssert (sum == expect); + reallyAssert(sum == expect); } static void t5(String nm, int n, Map s, Object[] key, int expect) { @@ -179,7 +179,7 @@ public class MapCheck { if (s.remove(key[i]) != null) ++sum; } timer.finish(); - reallyAssert (sum == expect); + reallyAssert(sum == expect); } static void t6(String nm, int n, Map s, Object[] k1, Object[] k2) { @@ -190,7 +190,7 @@ public class MapCheck { if (s.get(k2[i & absentMask]) != null) ++sum; } timer.finish(); - reallyAssert (sum == n); + reallyAssert(sum == n); } static void t7(String nm, int n, Map s, Object[] k1, Object[] k2) { @@ -201,7 +201,7 @@ public class MapCheck { if (s.containsKey(k2[i & absentMask])) ++sum; } timer.finish(); - reallyAssert (sum == n); + reallyAssert(sum == n); } static void t8(String nm, int n, Map s, Object[] key, int expect) { @@ -211,7 +211,7 @@ public class MapCheck { if (s.get(key[i]) != null) ++sum; } timer.finish(); - reallyAssert (sum == expect); + reallyAssert(sum == expect); } @@ -223,7 +223,7 @@ public class MapCheck { for (int i = 0; i < absentSize; i += step) if (s.containsValue(absent[i])) ++sum; timer.finish(); - reallyAssert (sum != 0); + reallyAssert(sum != 0); } @@ -235,7 +235,7 @@ public class MapCheck { if (ks.contains(key[i])) ++sum; } timer.finish(); - reallyAssert (sum == size); + reallyAssert(sum == size); } @@ -243,37 +243,37 @@ public class MapCheck { int sum = 0; timer.start("Iter Key ", size); for (Iterator it = s.keySet().iterator(); it.hasNext(); ) { - if(it.next() != MISSING) + if (it.next() != MISSING) ++sum; } timer.finish(); - reallyAssert (sum == size); + reallyAssert(sum == size); } static void ittest2(Map s, int size) { int sum = 0; timer.start("Iter Value ", size); for (Iterator it = s.values().iterator(); it.hasNext(); ) { - if(it.next() != MISSING) + if (it.next() != MISSING) ++sum; } timer.finish(); - reallyAssert (sum == size); + reallyAssert(sum == size); } static void ittest3(Map s, int size) { int sum = 0; timer.start("Iter Entry ", size); for (Iterator it = s.entrySet().iterator(); it.hasNext(); ) { - if(it.next() != MISSING) + if (it.next() != MISSING) ++sum; } timer.finish(); - reallyAssert (sum == size); + reallyAssert(sum == size); } static void ittest4(Map s, int size, int pos) { IdentityHashMap seen = new IdentityHashMap(size); - reallyAssert (s.size() == size); + reallyAssert(s.size() == size); int sum = 0; timer.start("Iter XEntry ", size); Iterator it = s.entrySet().iterator(); @@ -287,9 +287,9 @@ public class MapCheck { if (x != MISSING) ++sum; } - reallyAssert (s.containsKey(k)); + reallyAssert(s.containsKey(k)); it.remove(); - reallyAssert (!s.containsKey(k)); + reallyAssert(!s.containsKey(k)); while (it.hasNext()) { Map.Entry x = (Map.Entry)(it.next()); Object k2 = x.getKey(); @@ -298,12 +298,12 @@ public class MapCheck { ++sum; } - reallyAssert (s.size() == size-1); + reallyAssert(s.size() == size-1); s.put(k, v); - reallyAssert (seen.size() == size); + reallyAssert(seen.size() == size); timer.finish(); - reallyAssert (sum == size); - reallyAssert (s.size() == size); + reallyAssert(sum == size); + reallyAssert(s.size() == size); } @@ -324,7 +324,7 @@ public class MapCheck { ++sum; } timer.finish(); - reallyAssert (sum == size); + reallyAssert(sum == size); } static void entest2(Hashtable ht, int size) { @@ -335,7 +335,7 @@ public class MapCheck { ++sum; } timer.finish(); - reallyAssert (sum == size); + reallyAssert(sum == size); } @@ -349,7 +349,7 @@ public class MapCheck { ++sum; } timer.finish(); - reallyAssert (sum == size); + reallyAssert(sum == size); } static void entest4(Hashtable ht, int size) { @@ -361,7 +361,7 @@ public class MapCheck { ++sum; } timer.finish(); - reallyAssert (sum == size); + reallyAssert(sum == size); } static void entest(Map s, int size) { @@ -409,13 +409,13 @@ public class MapCheck { timer.start("Iter Equals ", size * 2); boolean eqt = s2.equals(s) && s.equals(s2); - reallyAssert (eqt); + reallyAssert(eqt); timer.finish(); timer.start("Iter HashCode ", size * 2); int shc = s.hashCode(); int s2hc = s2.hashCode(); - reallyAssert (shc == s2hc); + reallyAssert(shc == s2hc); timer.finish(); timer.start("Put (present) ", size); @@ -430,7 +430,7 @@ public class MapCheck { if (es2.contains(entry)) ++sum; } timer.finish(); - reallyAssert (sum == size); + reallyAssert(sum == size); t6("Get ", size, s2, key, absent); @@ -438,13 +438,13 @@ public class MapCheck { s2.put(key[size-1], absent[0]); timer.start("Iter Equals ", size * 2); eqt = s2.equals(s) && s.equals(s2); - reallyAssert (!eqt); + reallyAssert(!eqt); timer.finish(); timer.start("Iter HashCode ", size * 2); int s1h = s.hashCode(); int s2h = s2.hashCode(); - reallyAssert (s1h != s2h); + reallyAssert(s1h != s2h); timer.finish(); s2.put(key[size-1], hold); @@ -455,12 +455,12 @@ public class MapCheck { es.remove(s2i.next()); timer.finish(); - reallyAssert (s.isEmpty()); + reallyAssert(s.isEmpty()); timer.start("Clear ", size); s2.clear(); timer.finish(); - reallyAssert (s2.isEmpty() && s.isEmpty()); + reallyAssert(s2.isEmpty() && s.isEmpty()); } static void stest(Map s, int size) throws Exception { @@ -489,7 +489,7 @@ public class MapCheck { System.out.print(time + "ms"); if (s instanceof IdentityHashMap) return; - reallyAssert (s.equals(m)); + reallyAssert(s.equals(m)); } diff --git a/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java b/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java index 5f3d375515e7ecf2321fc1809d7f88f51f0fd8e9..53ed2919a9d82b1ef0580b8730b7cf5565bf10cb 100644 --- a/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java +++ b/test/java/util/concurrent/ConcurrentHashMap/MapLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile MapLoops.java + * @compile -source 1.5 MapLoops.java * @run main/timeout=1600 MapLoops * @summary Exercise multithreaded maps, by default ConcurrentHashMap. * Multithreaded hash table test. Each thread does a random walk @@ -225,7 +225,7 @@ public class MapLoops { barrier.await(); } catch (Throwable throwable) { - synchronized(System.err) { + synchronized (System.err) { System.err.println("--------------------------------"); throwable.printStackTrace(); } diff --git a/test/java/util/concurrent/ConcurrentQueues/LoopHelpers.java b/test/java/util/concurrent/ConcurrentQueues/LoopHelpers.java index f6bac816a7babe3f6b058ac3aa74ce76bb1979e2..5bf6d0dbbee5900c0abe3cfa9a55aa6d8313e645 100644 --- a/test/java/util/concurrent/ConcurrentQueues/LoopHelpers.java +++ b/test/java/util/concurrent/ConcurrentQueues/LoopHelpers.java @@ -79,9 +79,9 @@ class LoopHelpers { * Basically same as java.util.Random. */ public static class SimpleRandom { - private final static long multiplier = 0x5DEECE66DL; - private final static long addend = 0xBL; - private final static long mask = (1L << 48) - 1; + private static final long multiplier = 0x5DEECE66DL; + private static final long addend = 0xBL; + private static final long mask = (1L << 48) - 1; static final AtomicLong seq = new AtomicLong(1); private long seed = System.nanoTime() + seq.getAndIncrement(); diff --git a/test/java/util/concurrent/CopyOnWriteArrayList/EqualsRace.java b/test/java/util/concurrent/CopyOnWriteArrayList/EqualsRace.java index ad063ea237aab85723e093d0fc53955ef1dae4a8..7bc8fab638b6995943ff4390928f82a455706dec 100644 --- a/test/java/util/concurrent/CopyOnWriteArrayList/EqualsRace.java +++ b/test/java/util/concurrent/CopyOnWriteArrayList/EqualsRace.java @@ -66,7 +66,7 @@ public class EqualsRace { try {realMain(args);} catch (Throwable t) {unexpected(t);} System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); if (failed > 0) throw new AssertionError("Some tests failed");} - private static abstract class CheckedThread extends Thread { + private abstract static class CheckedThread extends Thread { public abstract void realRun() throws Throwable; public void run() { try { realRun(); } catch (Throwable t) { unexpected(t); }}} diff --git a/test/java/util/concurrent/CopyOnWriteArraySet/RacingCows.java b/test/java/util/concurrent/CopyOnWriteArraySet/RacingCows.java index afde87549ed374e79abdae14621349b9760152a1..6d13dac3cca70e94efe46ae0912cdab9cceb0668 100644 --- a/test/java/util/concurrent/CopyOnWriteArraySet/RacingCows.java +++ b/test/java/util/concurrent/CopyOnWriteArraySet/RacingCows.java @@ -125,7 +125,7 @@ public class RacingCows { try {realMain(args);} catch (Throwable t) {unexpected(t);} System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); if (failed > 0) throw new AssertionError("Some tests failed");} - private static abstract class CheckedThread extends Thread { + private abstract static class CheckedThread extends Thread { public abstract void realRun() throws Throwable; public void run() { try { realRun(); } catch (Throwable t) { unexpected(t); }}} diff --git a/test/java/util/concurrent/CyclicBarrier/Basic.java b/test/java/util/concurrent/CyclicBarrier/Basic.java index b20a81ea2ffe314defba39e8b0ed7234bb8df86b..f0459d613d531c32bb1853f5779dbe36598efbbd 100644 --- a/test/java/util/concurrent/CyclicBarrier/Basic.java +++ b/test/java/util/concurrent/CyclicBarrier/Basic.java @@ -83,7 +83,7 @@ public class Basic { //---------------------------------------------------------------- // Convenience methods for creating threads that call CyclicBarrier.await //---------------------------------------------------------------- - private static abstract class Awaiter extends Thread { + private abstract static class Awaiter extends Thread { static AtomicInteger count = new AtomicInteger(1); { @@ -417,14 +417,14 @@ public class Basic { try {realMain(args);} catch (Throwable t) {unexpected(t);} System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); if (failed > 0) throw new AssertionError("Some tests failed");} - static abstract class Fun { abstract void f() throws Throwable; } + abstract static class Fun { abstract void f() throws Throwable; } private static void THROWS(Class k, Fun... fs) { for (Fun f : fs) try { f.f(); fail("Expected " + k.getName() + " not thrown"); } catch (Throwable t) { if (k.isAssignableFrom(t.getClass())) pass(); else unexpected(t);}} - private static abstract class CheckedThread extends Thread { + private abstract static class CheckedThread extends Thread { abstract void realRun() throws Throwable; public void run() { try {realRun();} catch (Throwable t) {unexpected(t);}}} diff --git a/test/java/util/concurrent/Exchanger/ExchangeLoops.java b/test/java/util/concurrent/Exchanger/ExchangeLoops.java index b207b8c2d92f494c15ce51fd0c24a21ae3d08707..2055c056ca33215aae45ea7648b7372107484f46 100644 --- a/test/java/util/concurrent/Exchanger/ExchangeLoops.java +++ b/test/java/util/concurrent/Exchanger/ExchangeLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile ExchangeLoops.java + * @compile -source 1.5 ExchangeLoops.java * @run main/timeout=720 ExchangeLoops * @summary checks to make sure a pipeline of exchangers passes data. */ @@ -78,9 +78,9 @@ public class ExchangeLoops { final Exchanger right; final CyclicBarrier barrier; volatile int result; - Stage (Exchanger left, - Exchanger right, - CyclicBarrier b, int iters) { + Stage(Exchanger left, + Exchanger right, + CyclicBarrier b, int iters) { this.left = left; this.right = right; barrier = b; diff --git a/test/java/util/concurrent/Exchanger/LoopHelpers.java b/test/java/util/concurrent/Exchanger/LoopHelpers.java index d3dd5b4a5ef182500f5f8c375c941c01e96bb1a9..6b65b8b2d4aa5b0eec43287030d252a71b89e0cd 100644 --- a/test/java/util/concurrent/Exchanger/LoopHelpers.java +++ b/test/java/util/concurrent/Exchanger/LoopHelpers.java @@ -78,9 +78,9 @@ class LoopHelpers { * Basically same as java.util.Random. */ public static class SimpleRandom { - private final static long multiplier = 0x5DEECE66DL; - private final static long addend = 0xBL; - private final static long mask = (1L << 48) - 1; + private static final long multiplier = 0x5DEECE66DL; + private static final long addend = 0xBL; + private static final long mask = (1L << 48) - 1; static final AtomicLong seq = new AtomicLong(1); private long seed = System.nanoTime() + seq.getAndIncrement(); diff --git a/test/java/util/concurrent/ExecutorCompletionService/ExecutorCompletionServiceLoops.java b/test/java/util/concurrent/ExecutorCompletionService/ExecutorCompletionServiceLoops.java index 2c67ba5697d34270eadb9345d5587b005331f098..71c45e75f7fa3e7a28d804dc5ec8543587e50e4e 100644 --- a/test/java/util/concurrent/ExecutorCompletionService/ExecutorCompletionServiceLoops.java +++ b/test/java/util/concurrent/ExecutorCompletionService/ExecutorCompletionServiceLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4965960 - * @compile ExecutorCompletionServiceLoops.java + * @compile -source 1.5 ExecutorCompletionServiceLoops.java * @run main/timeout=3600 ExecutorCompletionServiceLoops * @summary Exercise ExecutorCompletionServiceLoops */ diff --git a/test/java/util/concurrent/ExecutorCompletionService/LoopHelpers.java b/test/java/util/concurrent/ExecutorCompletionService/LoopHelpers.java index d3dd5b4a5ef182500f5f8c375c941c01e96bb1a9..6b65b8b2d4aa5b0eec43287030d252a71b89e0cd 100644 --- a/test/java/util/concurrent/ExecutorCompletionService/LoopHelpers.java +++ b/test/java/util/concurrent/ExecutorCompletionService/LoopHelpers.java @@ -78,9 +78,9 @@ class LoopHelpers { * Basically same as java.util.Random. */ public static class SimpleRandom { - private final static long multiplier = 0x5DEECE66DL; - private final static long addend = 0xBL; - private final static long mask = (1L << 48) - 1; + private static final long multiplier = 0x5DEECE66DL; + private static final long addend = 0xBL; + private static final long mask = (1L << 48) - 1; static final AtomicLong seq = new AtomicLong(1); private long seed = System.nanoTime() + seq.getAndIncrement(); diff --git a/test/java/util/concurrent/Executors/Throws.java b/test/java/util/concurrent/Executors/Throws.java index c310ad5c9ec801884e592d54c39b2b23bc66bc72..d98537931ee39f2139deb39cd2ea91681d29df08 100644 --- a/test/java/util/concurrent/Executors/Throws.java +++ b/test/java/util/concurrent/Executors/Throws.java @@ -122,7 +122,7 @@ public class Throws { try {realMain(args);} catch (Throwable t) {unexpected(t);} System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); if (failed > 0) throw new AssertionError("Some tests failed");} - private static abstract class Fun {abstract void f() throws Throwable;} + private abstract static class Fun {abstract void f() throws Throwable;} static void THROWS(Class k, Fun... fs) { for (Fun f : fs) try { f.f(); fail("Expected " + k.getName() + " not thrown"); } diff --git a/test/java/util/concurrent/FutureTask/BlockingTaskExecutor.java b/test/java/util/concurrent/FutureTask/BlockingTaskExecutor.java index bd6c2e839da52eac2987c2d9d85d2f0c1e6042c8..4c6f12ba29d44486b50791b5fcb0b4a71ff79d76 100644 --- a/test/java/util/concurrent/FutureTask/BlockingTaskExecutor.java +++ b/test/java/util/concurrent/FutureTask/BlockingTaskExecutor.java @@ -87,7 +87,7 @@ public class BlockingTaskExecutor { * A helper class with a method to wait for a notification. * * The notification is received via the - * sendNotification method. + * {@code sendNotification} method. */ static class NotificationReceiver { /** Has the notifiee been notified? */ diff --git a/test/java/util/concurrent/FutureTask/CancelledFutureLoops.java b/test/java/util/concurrent/FutureTask/CancelledFutureLoops.java index c12f5cde94463d5ffc6e097b7c318e4658a6a3d1..6a0ca8c93df8c466dd66cce3fd4255ffa43e46fe 100644 --- a/test/java/util/concurrent/FutureTask/CancelledFutureLoops.java +++ b/test/java/util/concurrent/FutureTask/CancelledFutureLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile CancelledFutureLoops.java + * @compile -source 1.5 CancelledFutureLoops.java * @run main/timeout=2000 CancelledFutureLoops * @summary Checks for responsiveness of futures to cancellation. * Runs under the assumption that ITERS computations require more than @@ -64,10 +64,10 @@ public final class CancelledFutureLoops { try { new FutureLoop(i).test(); } - catch(BrokenBarrierException bb) { + catch (BrokenBarrierException bb) { // OK; ignore } - catch(ExecutionException ee) { + catch (ExecutionException ee) { // OK; ignore } Thread.sleep(TIMEOUT); diff --git a/test/java/util/concurrent/FutureTask/Customized.java b/test/java/util/concurrent/FutureTask/Customized.java index 1f1f8fb49391aa81922d203a7379c17ddc753951..5d107c58ad1ec473c83cb6b2b790b289c650ab2e 100644 --- a/test/java/util/concurrent/FutureTask/Customized.java +++ b/test/java/util/concurrent/FutureTask/Customized.java @@ -203,7 +203,7 @@ public class Customized { try {realMain(args);} catch (Throwable t) {unexpected(t);} System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); if (failed > 0) throw new AssertionError("Some tests failed");} - private static abstract class Fun {abstract void f() throws Throwable;} + private abstract static class Fun {abstract void f() throws Throwable;} static void THROWS(Class k, Fun... fs) { for (Fun f : fs) try { f.f(); fail("Expected " + k.getName() + " not thrown"); } diff --git a/test/java/util/concurrent/FutureTask/LoopHelpers.java b/test/java/util/concurrent/FutureTask/LoopHelpers.java index d3dd5b4a5ef182500f5f8c375c941c01e96bb1a9..6b65b8b2d4aa5b0eec43287030d252a71b89e0cd 100644 --- a/test/java/util/concurrent/FutureTask/LoopHelpers.java +++ b/test/java/util/concurrent/FutureTask/LoopHelpers.java @@ -78,9 +78,9 @@ class LoopHelpers { * Basically same as java.util.Random. */ public static class SimpleRandom { - private final static long multiplier = 0x5DEECE66DL; - private final static long addend = 0xBL; - private final static long mask = (1L << 48) - 1; + private static final long multiplier = 0x5DEECE66DL; + private static final long addend = 0xBL; + private static final long mask = (1L << 48) - 1; static final AtomicLong seq = new AtomicLong(1); private long seed = System.nanoTime() + seq.getAndIncrement(); diff --git a/test/java/util/concurrent/ScheduledThreadPoolExecutor/DelayOverflow.java b/test/java/util/concurrent/ScheduledThreadPoolExecutor/DelayOverflow.java index 2e0854b0fc7c21618fc87b8e1a115c71ae05abfc..bc34d00965fc0a7a5bd89b4add0617f15c60be35 100644 --- a/test/java/util/concurrent/ScheduledThreadPoolExecutor/DelayOverflow.java +++ b/test/java/util/concurrent/ScheduledThreadPoolExecutor/DelayOverflow.java @@ -161,11 +161,8 @@ public class DelayOverflow { if (x == null ? y == null : x.equals(y)) pass(); else fail(x + " not equal to " + y);} public static void main(String[] args) throws Throwable { - Class k = new Object(){}.getClass().getEnclosingClass(); - try {k.getMethod("instanceMain",String[].class) - .invoke( k.newInstance(), (Object) args);} - catch (Throwable e) {throw e.getCause();}} - public void instanceMain(String[] args) throws Throwable { + new DelayOverflow().instanceMain(args);} + void instanceMain(String[] args) throws Throwable { try {test(args);} catch (Throwable t) {unexpected(t);} System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); if (failed > 0) throw new AssertionError("Some tests failed");} diff --git a/test/java/util/concurrent/ThreadPoolExecutor/ConfigChanges.java b/test/java/util/concurrent/ThreadPoolExecutor/ConfigChanges.java index 40d11e04b311b42619226b3f1157be6839b59540..4c69a594bcbad6670146287bc62a125ff41324b2 100644 --- a/test/java/util/concurrent/ThreadPoolExecutor/ConfigChanges.java +++ b/test/java/util/concurrent/ThreadPoolExecutor/ConfigChanges.java @@ -36,9 +36,9 @@ import java.util.concurrent.atomic.*; import static java.util.concurrent.TimeUnit.*; public class ConfigChanges { - final static ThreadGroup tg = new ThreadGroup("pool"); + static final ThreadGroup tg = new ThreadGroup("pool"); - final static Random rnd = new Random(); + static final Random rnd = new Random(); static void report(ThreadPoolExecutor tpe) { try { @@ -241,7 +241,7 @@ public class ConfigChanges { try {realMain(args);} catch (Throwable t) {unexpected(t);} System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); if (failed > 0) throw new AssertionError("Some tests failed");} - private static abstract class Fun {abstract void f() throws Throwable;} + private abstract static class Fun {abstract void f() throws Throwable;} static void THROWS(Class k, Fun... fs) { for (Fun f : fs) try { f.f(); fail("Expected " + k.getName() + " not thrown"); } diff --git a/test/java/util/concurrent/ThreadPoolExecutor/Custom.java b/test/java/util/concurrent/ThreadPoolExecutor/Custom.java index 108ca7bd4fc6ce100bf4e712dddf267e86e514c7..d60bdcefdea872d9c4e829464c54e4f29a72f25a 100644 --- a/test/java/util/concurrent/ThreadPoolExecutor/Custom.java +++ b/test/java/util/concurrent/ThreadPoolExecutor/Custom.java @@ -43,7 +43,7 @@ public class Custom { private static class CustomTask extends FutureTask { - public final static AtomicInteger births = new AtomicInteger(0); + public static final AtomicInteger births = new AtomicInteger(0); CustomTask(Callable c) { super(c); births.getAndIncrement(); } CustomTask(Runnable r, V v) { super(r, v); births.getAndIncrement(); } } @@ -63,7 +63,7 @@ public class Custom { } private static class CustomSTPE extends ScheduledThreadPoolExecutor { - public final static AtomicInteger decorations = new AtomicInteger(0); + public static final AtomicInteger decorations = new AtomicInteger(0); CustomSTPE() { super(threadCount); } @@ -89,7 +89,7 @@ public class Custom { return count; } - private final static int threadCount = 10; + private static final int threadCount = 10; public static void main(String[] args) throws Throwable { CustomTPE tpe = new CustomTPE(); diff --git a/test/java/util/concurrent/ThreadPoolExecutor/ScheduledTickleService.java b/test/java/util/concurrent/ThreadPoolExecutor/ScheduledTickleService.java index 94c71e72605af2a110f4f7423d470d56a98e4cfd..a0c3b53d5e14fcb0f88cecf4b85e08d9b691fa4c 100644 --- a/test/java/util/concurrent/ThreadPoolExecutor/ScheduledTickleService.java +++ b/test/java/util/concurrent/ThreadPoolExecutor/ScheduledTickleService.java @@ -37,10 +37,10 @@ public class ScheduledTickleService { // We get intermittent ClassCastException if greater than 1 // because of calls to compareTo - private final static int concurrency = 2; + private static final int concurrency = 2; // Record when tasks are done - public final static CountDownLatch done = new CountDownLatch(concurrency); + public static final CountDownLatch done = new CountDownLatch(concurrency); public static void realMain(String... args) throws InterruptedException { // our tickle service diff --git a/test/java/util/concurrent/ThreadPoolExecutor/ShutdownNowExecuteRace.java b/test/java/util/concurrent/ThreadPoolExecutor/ShutdownNowExecuteRace.java index b2a8313893cf8ec08ee9e4ef1b332369f25814f7..04b08ef6f379749774cede4c88164a4811d7039c 100644 --- a/test/java/util/concurrent/ThreadPoolExecutor/ShutdownNowExecuteRace.java +++ b/test/java/util/concurrent/ThreadPoolExecutor/ShutdownNowExecuteRace.java @@ -40,7 +40,7 @@ public class ShutdownNowExecuteRace { static volatile boolean quit = false; static volatile ThreadPoolExecutor pool = null; - final static Runnable sleeper = new Runnable() { public void run() { + static final Runnable sleeper = new Runnable() { public void run() { final long ONE_HOUR = 1000L * 60L * 60L; try { Thread.sleep(ONE_HOUR); } catch (InterruptedException ie) {} @@ -81,14 +81,14 @@ public class ShutdownNowExecuteRace { try {realMain(args);} catch (Throwable t) {unexpected(t);} System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); if (failed > 0) throw new AssertionError("Some tests failed");} - private static abstract class Fun {abstract void f() throws Throwable;} + private abstract static class Fun {abstract void f() throws Throwable;} static void THROWS(Class k, Fun... fs) { for (Fun f : fs) try { f.f(); fail("Expected " + k.getName() + " not thrown"); } catch (Throwable t) { if (k.isAssignableFrom(t.getClass())) pass(); else unexpected(t);}} - private static abstract class CheckedThread extends Thread { + private abstract static class CheckedThread extends Thread { abstract void realRun() throws Throwable; public void run() { try {realRun();} catch (Throwable t) {unexpected(t);}}} diff --git a/test/java/util/concurrent/ThreadPoolExecutor/ThrowingTasks.java b/test/java/util/concurrent/ThreadPoolExecutor/ThrowingTasks.java index 6ff46c95c6bf0f3bf9c0248bb405e82bc160f033..534bf59f52ef9613584f4070a4c42d76bdc3d065 100644 --- a/test/java/util/concurrent/ThreadPoolExecutor/ThrowingTasks.java +++ b/test/java/util/concurrent/ThreadPoolExecutor/ThrowingTasks.java @@ -35,7 +35,7 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.*; public class ThrowingTasks { - final static Random rnd = new Random(); + static final Random rnd = new Random(); @SuppressWarnings("serial") static class UncaughtExceptions @@ -65,16 +65,16 @@ public class ThrowingTasks { } } - final static UncaughtExceptions uncaughtExceptions + static final UncaughtExceptions uncaughtExceptions = new UncaughtExceptions(); - final static UncaughtExceptionsTable uncaughtExceptionsTable + static final UncaughtExceptionsTable uncaughtExceptionsTable = new UncaughtExceptionsTable(); - final static AtomicLong totalUncaughtExceptions + static final AtomicLong totalUncaughtExceptions = new AtomicLong(0); - final static CountDownLatch uncaughtExceptionsLatch + static final CountDownLatch uncaughtExceptionsLatch = new CountDownLatch(24); - final static Thread.UncaughtExceptionHandler handler + static final Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { check(! Thread.currentThread().isInterrupted()); @@ -84,19 +84,19 @@ public class ThrowingTasks { uncaughtExceptionsLatch.countDown(); }}; - final static ThreadGroup tg = new ThreadGroup("Flaky"); + static final ThreadGroup tg = new ThreadGroup("Flaky"); - final static ThreadFactory tf = new ThreadFactory() { + static final ThreadFactory tf = new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(tg, r); t.setUncaughtExceptionHandler(handler); return t; }}; - final static RuntimeException rte = new RuntimeException(); - final static Error error = new Error(); - final static Throwable weird = new Throwable(); - final static Exception checkedException = new Exception(); + static final RuntimeException rte = new RuntimeException(); + static final Error error = new Error(); + static final Throwable weird = new Throwable(); + static final Exception checkedException = new Exception(); static class Thrower implements Runnable { Throwable t; @@ -105,13 +105,13 @@ public class ThrowingTasks { public void run() { if (t != null) Thread.currentThread().stop(t); } } - final static Thrower noThrower = new Thrower(null); - final static Thrower rteThrower = new Thrower(rte); - final static Thrower errorThrower = new Thrower(error); - final static Thrower weirdThrower = new Thrower(weird); - final static Thrower checkedThrower = new Thrower(checkedException); + static final Thrower noThrower = new Thrower(null); + static final Thrower rteThrower = new Thrower(rte); + static final Thrower errorThrower = new Thrower(error); + static final Thrower weirdThrower = new Thrower(weird); + static final Thrower checkedThrower = new Thrower(checkedException); - final static List throwers = Arrays.asList( + static final List throwers = Arrays.asList( noThrower, rteThrower, errorThrower, weirdThrower, checkedThrower); static class Flaky implements Runnable { diff --git a/test/java/util/concurrent/atomic/VMSupportsCS8.java b/test/java/util/concurrent/atomic/VMSupportsCS8.java index 09c648c3fca35ef96abdb92a0a839504aabf423b..72ad18a9a3060599ae69b3564354aade09bee3c6 100644 --- a/test/java/util/concurrent/atomic/VMSupportsCS8.java +++ b/test/java/util/concurrent/atomic/VMSupportsCS8.java @@ -24,6 +24,8 @@ /* * @test * @bug 4992443 4994819 + * @compile -source 1.5 VMSupportsCS8.java + * @run main VMSupportsCS8 * @summary Checks that the value of VMSupportsCS8 matches system properties. */ diff --git a/test/java/util/concurrent/locks/Lock/FlakyMutex.java b/test/java/util/concurrent/locks/Lock/FlakyMutex.java index 5d4fc70460d6e59ac212c8a7ca600ebb6c1c905f..acee4b9826098ac05fb46bf615cd0d2e17690455 100644 --- a/test/java/util/concurrent/locks/Lock/FlakyMutex.java +++ b/test/java/util/concurrent/locks/Lock/FlakyMutex.java @@ -75,10 +75,10 @@ public class FlakyMutex implements Lock { catch (Throwable t) { checkThrowable(t); } } - try { check (! m.tryLock()); } + try { check(! m.tryLock()); } catch (Throwable t) { checkThrowable(t); } - try { check (! m.tryLock(1, TimeUnit.MICROSECONDS)); } + try { check(! m.tryLock(1, TimeUnit.MICROSECONDS)); } catch (Throwable t) { checkThrowable(t); } m.unlock(); diff --git a/test/java/util/concurrent/locks/Lock/TimedAcquireLeak.java b/test/java/util/concurrent/locks/Lock/TimedAcquireLeak.java index 5fd884ad33c7652070e2ee132cd0ce9804d9275f..4f00f19abfd96b19c8a8cc02fec6c66b06c11f9c 100644 --- a/test/java/util/concurrent/locks/Lock/TimedAcquireLeak.java +++ b/test/java/util/concurrent/locks/Lock/TimedAcquireLeak.java @@ -64,7 +64,7 @@ public class TimedAcquireLeak { return outputOf(new InputStreamReader(is, "UTF-8")); } - final static ExecutorService drainers = Executors.newFixedThreadPool(12); + static final ExecutorService drainers = Executors.newFixedThreadPool(12); static Future futureOutputOf(final InputStream is) { return drainers.submit( new Callable() { public String call() throws IOException { diff --git a/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java b/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java index fc769df409294cf59bc27c1f39db6208989b821f..3f7667c247a15c69964fb97f8b17638296383292 100644 --- a/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java +++ b/test/java/util/concurrent/locks/ReentrantLock/CancelledLockLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile CancelledLockLoops.java + * @compile -source 1.5 CancelledLockLoops.java * @run main/timeout=2800 CancelledLockLoops * @summary tests lockInterruptibly. * Checks for responsiveness of locks to interrupts. Runs under that @@ -64,7 +64,7 @@ public final class CancelledLockLoops { try { new ReentrantLockLoop(i).test(); } - catch(BrokenBarrierException bb) { + catch (BrokenBarrierException bb) { // OK, ignore } Thread.sleep(TIMEOUT); diff --git a/test/java/util/concurrent/locks/ReentrantLock/LockOncePerThreadLoops.java b/test/java/util/concurrent/locks/ReentrantLock/LockOncePerThreadLoops.java index 88b2f2d00b14f31078110773bbb4a796c4accb98..8682e24dbab8b8af2c4cb1236f17af3e8b10763a 100644 --- a/test/java/util/concurrent/locks/ReentrantLock/LockOncePerThreadLoops.java +++ b/test/java/util/concurrent/locks/ReentrantLock/LockOncePerThreadLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile LockOncePerThreadLoops.java + * @compile -source 1.5 LockOncePerThreadLoops.java * @run main/timeout=15000 LockOncePerThreadLoops * @summary Checks for missed signals by locking and unlocking each of an array of locks once per thread */ diff --git a/test/java/util/concurrent/locks/ReentrantLock/LoopHelpers.java b/test/java/util/concurrent/locks/ReentrantLock/LoopHelpers.java index d3dd5b4a5ef182500f5f8c375c941c01e96bb1a9..6b65b8b2d4aa5b0eec43287030d252a71b89e0cd 100644 --- a/test/java/util/concurrent/locks/ReentrantLock/LoopHelpers.java +++ b/test/java/util/concurrent/locks/ReentrantLock/LoopHelpers.java @@ -78,9 +78,9 @@ class LoopHelpers { * Basically same as java.util.Random. */ public static class SimpleRandom { - private final static long multiplier = 0x5DEECE66DL; - private final static long addend = 0xBL; - private final static long mask = (1L << 48) - 1; + private static final long multiplier = 0x5DEECE66DL; + private static final long addend = 0xBL; + private static final long mask = (1L << 48) - 1; static final AtomicLong seq = new AtomicLong(1); private long seed = System.nanoTime() + seq.getAndIncrement(); diff --git a/test/java/util/concurrent/locks/ReentrantLock/SimpleReentrantLockLoops.java b/test/java/util/concurrent/locks/ReentrantLock/SimpleReentrantLockLoops.java index ac85bba4c3f646393973713c5036fb0ee6b49cbd..db7d5af61dc1ab205ac4c8cff69c0af15a23022a 100644 --- a/test/java/util/concurrent/locks/ReentrantLock/SimpleReentrantLockLoops.java +++ b/test/java/util/concurrent/locks/ReentrantLock/SimpleReentrantLockLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile SimpleReentrantLockLoops.java + * @compile -source 1.5 SimpleReentrantLockLoops.java * @run main/timeout=4500 SimpleReentrantLockLoops * @summary multiple threads using a single lock */ diff --git a/test/java/util/concurrent/locks/ReentrantLock/TimeoutLockLoops.java b/test/java/util/concurrent/locks/ReentrantLock/TimeoutLockLoops.java index 0a90bebc352fb264738efff6983ba40b0938593f..3c20867531a976a8cacde8747b1ca34b9ec1ae96 100644 --- a/test/java/util/concurrent/locks/ReentrantLock/TimeoutLockLoops.java +++ b/test/java/util/concurrent/locks/ReentrantLock/TimeoutLockLoops.java @@ -34,6 +34,8 @@ /* * @test * @bug 4486658 5031862 + * @compile -source 1.5 TimeoutLockLoops.java + * @run main TimeoutLockLoops * @summary Checks for responsiveness of locks to timeouts. * Runs under the assumption that ITERS computations require more than * TIMEOUT msecs to complete, which seems to be a safe assumption for diff --git a/test/java/util/concurrent/locks/ReentrantReadWriteLock/Bug6571733.java b/test/java/util/concurrent/locks/ReentrantReadWriteLock/Bug6571733.java index c63e7a30c77371ea97820c28f1516d6cad815c40..0a65d352a90846bdcfb4e6088af636dafe48f599 100644 --- a/test/java/util/concurrent/locks/ReentrantReadWriteLock/Bug6571733.java +++ b/test/java/util/concurrent/locks/ReentrantReadWriteLock/Bug6571733.java @@ -45,7 +45,7 @@ public class Bug6571733 { Thread thread = new Thread() { public void run() { try { - check (! lock.writeLock().tryLock(0, TimeUnit.DAYS)); + check(! lock.writeLock().tryLock(0, TimeUnit.DAYS)); lock.readLock().lock(); lock.readLock().unlock(); diff --git a/test/java/util/concurrent/locks/ReentrantReadWriteLock/LoopHelpers.java b/test/java/util/concurrent/locks/ReentrantReadWriteLock/LoopHelpers.java index d3dd5b4a5ef182500f5f8c375c941c01e96bb1a9..6b65b8b2d4aa5b0eec43287030d252a71b89e0cd 100644 --- a/test/java/util/concurrent/locks/ReentrantReadWriteLock/LoopHelpers.java +++ b/test/java/util/concurrent/locks/ReentrantReadWriteLock/LoopHelpers.java @@ -78,9 +78,9 @@ class LoopHelpers { * Basically same as java.util.Random. */ public static class SimpleRandom { - private final static long multiplier = 0x5DEECE66DL; - private final static long addend = 0xBL; - private final static long mask = (1L << 48) - 1; + private static final long multiplier = 0x5DEECE66DL; + private static final long addend = 0xBL; + private static final long mask = (1L << 48) - 1; static final AtomicLong seq = new AtomicLong(1); private long seed = System.nanoTime() + seq.getAndIncrement(); diff --git a/test/java/util/concurrent/locks/ReentrantReadWriteLock/MapLoops.java b/test/java/util/concurrent/locks/ReentrantReadWriteLock/MapLoops.java index ce6651fbb2df6035e35e3d19662292f61512fe71..a8e47e5a25edf9dfeca3ca70c169c6223931c289 100644 --- a/test/java/util/concurrent/locks/ReentrantReadWriteLock/MapLoops.java +++ b/test/java/util/concurrent/locks/ReentrantReadWriteLock/MapLoops.java @@ -34,7 +34,7 @@ /* * @test * @bug 4486658 - * @compile MapLoops.java + * @compile -source 1.5 MapLoops.java * @run main/timeout=4700 MapLoops * @summary Exercise multithreaded maps, by default ConcurrentHashMap. * Multithreaded hash table test. Each thread does a random walk @@ -65,7 +65,7 @@ public class MapLoops { if (args.length > 0) { try { mapClass = Class.forName(args[0]); - } catch(ClassNotFoundException e) { + } catch (ClassNotFoundException e) { throw new RuntimeException("Class " + args[0] + " not found."); } } diff --git a/test/java/util/concurrent/locks/ReentrantReadWriteLock/RWMap.java b/test/java/util/concurrent/locks/ReentrantReadWriteLock/RWMap.java index 8c5121e536a2921856a5fb878b28a7ab0062b2d8..53f63d6e33c01dca54eec675ddc62a5ff86e6749 100644 --- a/test/java/util/concurrent/locks/ReentrantReadWriteLock/RWMap.java +++ b/test/java/util/concurrent/locks/ReentrantReadWriteLock/RWMap.java @@ -57,21 +57,33 @@ public class RWMap implements Map { } public int size() { - rwl.readLock().lock(); try {return m.size();} finally { rwl.readLock().unlock(); } + rwl.readLock().lock(); + try { return m.size(); } + finally { rwl.readLock().unlock(); } } - public boolean isEmpty(){ - rwl.readLock().lock(); try {return m.isEmpty();} finally { rwl.readLock().unlock(); } + + public boolean isEmpty() { + rwl.readLock().lock(); + try { return m.isEmpty(); } + finally { rwl.readLock().unlock(); } } public Object get(Object key) { - rwl.readLock().lock(); try {return m.get(key);} finally { rwl.readLock().unlock(); } + rwl.readLock().lock(); + try { return m.get(key); } + finally { rwl.readLock().unlock(); } } public boolean containsKey(Object key) { - rwl.readLock().lock(); try {return m.containsKey(key);} finally { rwl.readLock().unlock(); } + rwl.readLock().lock(); + try { return m.containsKey(key); } + finally { rwl.readLock().unlock(); } } - public boolean containsValue(Object value){ - rwl.readLock().lock(); try {return m.containsValue(value);} finally { rwl.readLock().unlock(); } + + public boolean containsValue(Object value) { + rwl.readLock().lock(); + try { return m.containsValue(value); } + finally { rwl.readLock().unlock(); } } @@ -88,28 +100,45 @@ public class RWMap implements Map { } public boolean equals(Object o) { - rwl.readLock().lock(); try {return m.equals(o);} finally { rwl.readLock().unlock(); } + rwl.readLock().lock(); + try { return m.equals(o); } + finally { rwl.readLock().unlock(); } } + public int hashCode() { - rwl.readLock().lock(); try {return m.hashCode();} finally { rwl.readLock().unlock(); } + rwl.readLock().lock(); + try { return m.hashCode(); } + finally { rwl.readLock().unlock(); } } + public String toString() { - rwl.readLock().lock(); try {return m.toString();} finally { rwl.readLock().unlock(); } + rwl.readLock().lock(); + try { return m.toString(); } + finally { rwl.readLock().unlock(); } } - - public Object put(Object key, Object value) { - rwl.writeLock().lock(); try {return m.put(key, value);} finally { rwl.writeLock().unlock(); } + rwl.writeLock().lock(); + try { return m.put(key, value); } + finally { rwl.writeLock().unlock(); } } + public Object remove(Object key) { - rwl.writeLock().lock(); try {return m.remove(key);} finally { rwl.writeLock().unlock(); } + rwl.writeLock().lock(); + try { return m.remove(key); } + finally { rwl.writeLock().unlock(); } } + public void putAll(Map map) { - rwl.writeLock().lock(); try {m.putAll(map);} finally { rwl.writeLock().unlock(); } + rwl.writeLock().lock(); + try { m.putAll(map); } + finally { rwl.writeLock().unlock(); } } + public void clear() { - rwl.writeLock().lock(); try {m.clear();} finally { rwl.writeLock().unlock(); } + rwl.writeLock().lock(); + try { m.clear(); } + finally { rwl.writeLock().unlock(); } } } diff --git a/test/javax/swing/GroupLayout/6613904/bug6613904.java b/test/javax/swing/GroupLayout/6613904/bug6613904.java new file mode 100644 index 0000000000000000000000000000000000000000..0f0626e66c926d7cfe17e5cee5545c955d7b35dc --- /dev/null +++ b/test/javax/swing/GroupLayout/6613904/bug6613904.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 6613904 + * @summary javax.swing.GroupLayout.createParallelGroup(..) doesn't throw IllegalArgumentException for null arg + * @author Pavel Porvatov + */ + +import javax.swing.*; + +public class bug6613904 { + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + GroupLayout groupLayout = new GroupLayout(new JPanel()); + + try { + groupLayout.createParallelGroup(null); + + throw new RuntimeException("groupLayout.createParallelGroup(null) doesn't throw IAE"); + } catch (IllegalArgumentException e) { + // Ok + } + + try { + groupLayout.createParallelGroup(null, true); + + throw new RuntimeException("groupLayout.createParallelGroup(null, true) doesn't throw IAE"); + } catch (IllegalArgumentException e) { + // Ok + } + + try { + groupLayout.createParallelGroup(null, false); + + throw new RuntimeException("groupLayout.createParallelGroup(null, false) doesn't throw IAE"); + } catch (IllegalArgumentException e) { + // Ok + } + } + }); + } +} diff --git a/test/javax/swing/JPopupMenu/6987844/bug6987844.java b/test/javax/swing/JPopupMenu/6987844/bug6987844.java new file mode 100644 index 0000000000000000000000000000000000000000..d8802351bcbff4b9b1700fe79c4dcc179daa9ab5 --- /dev/null +++ b/test/javax/swing/JPopupMenu/6987844/bug6987844.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 6987844 + * @summary Incorrect width of JComboBox drop down + * @author Alexander Potochkin + * @run main bug6987844 + */ + +import sun.awt.SunToolkit; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.InputEvent; + +public class bug6987844 { + static JMenu menu1; + static JMenu menu2; + + public static void main(String... args) throws Exception { + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + Robot robot = new Robot(); + robot.setAutoDelay(200); + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + JFrame frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JMenuBar bar = new JMenuBar(); + menu1 = new JMenu("Menu1"); + menu1.add(new JMenuItem("item")); + bar.add(menu1); + menu2 = new JMenu("Menu2"); + menu2.add(new JMenuItem("item")); + menu2.add(new JMenuItem("item")); + bar.add(menu2); + + frame.setJMenuBar(bar); + frame.pack(); + + frame.setVisible(true); + } + }); + toolkit.realSync(); + Point point1 = menu1.getLocationOnScreen(); + Point point2 = menu2.getLocationOnScreen(); + + robot.mouseMove(point1.x + 1, point1.y + 1); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + robot.mouseMove(point2.x + 1, point2.y + 1); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + robot.mouseMove(point1.x + 1, point1.y + 1); + toolkit.realSync(); + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + Dimension popupSize1 = menu1.getPopupMenu().getSize(); + Dimension popupSize2 = menu2.getPopupMenu().getSize(); + if (popupSize1.equals(popupSize2)) { + throw new RuntimeException("First popup unexpedetly changed its size"); + } + } + }); + } +} diff --git a/test/javax/swing/text/DefaultHighlighter/6771184/bug6771184.java b/test/javax/swing/text/DefaultHighlighter/6771184/bug6771184.java new file mode 100644 index 0000000000000000000000000000000000000000..d63e8da0e61c204c011a94bac7a59a0bb35880bb --- /dev/null +++ b/test/javax/swing/text/DefaultHighlighter/6771184/bug6771184.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 6771184 + * @summary Some methods in text package don't throw BadLocationException when expected + * @author Pavel Porvatov + */ + +import javax.swing.*; +import javax.swing.text.BadLocationException; +import javax.swing.text.Highlighter; +import javax.swing.text.JTextComponent; +import java.awt.*; + +public class bug6771184 { + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + JTextArea textArea = new JTextArea("Tested string"); + + Highlighter highlighter = textArea.getHighlighter(); + Highlighter.HighlightPainter myPainter = new Highlighter.HighlightPainter() { + public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) { + } + }; + + int negativeTestedData[][] = {{50, 0}, + {-1, 1}, + {-5, -4}, + {Integer.MAX_VALUE, Integer.MIN_VALUE}, + {Integer.MIN_VALUE, Integer.MAX_VALUE}, + {Integer.MIN_VALUE, Integer.MIN_VALUE}}; + + for (int[] data : negativeTestedData) { + try { + highlighter.addHighlight(data[0], data[1], myPainter); + + throw new RuntimeException("Method addHighlight() does not throw BadLocationException for (" + + data[0] + ", " + data[1] + ") "); + } catch (BadLocationException e) { + // Ok + } + + Object objRef; + + try { + objRef = highlighter.addHighlight(0, 1, myPainter); + } catch (BadLocationException e) { + throw new RuntimeException("highlighter.addHighlight(0, 1, myPainter) throws exception", e); + } + + try { + highlighter.changeHighlight(objRef, data[0], data[1]); + + throw new RuntimeException("Method changeHighlight() does not throw BadLocationException for (" + + data[0] + ", " + data[1] + ") "); + } catch (BadLocationException e) { + // Ok + } + } + } + }); + } +} diff --git a/test/sun/java2d/GdiRendering/InsetClipping.java b/test/sun/java2d/GdiRendering/InsetClipping.java index 363f1609a35ab223623a0607d5be773af29ddcc3..0d03a4f83ddbe9c7c80289f0dbc26137d3e7f02c 100644 --- a/test/sun/java2d/GdiRendering/InsetClipping.java +++ b/test/sun/java2d/GdiRendering/InsetClipping.java @@ -84,6 +84,9 @@ public class InsetClipping extends Frame { Thread.sleep(100); } catch (Exception e) {} } + try { + Thread.sleep(2000); + } catch (InterruptedException ex) {} try { Robot robot = new Robot(); Point clientLoc = clipTest.getLocationOnScreen(); diff --git a/test/sun/java2d/SunGraphics2D/DrawImageBilinear.java b/test/sun/java2d/SunGraphics2D/DrawImageBilinear.java index ddc4b74e06bb14eeaab1c17734abbb1ddf1a9a37..e2dd1ba2174fafea92cc5683930757491151c741 100644 --- a/test/sun/java2d/SunGraphics2D/DrawImageBilinear.java +++ b/test/sun/java2d/SunGraphics2D/DrawImageBilinear.java @@ -56,6 +56,9 @@ public class DrawImageBilinear extends Canvas { private VolatileImage vimg; private static volatile BufferedImage capture; private static void doCapture(Component test) { + try { + Thread.sleep(2000); + } catch (InterruptedException ex) {} // Grab the screen region try { Robot robot = new Robot(); diff --git a/test/sun/java2d/SunGraphics2D/SourceClippingBlitTest/SourceClippingBlitTest.java b/test/sun/java2d/SunGraphics2D/SourceClippingBlitTest/SourceClippingBlitTest.java index 97fa82797305690a512d251138abb65bf601bb7a..292af722506e95632cc03761fa8503212d7869cc 100644 --- a/test/sun/java2d/SunGraphics2D/SourceClippingBlitTest/SourceClippingBlitTest.java +++ b/test/sun/java2d/SunGraphics2D/SourceClippingBlitTest/SourceClippingBlitTest.java @@ -204,6 +204,9 @@ public class SourceClippingBlitTest extends Canvas { int w = getWidth(); int h = getHeight(); Toolkit.getDefaultToolkit().sync(); + try { + Thread.sleep(2000); + } catch (InterruptedException ex) {} Point p = getLocationOnScreen(); grabbedBI = robot.createScreenCapture(new Rectangle(p.x, p.y, w, h)); diff --git a/test/sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.java b/test/sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.java index 21da7948778df8f3ac5597318fa1ce836c5ef5ee..800518e1cad40d2ce358758971652716c9f8638c 100644 --- a/test/sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.java +++ b/test/sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.java @@ -120,6 +120,9 @@ public class SharedMemoryPixmapsTest { } private boolean testRendering() throws RuntimeException { + try { + Thread.sleep(2000); + } catch (InterruptedException ex) {} Robot r = null; try { r = new Robot(); diff --git a/test/sun/security/krb5/tools/ktarg.sh b/test/sun/security/krb5/tools/ktarg.sh new file mode 100644 index 0000000000000000000000000000000000000000..4f84e2469aa7e6b59b098dac7c8374bbceff96f1 --- /dev/null +++ b/test/sun/security/krb5/tools/ktarg.sh @@ -0,0 +1,67 @@ +# +# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please 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 7002036 +# @summary ktab return code changes on a error case +# @run shell ktarg.sh +# + +if [ "${TESTJAVA}" = "" ] ; then + JAVAC_CMD=`which javac` + TESTJAVA=`dirname $JAVAC_CMD`/.. +fi + +if [ "${TESTSRC}" = "" ] ; then + TESTSRC="." +fi + +OS=`uname -s` +case "$OS" in + CYGWIN* ) + FS="/" + ;; + Windows_* ) + FS="\\" + ;; + * ) + FS="/" + echo "Unsupported system!" + exit 0; + ;; +esac + +KEYTAB=ktarg.tmp + +rm $KEYTAB 2> /dev/null +KTAB="${TESTJAVA}${FS}bin${FS}ktab -k $KEYTAB" + +$KTAB -a me@LOCAL mine || exit 1 + +$KTAB -hello +if [ $? = 0 ]; then exit 2; fi + +$KTAB +if [ $? = 0 ]; then exit 3; fi + +exit 0 diff --git a/test/sun/security/rsa/InvalidBitString.java b/test/sun/security/rsa/InvalidBitString.java new file mode 100644 index 0000000000000000000000000000000000000000..be9e42ca5444f95027113a9655bedc0224c557d0 --- /dev/null +++ b/test/sun/security/rsa/InvalidBitString.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 Validation of signatures succeed when it should fail + * @bug 6896700 + */ + +import java.io.InputStream; +import java.io.ByteArrayInputStream; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.PublicKey; +import java.security.SignatureException; + +public class InvalidBitString { + + // Test cert for CN=CA + static String signerCertStr = + "-----BEGIN CERTIFICATE-----\n" + + "MIIBtDCCAR2gAwIBAgIEemxRHjANBgkqhkiG9w0BAQUFADANMQswCQYDVQQDEwJDQTAeFw0xMDA2\n" + + "MDMwODA2MjlaFw0xMDA5MDEwODA2MjlaMA0xCzAJBgNVBAMTAkNBMIGfMA0GCSqGSIb3DQEBAQUA\n" + + "A4GNADCBiQKBgQCp2G7pGwMOw4oM7zFFeRKrByuPLNAXClGsh+itdRiOeUgEby6OB9IAgXm93086\n" + + "Z9dWCfRYbzJbDRSnUE7FS1iQsIRIeOEuFMIMogcBK+sOf364ONwMXsI4gtYVmxn4BaaajVWt6C/g\n" + + "FBGZQxp81aORDyUIrlCkMIxhZBSsNPIJYwIDAQABoyEwHzAdBgNVHQ4EFgQUKrvzNhJmdKoqq2li\n" + + "utCzKkwA1N0wDQYJKoZIhvcNAQEFBQADgYEAEIaegsW7fWWjXk4YOMlcl893vx6tnU8ThuQSjwGI\n" + + "rIs93sBYuY7lQIpQw8+XM89WT1XuBB6R2SsnxeW+gHtsU/EE6iJJAEMeCILwEGUL02blwHBQWmpa\n" + + "i3YeGXw+IFe/4OAysPT7ZRbUb7mPt37Ht6hIjain71ShR5anXIuawVE=\n" + + "-----END CERTIFICATE-----\n"; + // Test cert for CN=A, happens to have a zero at the beginning of signature + static String normalCertStr = + "-----BEGIN CERTIFICATE-----\n" + + "MIIB1DCCAT2gAwIBAgIEae+u1TANBgkqhkiG9w0BAQUFADANMQswCQYDVQQDEwJDQTAeFw0xMDA2\n" + + "MDMwODA2NTNaFw0xMDA5MDEwODA2NTNaMAwxCjAIBgNVBAMTAUEwgZ8wDQYJKoZIhvcNAQEBBQAD\n" + + "gY0AMIGJAoGBAKZ7C6bC8AJmXIRNwuPJcgIPW1ygN3rE5PIKPAkeK/dYnPmUJNuiSxOFPJCrLMuL\n" + + "sweQh82Dq/viu+KBb27xVzJ4pK02fbcWdJDo7cIms0Wm+HckK5myA6xmqnpmPOjb/vWCLE6pN2Xg\n" + + "pJyrdeWV77eBvqE9OiCsMTP8WgHI9zLvAgMBAAGjQjBAMB0GA1UdDgQWBBTtIKqCHnL9QeFn+YrX\n" + + "+k00NUk9mjAfBgNVHSMEGDAWgBQqu/M2EmZ0qiqraWK60LMqTADU3TANBgkqhkiG9w0BAQUFAAOB\n" + + "gQAAOcQsEruDAY/z3eXJ7OtWSZlLC0yTVNVdUVNLQ58xNqPrmKNBXNpj/72N8xrTB++ApW+DLgLy\n" + + "cwGU5PVRtsYeiV6prUkpqUf62SQgwI4guAQy1ileeP1CNQJI3cHQExMAHvQT8fJtlD0WZD3nfesq\n" + + "mmQDOpoJLkmO/73Z7IibVA==\n" + + "-----END CERTIFICATE-----\n"; + // normalCertStr with an extra zero at the beginning of signature + static String longerCertStr = + "-----BEGIN CERTIFICATE-----\n" + + "MIIB1TCCAT2gAwIBAgIEae+u1TANBgkqhkiG9w0BAQUFADANMQswCQYDVQQDEwJDQTAeFw0xMDA2\n" + + "MDMwODA2NTNaFw0xMDA5MDEwODA2NTNaMAwxCjAIBgNVBAMTAUEwgZ8wDQYJKoZIhvcNAQEBBQAD\n" + + "gY0AMIGJAoGBAKZ7C6bC8AJmXIRNwuPJcgIPW1ygN3rE5PIKPAkeK/dYnPmUJNuiSxOFPJCrLMuL\n" + + "sweQh82Dq/viu+KBb27xVzJ4pK02fbcWdJDo7cIms0Wm+HckK5myA6xmqnpmPOjb/vWCLE6pN2Xg\n" + + "pJyrdeWV77eBvqE9OiCsMTP8WgHI9zLvAgMBAAGjQjBAMB0GA1UdDgQWBBTtIKqCHnL9QeFn+YrX\n" + + "+k00NUk9mjAfBgNVHSMEGDAWgBQqu/M2EmZ0qiqraWK60LMqTADU3TANBgkqhkiG9w0BAQUFAAOB\n" + + "ggAAADnELBK7gwGP893lyezrVkmZSwtMk1TVXVFTS0OfMTaj65ijQVzaY/+9jfMa0wfvgKVvgy4C\n" + + "8nMBlOT1UbbGHoleqa1JKalH+tkkIMCOILgEMtYpXnj9QjUCSN3B0BMTAB70E/HybZQ9FmQ9533r\n" + + "KppkAzqaCS5Jjv+92eyIm1Q=\n" + + "-----END CERTIFICATE-----\n"; + // normalCertStr without the initial zero at the beginning of signature + static String shorterCertStr = + "-----BEGIN CERTIFICATE-----\n" + + "MIIB0zCCAT2gAwIBAgIEae+u1TANBgkqhkiG9w0BAQUFADANMQswCQYDVQQDEwJDQTAeFw0xMDA2\n" + + "MDMwODA2NTNaFw0xMDA5MDEwODA2NTNaMAwxCjAIBgNVBAMTAUEwgZ8wDQYJKoZIhvcNAQEBBQAD\n" + + "gY0AMIGJAoGBAKZ7C6bC8AJmXIRNwuPJcgIPW1ygN3rE5PIKPAkeK/dYnPmUJNuiSxOFPJCrLMuL\n" + + "sweQh82Dq/viu+KBb27xVzJ4pK02fbcWdJDo7cIms0Wm+HckK5myA6xmqnpmPOjb/vWCLE6pN2Xg\n" + + "pJyrdeWV77eBvqE9OiCsMTP8WgHI9zLvAgMBAAGjQjBAMB0GA1UdDgQWBBTtIKqCHnL9QeFn+YrX\n" + + "+k00NUk9mjAfBgNVHSMEGDAWgBQqu/M2EmZ0qiqraWK60LMqTADU3TANBgkqhkiG9w0BAQUFAAOB\n" + + "gAA5xCwSu4MBj/Pd5cns61ZJmUsLTJNU1V1RU0tDnzE2o+uYo0Fc2mP/vY3zGtMH74Clb4MuAvJz\n" + + "AZTk9VG2xh6JXqmtSSmpR/rZJCDAjiC4BDLWKV54/UI1AkjdwdATEwAe9BPx8m2UPRZkPed96yqa\n" + + "ZAM6mgkuSY7/vdnsiJtU\n" + + "-----END CERTIFICATE-----\n"; + + public static void main(String args[]) throws Exception { + + Certificate signer = generate(signerCertStr); + + // the valid certificate + Certificate normal = generate(normalCertStr); + // the invalid certificate with extra signature bits + Certificate longer = generate(longerCertStr); + // the invalid certificate without enough signature bits + Certificate shorter = generate(shorterCertStr); + + if (!test(normal, signer, " normal", true) || + !test(longer, signer, " longer", false) || + !test(shorter, signer, "shorter", false)) { + throw new Exception("Test failed."); + } + } + + private static Certificate generate(String certStr) throws Exception { + InputStream is = null; + try { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + is = new ByteArrayInputStream(certStr.getBytes()); + return cf.generateCertificate(is); + } finally { + if (is != null) { + is.close(); + } + } + } + + private static boolean test(Certificate target, Certificate signer, + String title, boolean expected) throws Exception { + System.out.print("Checking " + title + ": expected: " + + (expected ? " verified" : "NOT verified")); + boolean actual; + try { + PublicKey pubKey = signer.getPublicKey(); + target.verify(pubKey); + actual = true; + } catch (SignatureException se) { + actual = false; + } + System.out.println(", actual: " + + (actual ? " verified" : "NOT verified")); + return actual == expected; + } + +} diff --git a/test/sun/security/rsa/TestKeyPairGenerator.java b/test/sun/security/rsa/TestKeyPairGenerator.java index 444d5ece29115713d24094c12932a1ba6f113f6e..88ab075bced80c9b14ee52964e7592618c144152 100644 --- a/test/sun/security/rsa/TestKeyPairGenerator.java +++ b/test/sun/security/rsa/TestKeyPairGenerator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -85,8 +85,12 @@ public class TestKeyPairGenerator { sig.initVerify(kp2.getPublic()); sig.update(data); // verify needs to return false and not throw an Exception - if (sig.verify(signature)) { - throw new Exception("verification unexpectedly succeeded"); + try { + if (sig.verify(signature)) { + throw new Exception("verification unexpectedly succeeded"); + } + } catch (SignatureException se) { + // Yet another kind of failure, OK. } } diff --git a/test/sun/security/tools/jarsigner/JarSigningNonAscii.java b/test/sun/security/tools/jarsigner/JarSigningNonAscii.java index ed17e6e7bb6454481b884d7e1fc466e0b654d9dd..c0cae086252a65a361e1cb44af050b2c4865572f 100644 --- a/test/sun/security/tools/jarsigner/JarSigningNonAscii.java +++ b/test/sun/security/tools/jarsigner/JarSigningNonAscii.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -113,7 +113,7 @@ public class JarSigningNonAscii { } } - if (isSignedCount != 3) { + if (isSignedCount != 4) { throw new SecurityException("error signing JAR file"); } diff --git a/test/sun/security/tools/jarsigner/checkusage.sh b/test/sun/security/tools/jarsigner/checkusage.sh new file mode 100644 index 0000000000000000000000000000000000000000..957df161d9b35eadfca4a8dfe17e625ba340c7ae --- /dev/null +++ b/test/sun/security/tools/jarsigner/checkusage.sh @@ -0,0 +1,109 @@ +# +# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please 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 7004168 +# @summary jarsigner -verify checks for KeyUsage codesigning ext on all certs +# instead of just signing cert +# +# @run shell checkusage.sh +# + +if [ "${TESTJAVA}" = "" ] ; then + JAVAC_CMD=`which javac` + TESTJAVA=`dirname $JAVAC_CMD`/.. +fi + +# set platform-dependent variables +OS=`uname -s` +case "$OS" in + Windows_* ) + FS="\\" + ;; + * ) + FS="/" + ;; +esac + +KT="$TESTJAVA${FS}bin${FS}keytool -storepass changeit -keypass changeit" +JAR=$TESTJAVA${FS}bin${FS}jar +JARSIGNER="$TESTJAVA${FS}bin${FS}jarsigner" + +rm js.jks trust.jks unrelated.jks 2> /dev/null + +echo x > x +$JAR cvf a.jar x + +################### 3 Keystores ####################### + +# Keystore js.jks: including CA and Publisher +# CA contains a non-empty KeyUsage +$KT -keystore js.jks -genkeypair -alias ca -dname CN=CA -ext KU=kCS -ext bc -validity 365 +$KT -keystore js.jks -genkeypair -alias pub -dname CN=Publisher + +# Publisher contains the correct KeyUsage +$KT -keystore js.jks -certreq -alias pub | \ + $KT -keystore js.jks -gencert -alias ca -ext KU=dig -validity 365 | \ + $KT -keystore js.jks -importcert -alias pub + +# Keystore trust.jks: including CA only +$KT -keystore js.jks -exportcert -alias ca | \ + $KT -keystore trust.jks -importcert -alias ca -noprompt + +# Keystore unrelated.jks: unrelated +$KT -keystore unrelated.jks -genkeypair -alias nothing -dname CN=Nothing -validity 365 + + +################### 4 Tests ####################### + +# Test 1: Sign should be OK + +$JARSIGNER -keystore js.jks -storepass changeit a.jar pub +RESULT=$? +echo $RESULT +#[ $RESULT = 0 ] || exit 1 + +# Test 2: Verify should be OK + +$JARSIGNER -keystore trust.jks -strict -verify a.jar +RESULT=$? +echo $RESULT +#[ $RESULT = 0 ] || exit 2 + +# Test 3: When no keystore is specified, the error is only +# "chain not validated" + +$JARSIGNER -strict -verify a.jar +RESULT=$? +echo $RESULT +#[ $RESULT = 4 ] || exit 3 + +# Test 4: When unrelated keystore is specified, the error is +# "chain not validated" and "not alias in keystore" + +$JARSIGNER -keystore unrelated.jks -strict -verify a.jar +RESULT=$? +echo $RESULT +#[ $RESULT = 36 ] || exit 4 + +exit 0 diff --git a/test/sun/security/tools/jarsigner/concise_jarsigner.sh b/test/sun/security/tools/jarsigner/concise_jarsigner.sh index 0b145a902b62bf86550d659c590422d59f54cff7..5edce57057b66a1163a7c23d9fe603b896e40e75 100644 --- a/test/sun/security/tools/jarsigner/concise_jarsigner.sh +++ b/test/sun/security/tools/jarsigner/concise_jarsigner.sh @@ -1,5 +1,5 @@ # -# Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. # 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,9 +79,9 @@ $JAR uvf a.jar A5.class A6.class $JARSIGNER -verify a.jar [ $? = 0 ] || exit $LINENO -# 4(chainNotValidated)+16(hasUnsignedEntry)+32(aliasNotInStore) +# 4(chainNotValidated)+16(hasUnsignedEntry) $JARSIGNER -verify a.jar -strict -[ $? = 52 ] || exit $LINENO +[ $? = 20 ] || exit $LINENO # 16(hasUnsignedEntry) $JARSIGNER -verify a.jar -strict -keystore js.jks @@ -103,27 +103,31 @@ LINES=`$JARSIGNER -verify a.jar -verbose | grep $YEAR | wc -l` LINES=`$JARSIGNER -verify a.jar -verbose:grouped | grep $YEAR | wc -l` [ $LINES = 12 ] || exit $LINENO -# 3 groups: unrelated, signed, unsigned +# 4 groups: MANIFST, unrelated, signed, unsigned LINES=`$JARSIGNER -verify a.jar -verbose:summary | grep $YEAR | wc -l` +[ $LINES = 4 ] || exit $LINENO + +# still 4 groups, but MANIFEST group has no other file +LINES=`$JARSIGNER -verify a.jar -verbose:summary | grep "more)" | wc -l` [ $LINES = 3 ] || exit $LINENO -# 4 groups: unrelated, signed by a1/a2, signed by a2, unsigned +# 5 groups: MANIFEST, unrelated, signed by a1/a2, signed by a2, unsigned LINES=`$JARSIGNER -verify a.jar -verbose:summary -certs | grep $YEAR | wc -l` -[ $LINES = 4 ] || exit $LINENO +[ $LINES = 5 ] || exit $LINENO -# 2*2 for A1/A2, 2 for A3/A4 +# 2 for MANIFEST, 2*2 for A1/A2, 2 for A3/A4 LINES=`$JARSIGNER -verify a.jar -verbose -certs | grep "\[certificate" | wc -l` -[ $LINES = 6 ] || exit $LINENO +[ $LINES = 8 ] || exit $LINENO -# a1,a2 for A1/A2, a2 for A3/A4 +# a1,a2 for MANIFEST, a1,a2 for A1/A2, a2 for A3/A4 LINES=`$JARSIGNER -verify a.jar -verbose:grouped -certs | grep "\[certificate" | wc -l` -[ $LINES = 3 ] || exit $LINENO +[ $LINES = 5 ] || exit $LINENO -# a1,a2 for A1/A2, a2 for A3/A4 +# a1,a2 for MANIFEST, a1,a2 for A1/A2, a2 for A3/A4 LINES=`$JARSIGNER -verify a.jar -verbose:summary -certs | grep "\[certificate" | wc -l` -[ $LINES = 3 ] || exit $LINENO +[ $LINES = 5 ] || exit $LINENO -# 4 groups +# still 5 groups, but MANIFEST group has no other file LINES=`$JARSIGNER -verify a.jar -verbose:summary -certs | grep "more)" | wc -l` [ $LINES = 4 ] || exit $LINENO diff --git a/test/sun/security/tools/jarsigner/onlymanifest.sh b/test/sun/security/tools/jarsigner/onlymanifest.sh new file mode 100644 index 0000000000000000000000000000000000000000..5ea95784b1b5007280fa58396efddbd70a8f5856 --- /dev/null +++ b/test/sun/security/tools/jarsigner/onlymanifest.sh @@ -0,0 +1,68 @@ +# +# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please 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 7004035 +# @summary signed jar with only META-INF/* inside is not verifiable +# + +if [ "${TESTJAVA}" = "" ] ; then + JAVAC_CMD=`which javac` + TESTJAVA=`dirname $JAVAC_CMD`/.. +fi + +# set platform-dependent variables +OS=`uname -s` +case "$OS" in + Windows_* ) + FS="\\" + ;; + * ) + FS="/" + ;; +esac + +KS=onlymanifest.jks +JFILE=onlymanifest.jar + +KT="$TESTJAVA${FS}bin${FS}keytool -storepass changeit -keypass changeit \ + -keystore $KS" +JAR=$TESTJAVA${FS}bin${FS}jar +JARSIGNER=$TESTJAVA${FS}bin${FS}jarsigner + +rm $KS $JFILE 2> /dev/null + +# Create an empty jar file with only MANIFEST.MF + +echo "Key: Value" > manifest +$JAR cvfm $JFILE manifest + +$KT -alias a -dname CN=a -genkey -validity 300 || exit 1 +$JARSIGNER -keystore $KS -storepass changeit $JFILE a -debug -strict || exit 2 +$JARSIGNER -keystore $KS -storepass changeit -verify $JFILE a -debug -strict \ + > onlymanifest.out || exit 3 + +grep unsigned onlymanifest.out && exit 4 + +exit 0 + diff --git a/test/tools/launcher/Settings.java b/test/tools/launcher/Settings.java new file mode 100644 index 0000000000000000000000000000000000000000..b78443acc6ba2bb97da2ec46e707a407c8f92378 --- /dev/null +++ b/test/tools/launcher/Settings.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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.File; +import java.io.IOException; + +/* + * @test + * @bug 6994753 + * @summary tests -XshowSettings options + * @compile -XDignore.symbol.file Settings.java TestHelper.java + * @run main Settings + * @author ksrini + */ +public class Settings { + private static File testJar = null; + + static void init() throws IOException { + if (testJar != null) { + return; + } + testJar = new File("test.jar"); + StringBuilder tsrc = new StringBuilder(); + tsrc.append("public static void main(String... args) {\n"); + tsrc.append(" for (String x : args) {\n"); + tsrc.append(" System.out.println(x);\n"); + tsrc.append(" }\n"); + tsrc.append("}\n"); + TestHelper.createJar(testJar, tsrc.toString()); + } + + static void checkContains(TestHelper.TestResult tr, String str) { + if (!tr.contains(str)) { + System.out.println(tr); + throw new RuntimeException(str + " not found"); + } + } + + static void checkNoContains(TestHelper.TestResult tr, String str) { + if (tr.contains(str)) { + System.out.println(tr.status); + throw new RuntimeException(str + " found"); + } + } + + private static final String VM_SETTINGS = "VM settings:"; + private static final String PROP_SETTINGS = "Property settings:"; + private static final String LOCALE_SETTINGS = "Locale settings:"; + + static void containsAllOptions(TestHelper.TestResult tr) { + checkContains(tr, VM_SETTINGS); + checkContains(tr, PROP_SETTINGS); + checkContains(tr, LOCALE_SETTINGS); + } + + static void runTestOptionDefault() throws IOException { + TestHelper.TestResult tr = null; + tr = TestHelper.doExec(TestHelper.javaCmd, "-Xmx512m", "-Xss128k", + "-XshowSettings", "-jar", testJar.getAbsolutePath()); + containsAllOptions(tr); + if (!tr.isOK()) { + System.out.println(tr.status); + throw new RuntimeException("test fails"); + } + } + + static void runTestOptionAll() throws IOException { + init(); + TestHelper.TestResult tr = null; + tr = TestHelper.doExec(TestHelper.javaCmd, "-XshowSettings:all"); + containsAllOptions(tr); + } + + static void runTestOptionVM() throws IOException { + TestHelper.TestResult tr = null; + tr = TestHelper.doExec(TestHelper.javaCmd, "-XshowSettings:vm"); + checkContains(tr, VM_SETTINGS); + checkNoContains(tr, PROP_SETTINGS); + checkNoContains(tr, LOCALE_SETTINGS); + } + + static void runTestOptionProperty() throws IOException { + TestHelper.TestResult tr = null; + tr = TestHelper.doExec(TestHelper.javaCmd, "-XshowSettings:properties"); + checkNoContains(tr, VM_SETTINGS); + checkContains(tr, PROP_SETTINGS); + checkNoContains(tr, LOCALE_SETTINGS); + } + + static void runTestOptionLocale() throws IOException { + TestHelper.TestResult tr = null; + tr = TestHelper.doExec(TestHelper.javaCmd, "-XshowSettings:locale"); + checkNoContains(tr, VM_SETTINGS); + checkNoContains(tr, PROP_SETTINGS); + checkContains(tr, LOCALE_SETTINGS); + } + + static void runTestBadOptions() throws IOException { + TestHelper.TestResult tr = null; + tr = TestHelper.doExec(TestHelper.javaCmd, "-XshowSettingsBadOption"); + checkNoContains(tr, VM_SETTINGS); + checkNoContains(tr, PROP_SETTINGS); + checkNoContains(tr, LOCALE_SETTINGS); + checkContains(tr, "Unrecognized option: -XshowSettingsBadOption"); + } + public static void main(String... args) { + try { + runTestOptionAll(); + runTestOptionDefault(); + runTestOptionVM(); + runTestOptionProperty(); + runTestOptionLocale(); + runTestBadOptions(); + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } + } +}