diff --git a/.hgtags b/.hgtags index 6e2a50acf2f3b84f81797d10ddfe563e8f2a58ee..45fbf746c13291e93db1c38aa9a7615fba78fc4e 100644 --- a/.hgtags +++ b/.hgtags @@ -216,3 +216,7 @@ c63eda8f63008a4398d2c22ac8d72f7fef6f9238 jdk8-b90 a2a2a91075ad85becbe10a39d7fd04ef9bea8df5 jdk8-b92 691d6c6cd332d98b0f0221445a73906776f31f72 jdk8-b93 51479fa56b7c4363c6d87c2e8b898d8185cf4b22 jdk8-b94 +42aa9f1828852bb8b77e98ec695211493ae0759d jdk8-b95 +4a5d3cf2b3af1660db0237e8da324c140e534fa4 jdk8-b96 +978a95239044f26dcc8a6d59246be07ad6ca6be2 jdk8-b97 +c4908732fef5235f1b98cafe0ce507771ef7892c jdk8-b98 diff --git a/make/common/Release.gmk b/make/common/Release.gmk index ce2dda53d1d9c86e3b6e8ec51e939898a66f02da..b584781eb50355746ef7476b6a714f469d2ff8ac 100644 --- a/make/common/Release.gmk +++ b/make/common/Release.gmk @@ -252,7 +252,7 @@ images:: sanity-images post-sanity-images \ $(INITIAL_IMAGE_JRE) $(INITIAL_IMAGE_JDK) \ trim-image-jre trim-image-jdk \ identify-image-jre identify-image-jdk \ - process-image-jre process-image-jdk sec-files sec-files-win jgss-files + process-image-jre process-image-jdk sec-files sec-files-win jgss-files endif # Don't use these @@ -400,7 +400,8 @@ TOOLS = \ # classes that go into jfr.jar JFR_CLASSES_DIRS= \ com/oracle/jrockit/jfr \ - oracle/jrockit/jfr + oracle/jrockit/jfr \ + jdk/jfr # classes that go into jsse.jar JSSE_CLASSES_DIRS = \ @@ -612,6 +613,7 @@ ifndef JAVASE_EMBEDDED $(ECHO) "oracle/jrockit/jfr/parser/" >> $@ $(ECHO) "oracle/jrockit/jfr/settings/" >> $@ $(ECHO) "oracle/jrockit/jfr/tools/" >> $@ + $(ECHO) "jdk/jfr/" >> $@ endif endif diff --git a/make/sun/font/Makefile b/make/sun/font/Makefile index 1cdd11934ccd1bd21a193d07f13d3bdb1d3d6f68..fd8c8a2c44840f5eb270dd823d927b0156f32765 100644 --- a/make/sun/font/Makefile +++ b/make/sun/font/Makefile @@ -36,7 +36,11 @@ PRODUCT = sun CPLUSPLUSLIBRARY=true # Use higher optimization level +ifeq ($(PLATFORM), windows) +OPTIMIZATION_LEVEL = HIGHEST +else OPTIMIZATION_LEVEL = HIGHER +endif include $(BUILDDIR)/common/Defs.gmk diff --git a/makefiles/CompileNativeLibraries.gmk b/makefiles/CompileNativeLibraries.gmk index 2fc34d8eea754e5f7bf032af069d78a20fa127c9..02bf3be808c5cc68d788be3c8051536c5f10f388 100644 --- a/makefiles/CompileNativeLibraries.gmk +++ b/makefiles/CompileNativeLibraries.gmk @@ -1332,7 +1332,7 @@ LIBFONTMANAGER_OPTIMIZATION:=HIGH ifeq ($(OPENJDK_TARGET_OS),windows) LIBFONTMANAGER_EXCLUDE_FILES += X11FontScaler.c \ X11TextRenderer.c - LIBFONTMANAGER_OPTIMIZATION:=LOW +LIBFONTMANAGER_OPTIMIZATION:=HIGHEST else LIBFONTMANAGER_EXCLUDE_FILES += fontpath.c \ lcdglyph.c @@ -2916,7 +2916,7 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBJSOUNDALSA,\ PLATFORM_API_LinuxOS_ALSA_Ports.c,\ LANG:=C,\ OPTIMIZATION:=LOW, \ - CFLAGS:=$(CFLAGS_JDKLIB) \ + CFLAGS:=$(CFLAGS_JDKLIB) $(ALSA_CFLAGS) \ $(LIBJSOUND_CFLAGS) \ -DUSE_DAUDIO=TRUE \ -DUSE_PORTS=TRUE \ @@ -2925,7 +2925,7 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBJSOUNDALSA,\ MAPFILE:=$(JDK_TOPDIR)/makefiles/mapfiles/libjsoundalsa/mapfile-vers, \ LDFLAGS:=$(LDFLAGS_JDKLIB)\ $(call SET_SHARED_LIBRARY_ORIGIN),\ - LDFLAGS_SUFFIX:=-lasound -ljava -ljvm,\ + LDFLAGS_SUFFIX:=$(ALSA_LIBS) -ljava -ljvm,\ OBJECT_DIR:=$(JDK_OUTPUTDIR)/objs/libjsoundalsa,\ DEBUG_SYMBOLS:=$(DEBUG_ALL_BINARIES))) diff --git a/makefiles/CopyFiles.gmk b/makefiles/CopyFiles.gmk index 82d3d4bb40e2417f5020943668e4c27ac98084f4..cb479bba1c52ec19a8e617e244918d1fa1ba721c 100644 --- a/makefiles/CopyFiles.gmk +++ b/makefiles/CopyFiles.gmk @@ -538,21 +538,4 @@ COPY_FILES += $(JDK_OUTPUTDIR)/lib/sound.properties ########################################################################################## -ifndef OPENJDK -ifeq ($(ENABLE_JFR), true) - -JFR_CONFIGURATION_DIR_SRC := $(JDK_TOPDIR)/src/closed/share/classes/oracle/jrockit/jfr/settings/ -JFR_CONFIGURATION_DIR_DST := $(LIBDIR)/jfr/ - -JFR_SRC_FILES = $(wildcard $(JFR_CONFIGURATION_DIR_SRC)/*.jfc) -JFR_TARGET_FILES = $(subst $(JFR_CONFIGURATION_DIR_SRC),$(JFR_CONFIGURATION_DIR_DST),$(JFR_SRC_FILES)) - -$(JFR_CONFIGURATION_DIR_DST)/%.jfc : $(JFR_CONFIGURATION_DIR_SRC)/%.jfc - $(call install-file) - -COPY_FILES += $(JFR_TARGET_FILES) - -endif -endif - -########################################################################################## +-include $(CUSTOM_MAKE_DIR)/CopyFiles.gmk diff --git a/makefiles/CreateJars.gmk b/makefiles/CreateJars.gmk index 64c96b2c97e00bfe6c86a89cb23b90d8069a295e..54531f19ef5a7f86c1338df08700a82eb872e589 100644 --- a/makefiles/CreateJars.gmk +++ b/makefiles/CreateJars.gmk @@ -132,7 +132,7 @@ $(eval $(call SetupArchive,BUILD_LOCALEDATA_JAR,,\ ########################################################################################## # Full JRE exclude list for rt.jar and resources.jar -# This value should exclude types destined for jars other than rt.jar and resources.jar. +# This value should exclude types destined for jars other than rt.jar and resources.jar. # When building a Profile this value augments the profile specific exclusions RT_JAR_EXCLUDES += \ com/oracle/security \ @@ -246,7 +246,8 @@ RT_JAR_EXCLUDES += \ sun/util/resources/cldr \ $(LOCALEDATA_INCLUDES) \ com/oracle/jrockit/jfr \ - oracle/jrockit/jfr + oracle/jrockit/jfr \ + jdk/jfr ifeq ($(OPENJDK_TARGET_OS), macosx) RT_JAR_EXCLUDES += com/sun/nio/sctp \ @@ -337,7 +338,7 @@ $(PROFILE_VERSION_CLASS_TARGETS) : $(PROFILE_VERSION_JAVA_TARGETS) # Support for removing the addPropertyChangeListener and removePropertyChangeListener -# methods from classes that only go into the profile builds. +# methods from classes that only go into the profile builds. BEANLESS_CLASSES = $(IMAGES_OUTPUTDIR)/beanless # When there are $ characters in filenames we have some very subtle interactions between @@ -352,7 +353,7 @@ CLASSES_TO_DEBEAN = \ java/util/jar/Pack200\$$Packer.class \ java/util/jar/Pack200\$$Unpacker.class \ com/sun/java/util/jar/pack/PackerImpl.class \ - com/sun/java/util/jar/pack/UnpackerImpl.class + com/sun/java/util/jar/pack/UnpackerImpl.class ifneq ($(PROFILE),) BEANLESS_CLASSES_TARGETS := $(addprefix $(BEANLESS_CLASSES)/, $(CLASSES_TO_DEBEAN)) @@ -428,7 +429,8 @@ ifeq ($(ENABLE_JFR), true) SRCS:=$(JDK_OUTPUTDIR)/classes,\ SUFFIXES:=.class .jfc .xsd,\ INCLUDES:=com/oracle/jrockit/jfr \ - oracle/jrockit/jfr,\ + oracle/jrockit/jfr \ + jdk/jfr,\ JAR:=$(IMAGES_OUTPUTDIR)/lib/jfr.jar,\ SKIP_METAINF:=true,\ MANIFEST:=$(MAINMANIFEST), \ @@ -468,14 +470,14 @@ $(JCE_MANIFEST): $(MAINMANIFEST) $(MV) $@.tmp $@ ########################################################################################## -# For security and crypto jars, always build the jar, but for closed, install the prebuilt -# signed version instead of the newly built jar. Unsigned jars are treated as intermediate -# targets and explicitly added to the JARS list. For open, signing is not needed. See +# For security and crypto jars, always build the jar, but for closed, install the prebuilt +# signed version instead of the newly built jar. Unsigned jars are treated as intermediate +# targets and explicitly added to the JARS list. For open, signing is not needed. See # SignJars.gmk for more information. # # The source for the crypto jars is not available for all licensees. The BUILD_CRYPTO # variable is set to no if these jars can't be built to skip that step of the build. -# Note that for OPENJDK, the build will fail if BUILD_CRYPTO=no since then there is no +# Note that for OPENJDK, the build will fail if BUILD_CRYPTO=no since then there is no # other way to get the jars than to build them. SUNPKCS11_JAR_DST := $(IMAGES_OUTPUTDIR)/lib/ext/sunpkcs11.jar @@ -738,7 +740,7 @@ $(UCRYPTO_JAR_DST) : $(UCRYPTO_JAR_SRC) @$(ECHO) $(LOG_INFO) "\n>>>Installing prebuilt OracleUcrypto provider..." $(install-file) -JARS += $(UCRYPTO_JAR_UNSIGNED) +JARS += $(UCRYPTO_JAR_UNSIGNED) endif endif diff --git a/makefiles/profile-includes.txt b/makefiles/profile-includes.txt index 8a137b8b4622918b772470457ecefdee064347a1..f4876284b735d29b585269b209bd8e96bc5fe997 100644 --- a/makefiles/profile-includes.txt +++ b/makefiles/profile-includes.txt @@ -125,13 +125,11 @@ PROFILE_3_JRE_LIB_FILES := \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)jaas_unix$(SHARED_LIBRARY_SUFFIX) \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)java_crw_demo$(SHARED_LIBRARY_SUFFIX) \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)java_crw_demo.diz \ - $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)jfr$(SHARED_LIBRARY_SUFFIX) \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)jsdt$(SHARED_LIBRARY_SUFFIX) \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)jsdt.diz \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)management$(SHARED_LIBRARY_SUFFIX) \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)management.diz \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)sctp$(SHARED_LIBRARY_SUFFIX) \ - jfr.jar \ jvm.hprof.txt \ management-agent.jar \ management/jmxremote.access \ @@ -164,6 +162,7 @@ FULL_JRE_LIB_FILES := \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)fontmanager$(SHARED_LIBRARY_SUFFIX) \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)jawt$(SHARED_LIBRARY_SUFFIX) \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)jdwp$(SHARED_LIBRARY_SUFFIX) \ + $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)jfr$(SHARED_LIBRARY_SUFFIX) \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)jpeg$(SHARED_LIBRARY_SUFFIX) \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)jsound$(SHARED_LIBRARY_SUFFIX) \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/$(LIBRARY_PREFIX)jsoundalsa$(SHARED_LIBRARY_SUFFIX) \ @@ -214,6 +213,7 @@ FULL_JRE_LIB_FILES := \ images/cursors/motif_MoveDrop32x32.gif \ images/cursors/motif_MoveNoDrop32x32.gif \ jexec \ + jfr.jar \ oblique-fonts/LucidaSansDemiOblique.ttf \ oblique-fonts/LucidaSansOblique.ttf \ oblique-fonts/LucidaTypewriterBoldOblique.ttf \ diff --git a/makefiles/sun/awt/ToBin.java b/makefiles/sun/awt/ToBin.java index 18ac89b6ec81794b324ebdb935238bccb9040285..db97240e43289a42133748c32c88938c9c1361d7 100644 --- a/makefiles/sun/awt/ToBin.java +++ b/makefiles/sun/awt/ToBin.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2013 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java b/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java index a73dbd17802671a23ddfa8af288820e1a064a621..ae7d363b84eb0f3d455cba8f6a07d0fa5da2c531 100644 --- a/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java +++ b/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java @@ -127,8 +127,21 @@ public class CEmbeddedFrame extends EmbeddedFrame { } } + /** + * When the parent window is activated this method is called for all EmbeddedFrames in it. + * + * For the CEmbeddedFrame which had focus before the deactivation this method triggers + * focus events in the following order: + * 1. WINDOW_ACTIVATED for this EmbeddedFrame + * 2. WINDOW_GAINED_FOCUS for this EmbeddedFrame + * 3. FOCUS_GAINED for the most recent focus owner in this EmbeddedFrame + * + * The caller must not requestFocus on the EmbeddedFrame together with calling this method. + * + * @param parentWindowActive true if the window is activated, false otherwise + */ // handleWindowFocusEvent is called for all applets, when the browser - // becames active/inactive. This event should be filtered out for + // becomes active/inactive. This event should be filtered out for // non-focused applet. This method can be called from different threads. public void handleWindowFocusEvent(boolean parentWindowActive) { this.parentWindowActive = parentWindowActive; diff --git a/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java b/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java index eab279193dd13d9f5c44dcaba0430fadd114b513..7230b2eeeb5d5457f3fbe81451682c7d644ea2dd 100644 --- a/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java +++ b/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java @@ -812,8 +812,6 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo throw new RuntimeException("Unknown window state: " + windowState); } - nativeSynthesizeMouseEnteredExitedEvents(); - // NOTE: the SWP.windowState field gets updated to the newWindowState // value when the native notification comes to us } diff --git a/src/macosx/native/com/apple/laf/AquaFileView.m b/src/macosx/native/com/apple/laf/AquaFileView.m index 8f33cc5da8c7bd49d546e9bf449dade0a470f2a2..65fcc72abd3be44a39153b44a067a58de362b4c4 100644 --- a/src/macosx/native/com/apple/laf/AquaFileView.m +++ b/src/macosx/native/com/apple/laf/AquaFileView.m @@ -187,13 +187,13 @@ JNIEXPORT jstring JNICALL Java_com_apple_laf_AquaFileView_getNativePathForResolv JNF_COCOA_ENTER(env); UInt8 pathCString[MAXPATHLEN + 1]; - size_t pathSize = sizeof(pathCString); + size_t maxPathLen = sizeof(pathCString) - 1; jbyte *byteArray = (*env)->GetByteArrayElements(env, pathToAlias, NULL); jsize length = (*env)->GetArrayLength(env, pathToAlias); - if (length > pathSize) { - length = pathSize; + if (length > maxPathLen) { + length = maxPathLen; } strncpy((char *)pathCString, (char *)byteArray, length); // make sure it's null terminated diff --git a/src/macosx/native/sun/awt/AWTEvent.m b/src/macosx/native/sun/awt/AWTEvent.m index fd3caa6051f28bf5aa94ec56d0b3ef91a7951ebe..b2d54f7e7053c40afba41e8b5034ac5ec736a5d9 100644 --- a/src/macosx/native/sun/awt/AWTEvent.m +++ b/src/macosx/native/sun/awt/AWTEvent.m @@ -382,7 +382,7 @@ static unichar NsGetDeadKeyChar(unsigned short keyCode) { TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource(); CFDataRef uchr = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData); - if (uchr == nil) { return; } + if (uchr == nil) { return 0; } const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(uchr); // Carbon modifiers should be used instead of NSEvent modifiers UInt32 modifierKeyState = (GetCurrentEventKeyModifiers() >> 8) & 0xFF; diff --git a/src/macosx/native/sun/awt/AWTWindow.m b/src/macosx/native/sun/awt/AWTWindow.m index 2997ff4de7560c2306fe25a3664fdbcdbc30788b..2a596bcfa75bb6abe62d046a15f01efb65c0d3c4 100644 --- a/src/macosx/native/sun/awt/AWTWindow.m +++ b/src/macosx/native/sun/awt/AWTWindow.m @@ -447,6 +447,8 @@ AWT_ASSERT_APPKIT_THREAD; // TODO: create generic AWT assert } + [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows]; + NSRect frame = ConvertNSScreenRect(env, [self.nsWindow frame]); static JNF_MEMBER_CACHE(jm_deliverMoveResizeEvent, jc_CPlatformWindow, "deliverMoveResizeEvent", "(IIIIZ)V"); @@ -630,6 +632,7 @@ AWT_ASSERT_APPKIT_THREAD; [self _notifyFullScreenOp:com_apple_eawt_FullScreenHandler_FULLSCREEN_DID_ENTER withEnv:env]; (*env)->DeleteLocalRef(env, platformWindow); } + [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows]; } - (void)windowWillExitFullScreen:(NSNotification *)notification { @@ -652,6 +655,7 @@ AWT_ASSERT_APPKIT_THREAD; [self _notifyFullScreenOp:com_apple_eawt_FullScreenHandler_FULLSCREEN_DID_EXIT withEnv:env]; (*env)->DeleteLocalRef(env, platformWindow); } + [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows]; } - (void)sendEvent:(NSEvent *)event { @@ -891,8 +895,6 @@ JNF_COCOA_ENTER(env); // ensure we repaint the whole window after the resize operation // (this will also re-enable screen updates, which were disabled above) // TODO: send PaintEvent - - [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows]; }]; JNF_COCOA_EXIT(env); diff --git a/src/share/classes/java/awt/DefaultKeyboardFocusManager.java b/src/share/classes/java/awt/DefaultKeyboardFocusManager.java index 1358908528b11ba7c7e8b2f4c2e7a2ae737a193e..7c0c39d8ffa81e70323a3d823de427db8dd98ade 100644 --- a/src/share/classes/java/awt/DefaultKeyboardFocusManager.java +++ b/src/share/classes/java/awt/DefaultKeyboardFocusManager.java @@ -285,10 +285,17 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager { TimedWindowEvent we = (TimedWindowEvent)e; long time = we.getWhen(); synchronized (this) { - for (KeyEvent ke: enqueuedKeyEvents) { - if (time >= ke.getWhen()) { - SunToolkit.postEvent(AppContext.getAppContext(), new SequencedEvent(e)); - return true; + KeyEvent ke = enqueuedKeyEvents.isEmpty() ? null : enqueuedKeyEvents.getFirst(); + if (ke != null && time >= ke.getWhen()) { + TypeAheadMarker marker = typeAheadMarkers.getFirst(); + if (marker != null) { + Window toplevel = marker.untilFocused.getContainingWindow(); + // Check that the component awaiting focus belongs to + // the current focused window. See 8015454. + if (toplevel != null && toplevel.isFocused()) { + SunToolkit.postEvent(AppContext.getAppContext(), new SequencedEvent(e)); + return true; + } } } } diff --git a/src/share/classes/java/awt/color/ICC_Profile.java b/src/share/classes/java/awt/color/ICC_Profile.java index b459f63b16d40ae5c98bcceb344f35b226781026..c1534249f391a14a30d261e81b3810920a27ffda 100644 --- a/src/share/classes/java/awt/color/ICC_Profile.java +++ b/src/share/classes/java/awt/color/ICC_Profile.java @@ -37,6 +37,7 @@ package java.awt.color; import sun.java2d.cmm.PCMM; import sun.java2d.cmm.CMSManager; +import sun.java2d.cmm.ProfileDataVerifier; import sun.java2d.cmm.ProfileDeferralMgr; import sun.java2d.cmm.ProfileDeferralInfo; import sun.java2d.cmm.ProfileActivator; @@ -775,6 +776,8 @@ public class ICC_Profile implements Serializable { ProfileDeferralMgr.activateProfiles(); } + ProfileDataVerifier.verify(data); + try { theID = CMSManager.getModule().loadProfile(data); } catch (CMMException c) { diff --git a/src/share/classes/java/beans/XMLEncoder.java b/src/share/classes/java/beans/XMLEncoder.java index 2ac3cdc30b29e82a4c8364f6ec42b4fbda8e6d9f..b7cc21de31288341f313f0bc5e76ddebee7e38b0 100644 --- a/src/share/classes/java/beans/XMLEncoder.java +++ b/src/share/classes/java/beans/XMLEncoder.java @@ -377,7 +377,7 @@ public class XMLEncoder extends Encoder implements AutoCloseable { Object arg = args[i]; mark(arg, true); } - mark(stm.getTarget(), false); + mark(stm.getTarget(), stm instanceof Expression); } diff --git a/src/share/classes/java/lang/Thread.java b/src/share/classes/java/lang/Thread.java index d97f03d4e24f5e71ecea94115d44f82b81b7160e..c07fde2f291919140138171076e03ee30390b36a 100644 --- a/src/share/classes/java/lang/Thread.java +++ b/src/share/classes/java/lang/Thread.java @@ -2013,12 +2013,21 @@ class Thread implements Runnable { // The following three initially uninitialized fields are exclusively - // managed by class java.util.concurrent.ThreadLocalRandom. + // managed by class java.util.concurrent.ThreadLocalRandom. These + // fields are used to build the high-performance PRNGs in the + // concurrent code, and we can not risk accidental false sharing. + // Hence, the fields are isolated with @Contended. + /** The current seed for a ThreadLocalRandom */ + @sun.misc.Contended("tlr") long threadLocalRandomSeed; + /** Probe hash value; nonzero if threadLocalRandomSeed initialized */ + @sun.misc.Contended("tlr") int threadLocalRandomProbe; + /** Secondary seed isolated from public ThreadLocalRandom sequence */ + @sun.misc.Contended("tlr") int threadLocalRandomSecondarySeed; /* Some private helper methods */ diff --git a/src/share/classes/java/lang/instrument/Instrumentation.java b/src/share/classes/java/lang/instrument/Instrumentation.java index 1844837fd3b2d6172dff9699a1c31d2399fdd88b..4cdb2de9c9aac0819d1d7d4ae0eefb3ce5bc48d7 100644 --- a/src/share/classes/java/lang/instrument/Instrumentation.java +++ b/src/share/classes/java/lang/instrument/Instrumentation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -363,6 +363,8 @@ public interface Instrumentation { * Primitive classes (for example, java.lang.Integer.TYPE) * and array classes are never modifiable. * + * @param theClass the class to check for being modifiable + * @return whether or not the argument class is modifiable * @throws java.lang.NullPointerException if the specified class is null. * * @see #retransformClasses @@ -549,14 +551,14 @@ public interface Instrumentation { * {@link java.lang.instrument.ClassFileTransformer ClassFileTransformer}, * it enables native methods to be * instrumented. - *

+ *

* Since native methods cannot be directly instrumented * (they have no bytecodes), they must be wrapped with * a non-native method which can be instrumented. * For example, if we had: *

      *   native boolean foo(int x);
- *

+ *

* We could transform the class file (with the * ClassFileTransformer during the initial definition * of the class) so that this becomes: @@ -567,14 +569,14 @@ public interface Instrumentation { * } * * native boolean wrapped_foo(int x); - *

+ *

* Where foo becomes a wrapper for the actual native * method with the appended prefix "wrapped_". Note that * "wrapped_" would be a poor choice of prefix since it * might conceivably form the name of an existing method * thus something like "$$$MyAgentWrapped$$$_" would be * better but would make these examples less readable. - *

+ *

* The wrapper will allow data to be collected on the native * method call, but now the problem becomes linking up the * wrapped method with the native implementation. @@ -583,7 +585,7 @@ public interface Instrumentation { * which might be: *

      *   Java_somePackage_someClass_foo(JNIEnv* env, jint x)
- *

+ *

* This function allows the prefix to be specified and the * proper resolution to occur. * Specifically, when the standard resolution fails, the @@ -596,29 +598,29 @@ public interface Instrumentation { *

{@code
      *   method(foo) -> nativeImplementation(foo)
      * }
- *

+ *

* When this fails, the resolution will be retried with * the specified prefix prepended to the method name, * yielding the correct resolution: *

{@code
      *   method(wrapped_foo) -> nativeImplementation(foo)
      * }
- *

+ *

* For automatic resolution, the JVM will attempt: *

{@code
      *   method(wrapped_foo) -> nativeImplementation(wrapped_foo)
      * }
- *

+ *

* When this fails, the resolution will be retried with * the specified prefix deleted from the implementation name, * yielding the correct resolution: *

{@code
      *   method(wrapped_foo) -> nativeImplementation(foo)
      * }
- *

+ *

* Note that since the prefix is only used when standard * resolution fails, native methods can be wrapped selectively. - *

+ *

* Since each ClassFileTransformer * can do its own transformation of the bytecodes, more * than one layer of wrappers may be applied. Thus each diff --git a/src/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java b/src/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java index 16703fc09177dfd3dc1bb2876f4a5fb0ee8c9ec0..0b6f4016b1d3c8c92d00c7d8ec4c964661c06f42 100644 --- a/src/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java +++ b/src/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java @@ -112,7 +112,9 @@ import java.security.PrivilegedAction; implMethodDesc = implMethodType.toMethodDescriptorString(); Type implMethodAsmType = Type.getMethodType(implMethodDesc); implMethodArgumentTypes = implMethodAsmType.getArgumentTypes(); - implMethodReturnType = implMethodAsmType.getReturnType(); + implMethodReturnType = (implKind == MethodHandleInfo.REF_newInvokeSpecial) + ? Type.getObjectType(implMethodClassName) + : implMethodAsmType.getReturnType(); constructorType = invokedType.changeReturnType(Void.TYPE); constructorDesc = constructorType.toMethodDescriptorString(); lambdaClassName = targetClass.getName().replace('.', '/') + "$$Lambda$" + counter.incrementAndGet(); diff --git a/src/share/classes/java/lang/invoke/LambdaConversionException.java b/src/share/classes/java/lang/invoke/LambdaConversionException.java index 11ffb580ea944c40b90a734ed9799d77db634672..5cc3c626e363c407031fbc118093780450788fe5 100644 --- a/src/share/classes/java/lang/invoke/LambdaConversionException.java +++ b/src/share/classes/java/lang/invoke/LambdaConversionException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,21 +29,45 @@ package java.lang.invoke; * LambdaConversionException */ public class LambdaConversionException extends Exception { + /** + * Constructs a {@code LambdaConversionException}. + */ public LambdaConversionException() { } + /** + * Constructs a {@code LambdaConversionException} with a message. + * @param message the detail message + */ public LambdaConversionException(String message) { super(message); } + /** + * Constructs a {@code LambdaConversionException} with a message and cause. + * @param message the detail message + * @param cause the cause + */ public LambdaConversionException(String message, Throwable cause) { super(message, cause); } + /** + * Constructs a {@code LambdaConversionException} with a cause. + * @param cause the cause + */ public LambdaConversionException(Throwable cause) { super(cause); } + /** + * Constructs a {@code LambdaConversionException} with a message, + * cause, and other settings. + * @param message the detail message + * @param cause the cause + * @param enableSuppression whether or not suppressed exceptions are enabled + * @param writableStackTrace whether or not the stack trace is writable + */ public LambdaConversionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } diff --git a/src/share/classes/java/lang/invoke/LambdaMetafactory.java b/src/share/classes/java/lang/invoke/LambdaMetafactory.java index d179d438e8a2d304e995b1918f83452fe9b374c1..e03dda002d1217d970e8cda1a0a32d90f01724d3 100644 --- a/src/share/classes/java/lang/invoke/LambdaMetafactory.java +++ b/src/share/classes/java/lang/invoke/LambdaMetafactory.java @@ -111,7 +111,7 @@ package java.lang.invoke; * done on return type, while a strict version is applied to arguments. * *

A type Q is considered adaptable to S as follows: - * + *
* * * @@ -155,7 +155,7 @@ public class LambdaMetafactory { private static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; -/** + /** * Standard meta-factory for conversion of lambda expressions or method references to functional interfaces. * * @param caller Stacked automatically by VM; represents a lookup context with the accessibility privileges @@ -174,7 +174,7 @@ public class LambdaMetafactory { * @param instantiatedMethodType The signature of the primary functional interface method after type variables * are substituted with their instantiation from the capture site * @return a CallSite, which, when invoked, will return an instance of the functional interface - * @throws ReflectiveOperationException + * @throws ReflectiveOperationException if the caller is not able to reconstruct one of the method handles * @throws LambdaConversionException If any of the meta-factory protocol invariants are violated */ public static CallSite metaFactory(MethodHandles.Lookup caller, @@ -226,7 +226,7 @@ public class LambdaMetafactory { * the first argument in the invocation signature will correspond to the receiver. * @param args argument to pass, flags, marker interface count, and marker interfaces as described above * @return a CallSite, which, when invoked, will return an instance of the functional interface - * @throws ReflectiveOperationException + * @throws ReflectiveOperationException if the caller is not able to reconstruct one of the method handles * @throws LambdaConversionException If any of the meta-factory protocol invariants are violated */ public static CallSite altMetaFactory(MethodHandles.Lookup caller, diff --git a/src/share/classes/java/lang/invoke/MethodHandle.java b/src/share/classes/java/lang/invoke/MethodHandle.java index 06084056fb4edb6d2a648cb1cac082e7f3a9b5f3..df784d35e5b6be8a1098c97ee0ae5f92a8cbf96b 100644 --- a/src/share/classes/java/lang/invoke/MethodHandle.java +++ b/src/share/classes/java/lang/invoke/MethodHandle.java @@ -44,7 +44,7 @@ import java.util.logging.Logger; * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion}, * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}. * - *

Method handle contents

+ *

Method handle contents

* Method handles are dynamically and strongly typed according to their parameter and return types. * They are not distinguished by the name or the defining class of their underlying methods. * A method handle must be invoked using a symbolic type descriptor which matches @@ -81,7 +81,7 @@ import java.util.logging.Logger; * from its specific class, as the method handle class hierarchy (if any) * may change from time to time or across implementations from different vendors. * - *

Method handle compilation

+ *

Method handle compilation

* A Java method call expression naming {@code invokeExact} or {@code invoke} * can invoke a method handle from Java source code. * From the viewpoint of source code, these methods can take any arguments @@ -111,7 +111,7 @@ import java.util.logging.Logger; * The ambiguity with the type {@code Void} is harmless, since there are no references of type * {@code Void} except the null reference. * - *

Method handle invocation

+ *

Method handle invocation

* The first time a {@code invokevirtual} instruction is executed * it is linked, by symbolically resolving the names in the instruction * and verifying that the method call is statically legal. @@ -154,7 +154,7 @@ import java.util.logging.Logger; * (Note: The adjusted method handle {@code M2} is not directly observable, * and implementations are therefore not required to materialize it.) * - *

Invocation checking

+ *

Invocation checking

* In typical programs, method handle type matching will usually succeed. * But if a match fails, the JVM will throw a {@link WrongMethodTypeException}, * either directly (in the case of {@code invokeExact}) or indirectly as if @@ -195,7 +195,7 @@ import java.util.logging.Logger; * They should not be passed to untrusted code unless their use from * the untrusted code would be harmless. * - *

Method handle creation

+ *

Method handle creation

* Java code can create a method handle that directly accesses * any method, constructor, or field that is accessible to that code. * This is done via a reflective, capability-based API called @@ -249,7 +249,7 @@ import java.util.logging.Logger; * receiver type. Such a method handle simulates the effect of * an {@code invokespecial} instruction to the same method. * - *

Usage examples

+ *

Usage examples

* Here are some examples of usage: *

{@code
 Object x, y; String s; int i;
@@ -295,7 +295,7 @@ mh.invokeExact(System.out, "Hello, world.");
  * be a method which calls {@link java.util.Objects#equals(Object,Object) Objects.equals }
  * on its arguments, and asserts that the result is true.
  *
- * 

Exceptions

+ *

Exceptions

* The methods {@code invokeExact} and {@code invoke} are declared * to throw {@link java.lang.Throwable Throwable}, * which is to say that there is no static restriction on what a method handle @@ -308,7 +308,7 @@ mh.invokeExact(System.out, "Hello, world."); * throwables locally, rethrowing only those which are legal in the context, * and wrapping ones which are illegal. * - *

Signature polymorphism

+ *

Signature polymorphism

* The unusual compilation and linkage behavior of * {@code invokeExact} and plain {@code invoke} * is referenced by the term signature polymorphism. @@ -333,7 +333,7 @@ mh.invokeExact(System.out, "Hello, world."); * Tools which determine symbolic linkage are required to accept such * untransformed descriptors, without reporting linkage errors. * - *

Interoperation between method handles and the Core Reflection API

+ *

Interoperation between method handles and the Core Reflection API

* Using factory methods in the {@link java.lang.invoke.MethodHandles.Lookup Lookup} API, * any class member represented by a Core Reflection API object * can be converted to a behaviorally equivalent method handle. @@ -375,7 +375,7 @@ mh.invokeExact(System.out, "Hello, world."); * to call {@code invokeExact} or plain {@code invoke}, * for any specified type descriptor . * - *

Interoperation between method handles and Java generics

+ *

Interoperation between method handles and Java generics

* A method handle can be obtained on a method, constructor, or field * which is declared with Java generic types. * As with the Core Reflection API, the type of the method handle @@ -457,6 +457,8 @@ public abstract class MethodHandle { * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI, * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}, * it will throw an {@code UnsupportedOperationException}. + * @param args the signature-polymorphic parameter list, statically represented using varargs + * @return the signature-polymorphic result, statically represented using {@code Object} * @throws WrongMethodTypeException if the target's type is not identical with the caller's symbolic type descriptor * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call */ @@ -491,6 +493,8 @@ public abstract class MethodHandle { * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI, * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}, * it will throw an {@code UnsupportedOperationException}. + * @param args the signature-polymorphic parameter list, statically represented using varargs + * @return the signature-polymorphic result, statically represented using {@code Object} * @throws WrongMethodTypeException if the target's type cannot be adjusted to the caller's symbolic type descriptor * @throws ClassCastException if the target's type can be adjusted to the caller, but a reference cast fails * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call @@ -511,15 +515,26 @@ public abstract class MethodHandle { * operations on outgoing argument values.) * The caller can assume that the incoming result value is part of the range * of the callee's return type. + * @param args the signature-polymorphic parameter list, statically represented using varargs + * @return the signature-polymorphic result, statically represented using {@code Object} */ /*non-public*/ final native @PolymorphicSignature Object invokeBasic(Object... args) throws Throwable; + /** + * Private method for trusted invocation of a MemberName of kind {@code REF_invokeVirtual}. + * The caller signature is restricted to basic types as with {@code invokeBasic}. + * The trailing (not leading) argument must be a MemberName. + * @param args the signature-polymorphic parameter list, statically represented using varargs + * @return the signature-polymorphic result, statically represented using {@code Object} + */ /*non-public*/ static native @PolymorphicSignature Object linkToVirtual(Object... args) throws Throwable; /** * Private method for trusted invocation of a MemberName of kind {@code REF_invokeStatic}. * The caller signature is restricted to basic types as with {@code invokeBasic}. * The trailing (not leading) argument must be a MemberName. + * @param args the signature-polymorphic parameter list, statically represented using varargs + * @return the signature-polymorphic result, statically represented using {@code Object} */ /*non-public*/ static native @PolymorphicSignature Object linkToStatic(Object... args) throws Throwable; @@ -527,6 +542,8 @@ public abstract class MethodHandle { * Private method for trusted invocation of a MemberName of kind {@code REF_invokeSpecial}. * The caller signature is restricted to basic types as with {@code invokeBasic}. * The trailing (not leading) argument must be a MemberName. + * @param args the signature-polymorphic parameter list, statically represented using varargs + * @return the signature-polymorphic result, statically represented using {@code Object} */ /*non-public*/ static native @PolymorphicSignature Object linkToSpecial(Object... args) throws Throwable; @@ -534,6 +551,8 @@ public abstract class MethodHandle { * Private method for trusted invocation of a MemberName of kind {@code REF_invokeInterface}. * The caller signature is restricted to basic types as with {@code invokeBasic}. * The trailing (not leading) argument must be a MemberName. + * @param args the signature-polymorphic parameter list, statically represented using varargs + * @return the signature-polymorphic result, statically represented using {@code Object} */ /*non-public*/ static native @PolymorphicSignature Object linkToInterface(Object... args) throws Throwable; diff --git a/src/share/classes/java/lang/invoke/MethodHandleProxies.java b/src/share/classes/java/lang/invoke/MethodHandleProxies.java index 641f2eeea510099a234ffe0364ea05ab8984f4e0..246160cabafdb8879432423b6367348bd18d789f 100644 --- a/src/share/classes/java/lang/invoke/MethodHandleProxies.java +++ b/src/share/classes/java/lang/invoke/MethodHandleProxies.java @@ -108,8 +108,9 @@ public class MethodHandleProxies { * Future versions of this API may also equip wrapper instances * with one or more additional public "marker" interfaces. * + * @param the desired type of the wrapper, a single-method interface + * @param intfc a class object representing {@code T} * @param target the method handle to invoke from the wrapper - * @param intfc the desired type of the wrapper, a single-method interface * @return a correctly-typed wrapper for the given target * @throws NullPointerException if either argument is null * @throws IllegalArgumentException if the {@code intfc} is not a diff --git a/src/share/classes/java/lang/invoke/MethodHandles.java b/src/share/classes/java/lang/invoke/MethodHandles.java index d37c8e947d8816a655ddccfdc45ddfd01a95c9d0..3bf24bc85039cd16630bd7bde128af127532eea0 100644 --- a/src/share/classes/java/lang/invoke/MethodHandles.java +++ b/src/share/classes/java/lang/invoke/MethodHandles.java @@ -70,6 +70,7 @@ public class MethodHandles { * including direct method handles to private fields and methods. * This lookup object is a capability which may be delegated to trusted agents. * Do not store it in place where untrusted code can access it. + * @return a lookup object for the caller of this method */ @CallerSensitive public static Lookup lookup() { @@ -88,6 +89,7 @@ public class MethodHandles { * {@linkplain Lookup#in publicLookup().in(C.class)}. * Since all classes have equal access to public names, * such a change would confer no new access rights. + * @return a lookup object which is trusted minimally */ public static Lookup publicLookup() { return Lookup.PUBLIC_LOOKUP; @@ -111,72 +113,74 @@ public class MethodHandles { * on the {@code Lookup} object to create method handles for access-checked members. * This includes all methods, constructors, and fields which are allowed to the lookup class, * even private ones. - *

+ * + *

Lookup Factory Methods

* The factory methods on a {@code Lookup} object correspond to all major * use cases for methods, constructors, and fields. * Here is a summary of the correspondence between these factory methods and * the behavior the resulting method handles: - * *
QSLink-time checksCapture-time checks
PrimitivePrimitive
* * - * - * + * + * * * - * - * + * + * * * - * - * + * + * * * - * - * + * + * * * - * - * + * + * * * - * - * + * + * * * - * - * + * + * * * - * - * + * + * * * - * - * + * + * * * - * - * + * + * * * - * - * + * + * * * - * - * + * + * * * - * - * + * + * * *
lookup expressionmemberbehavior
{@linkplain java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}FT f;(T) this.f;{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}{@code FT f;}{@code (T) this.f;}
{@linkplain java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}static
FT f;
(T) C.f;{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}{@code static}
{@code FT f;}
{@code (T) C.f;}
{@linkplain java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}FT f;this.f = x;{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}{@code FT f;}{@code this.f = x;}
{@linkplain java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}static
FT f;
C.f = arg;{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}{@code static}
{@code FT f;}
{@code C.f = arg;}
{@linkplain java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}T m(A*);(T) this.m(arg*);{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}{@code T m(A*);}{@code (T) this.m(arg*);}
{@linkplain java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}static
T m(A*);
(T) C.m(arg*);{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}{@code static}
{@code T m(A*);}
{@code (T) C.m(arg*);}
{@linkplain java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}T m(A*);(T) super.m(arg*);{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}{@code T m(A*);}{@code (T) super.m(arg*);}
{@linkplain java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}C(A*);(T) new C(arg*);{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}{@code C(A*);}{@code new C(arg*);}
{@linkplain java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}(static)?
FT f;
(FT) aField.get(thisOrNull);{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}({@code static})?
{@code FT f;}
{@code (FT) aField.get(thisOrNull);}
{@linkplain java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}(static)?
FT f;
aField.set(thisOrNull, arg);{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}({@code static})?
{@code FT f;}
{@code aField.set(thisOrNull, arg);}
{@linkplain java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}(static)?
T m(A*);
(T) aMethod.invoke(thisOrNull, arg*);{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}({@code static})?
{@code T m(A*);}
{@code (T) aMethod.invoke(thisOrNull, arg*);}
{@linkplain java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}C(A*);(C) aConstructor.newInstance(arg*);{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}{@code C(A*);}{@code (C) aConstructor.newInstance(arg*);}
{@linkplain java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}(static)?
T m(A*);
(T) aMethod.invoke(thisOrNull, arg*);{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}({@code static})?
{@code T m(A*);}
{@code (T) aMethod.invoke(thisOrNull, arg*);}
- * + * * Here, the type {@code C} is the class or interface being searched for a member, * documented as a parameter named {@code refc} in the lookup methods. - * The method or constructor type {@code MT} is composed from the return type {@code T} + * The method type {@code MT} is composed from the return type {@code T} * and the sequence of argument types {@code A*}. + * The constructor also has a sequence of argument types {@code A*} and + * is deemed to return the newly-created object of type {@code C}. * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. * The formal parameter {@code this} stands for the self-reference of type {@code C}; * if it is present, it is always the leading argument to the method handle invocation. @@ -210,7 +214,7 @@ public class MethodHandles { * security manager checks. * * - *

Access checking

+ *

Access checking

* Access checks are applied in the factory methods of {@code Lookup}, * when a method handle is created. * This is a key difference from the Core Reflection API, since @@ -297,7 +301,7 @@ public class MethodHandles { * with static methods of {@link MethodHandles}, * independently of any {@code Lookup} object. * - *

Security manager interactions

+ *

Security manager interactions

* * If a security manager is present, member lookups are subject to * additional checks. @@ -388,6 +392,7 @@ public class MethodHandles { * but the permissions may be additionally limited by the bitmask * {@link #lookupModes lookupModes}, which controls whether non-public members * can be accessed. + * @return the lookup class, on behalf of which this lookup object finds members */ public Class lookupClass() { return lookupClass; @@ -414,6 +419,7 @@ public class MethodHandles { * The purpose of this is to restrict access via the new lookup object, * so that it can access only names which can be reached by the original * lookup object, and also by the new lookup class. + * @return the lookup modes, which limit the kinds of access performed by this lookup object */ public int lookupModes() { return allowedModes & ALL_MODES; @@ -1352,6 +1358,7 @@ return mh1; * The type of the method handle will have a void return type. * Its last argument will be the array's element type. * The first and second arguments will be the array type and int. + * @param arrayClass the class of an array * @return a method handle which can store values into the array type * @throws NullPointerException if the argument is null * @throws IllegalArgumentException if arrayClass is not an array type @@ -1580,12 +1587,12 @@ import static java.lang.invoke.MethodType.*; ... MethodType intfn1 = methodType(int.class, int.class); MethodType intfn2 = methodType(int.class, int.class, int.class); -MethodHandle sub = ... {int x, int y => x-y} ...; +MethodHandle sub = ... (int x, int y) -> (x-y) ...; assert(sub.type().equals(intfn2)); MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); assert((int)rsub.invokeExact(1, 100) == 99); -MethodHandle add = ... {int x, int y => x+y} ...; +MethodHandle add = ... (int x, int y) -> (x+y) ...; assert(add.type().equals(intfn2)); MethodHandle twice = permuteArguments(add, intfn1, 0, 0); assert(twice.type().equals(intfn1)); @@ -2261,6 +2268,8 @@ assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); * The method type will nominally specify a return of {@code returnType}. * The return type may be anything convenient: It doesn't matter to the * method handle's behavior, since it will never return normally. + * @param returnType the return type of the desired method handle + * @param exType the parameter type of the desired method handle * @return method handle which can throw the given exceptions * @throws NullPointerException if either argument is null */ diff --git a/src/share/classes/java/lang/invoke/MethodType.java b/src/share/classes/java/lang/invoke/MethodType.java index 7c9f2450840b430552545b591d1ce15c76c6c6e3..f55479f1345a784007b9f4e6896345aa9392df15 100644 --- a/src/share/classes/java/lang/invoke/MethodType.java +++ b/src/share/classes/java/lang/invoke/MethodType.java @@ -194,6 +194,8 @@ class MethodType implements java.io.Serializable { /** * Finds or creates a method type with the given components. * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. + * @param rtype the return type + * @param ptypes the parameter types * @return a method type with the given components * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class} @@ -214,6 +216,9 @@ class MethodType implements java.io.Serializable { * Finds or creates a method type with the given components. * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. * The leading parameter type is prepended to the remaining array. + * @param rtype the return type + * @param ptype0 the first parameter type + * @param ptypes the remaining parameter types * @return a method type with the given components * @throws NullPointerException if {@code rtype} or {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is null * @throws IllegalArgumentException if {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is {@code void.class} @@ -230,6 +235,7 @@ class MethodType implements java.io.Serializable { * Finds or creates a method type with the given components. * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. * The resulting method has no parameter types. + * @param rtype the return type * @return a method type with the given return value * @throws NullPointerException if {@code rtype} is null */ @@ -242,6 +248,8 @@ class MethodType implements java.io.Serializable { * Finds or creates a method type with the given components. * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. * The resulting method has the single given parameter type. + * @param rtype the return type + * @param ptype0 the parameter type * @return a method type with the given return value and parameter type * @throws NullPointerException if {@code rtype} or {@code ptype0} is null * @throws IllegalArgumentException if {@code ptype0} is {@code void.class} @@ -256,6 +264,9 @@ class MethodType implements java.io.Serializable { * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. * The resulting method has the same parameter types as {@code ptypes}, * and the specified return type. + * @param rtype the return type + * @param ptypes the method type which supplies the parameter types + * @return a method type with the given components * @throws NullPointerException if {@code rtype} or {@code ptypes} is null */ public static @@ -938,7 +949,8 @@ s.writeObject(this.parameterArray()); * provided to the factory method {@link #methodType(Class,Class[]) methodType}. * For example, null values, or {@code void} parameter types, * will lead to exceptions during deserialization. - * @param the stream to write the object to + * @param s the stream to write the object to + * @throws java.io.IOException if there is a problem writing the object */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.defaultWriteObject(); // requires serialPersistentFields to be an empty array @@ -953,7 +965,9 @@ s.writeObject(this.parameterArray()); * It provides the parameters to the factory method called by * {@link #readResolve readResolve}. * After that call it is discarded. - * @param the stream to read the object from + * @param s the stream to read the object from + * @throws java.io.IOException if there is a problem reading the object + * @throws ClassNotFoundException if one of the component classes cannot be resolved * @see #MethodType() * @see #readResolve * @see #writeObject diff --git a/src/share/classes/java/lang/invoke/MutableCallSite.java b/src/share/classes/java/lang/invoke/MutableCallSite.java index d48f99afefbde21e8eea9a16856286b8e696b7bd..37bd4641484e8a2731618c4f309d1243806900e8 100644 --- a/src/share/classes/java/lang/invoke/MutableCallSite.java +++ b/src/share/classes/java/lang/invoke/MutableCallSite.java @@ -195,7 +195,7 @@ public class MutableCallSite extends CallSite { * processed before the method returns abnormally. * Which elements these are (if any) is implementation-dependent. * - *

Java Memory Model details

+ *

Java Memory Model details

* In terms of the Java Memory Model, this operation performs a synchronization * action which is comparable in effect to the writing of a volatile variable * by the current thread, and an eventual volatile read by every other thread diff --git a/src/share/classes/java/lang/invoke/SerializedLambda.java b/src/share/classes/java/lang/invoke/SerializedLambda.java index 3679e3f726d91716277a1e56db0cd595e0367e88..558fa5ab6ee98610f5a13a257cdae9a27655a819 100644 --- a/src/share/classes/java/lang/invoke/SerializedLambda.java +++ b/src/share/classes/java/lang/invoke/SerializedLambda.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -97,66 +97,113 @@ public final class SerializedLambda implements Serializable { this.capturedArgs = Objects.requireNonNull(capturedArgs).clone(); } - /** Get the name of the class that captured this lambda */ + /** + * Get the name of the class that captured this lambda. + * @return the name of the class that captured this lambda + */ public String getCapturingClass() { return capturingClass.getName().replace('.', '/'); } - /** Get the name of the functional interface class to which this lambda has been converted */ + /** + * Get the name of the functional interface class to which this + * lambda has been converted + * @return the name of the functional interface this lambda has + * been converted to + */ public String getFunctionalInterfaceClass() { return functionalInterfaceClass; } - /** Get the name of the primary method for the functional interface to which this lambda has been converted */ + /** + * Get the name of the primary method for the functional interface + * to which this lambda has been converted. + * @return the name of the primary methods of the functional interface + */ public String getFunctionalInterfaceMethodName() { return functionalInterfaceMethodName; } - /** Get the signature of the primary method for the functional interface to which this lambda has been converted */ + /** + * Get the signature of the primary method for the functional + * interface to which this lambda has been converted. + * @return the signature of the primary method of the functional + * interface + */ public String getFunctionalInterfaceMethodSignature() { return functionalInterfaceMethodSignature; } - /** Get the method handle kind (see {@link MethodHandleInfo}) of the primary method for the functional interface - * to which this lambda has been converted */ + /** + * Get the method handle kind (see {@link MethodHandleInfo}) of + * the primary method for the functional interface to which this + * lambda has been converted + * @return the method handle kind of the primary method of + * functional interface + */ public int getFunctionalInterfaceMethodKind() { return functionalInterfaceMethodKind; } - /** Get the name of the class containing the implementation method */ + /** + * Get the name of the class containing the implementation + * method. + * @return the name of the class containing the implementation + * method + */ public String getImplClass() { return implClass; } - /** Get the name of the implementation method */ + /** + * Get the name of the implementation method. + * @return the name of the implementation method + */ public String getImplMethodName() { return implMethodName; } - /** Get the signature of the implementation method */ + /** + * Get the signature of the implementation method. + * @return the signature of the implementation method + */ public String getImplMethodSignature() { return implMethodSignature; } - /** Get the method handle kind (see {@link MethodHandleInfo}) of the implementation method */ + /** + * Get the method handle kind (see {@link MethodHandleInfo}) of + * the implementation method. + * @return the method handle kind of the implementation method + */ public int getImplMethodKind() { return implMethodKind; } /** - * Get the signature of the primary functional interface method after type variables are substituted with - * their instantiation from the capture site + * Get the signature of the primary functional interface method + * after type variables are substituted with their instantiation + * from the capture site. + * @return the signature of the primary functional interface method + * after type variable processing */ public final String getInstantiatedMethodType() { return instantiatedMethodType; } - /** Get the count of dynamic arguments to the lambda capture site */ + /** + * Get the count of dynamic arguments to the lambda capture site. + * @return the count of dynamic arguments to the lambda capture site + */ public int getCapturedArgCount() { return capturedArgs.length; } - /** Get a dynamic argument to the lambda capture site */ + /** + * Get a dynamic argument to the lambda capture site. + * @param i the argument to capture + * @return a dynamic argument to the lambda capture site + */ public Object getCapturedArg(int i) { return capturedArgs[i]; } diff --git a/src/share/classes/java/lang/invoke/package-info.java b/src/share/classes/java/lang/invoke/package-info.java index 880bf54021f622ae72f6a067818a672f5c282ffb..51fc21c3f7760841e8d90f870c45e96736ab6fb0 100644 --- a/src/share/classes/java/lang/invoke/package-info.java +++ b/src/share/classes/java/lang/invoke/package-info.java @@ -43,13 +43,13 @@ * * * - *

Summary of relevant Java Virtual Machine changes

+ *

Summary of relevant Java Virtual Machine changes

* The following low-level information summarizes relevant parts of the * Java Virtual Machine specification. For full details, please see the * current version of that specification. * * Each occurrence of an {@code invokedynamic} instruction is called a dynamic call site. - *

{@code invokedynamic} instructions

+ *

{@code invokedynamic} instructions

* A dynamic call site is originally in an unlinked state. In this state, there is * no target method for the call site to invoke. *

@@ -97,7 +97,7 @@ * If this happens, the same error will the thrown for all subsequent * attempts to execute the dynamic call site. * - *

timing of linkage

+ *

timing of linkage

* A dynamic call site is linked just before its first execution. * The bootstrap method call implementing the linkage occurs within * a thread that is attempting a first execution. @@ -131,7 +131,7 @@ * just before its first invocation. * There is no way to undo the effect of a completed bootstrap method call. * - *

types of bootstrap methods

+ *

types of bootstrap methods

* As long as each bootstrap method can be correctly invoked * by {@code MethodHandle.invoke}, its detailed type is arbitrary. * For example, the first argument could be {@code Object} diff --git a/src/share/classes/java/math/BigDecimal.java b/src/share/classes/java/math/BigDecimal.java index d2a449223788b216af347c029ae0693cd82ea5f9..944f8a79fbe9faf983b9e1a01d613e768b10b2e2 100644 --- a/src/share/classes/java/math/BigDecimal.java +++ b/src/share/classes/java/math/BigDecimal.java @@ -2572,6 +2572,9 @@ public class BigDecimal extends Number implements Comparable { * ({@code this} * 10n). The scale of * the result is {@code (this.scale() - n)}. * + * @param n the exponent power of ten to scale by + * @return a BigDecimal whose numerical value is equal to + * ({@code this} * 10n) * @throws ArithmeticException if the scale would be * outside the range of a 32-bit integer. * diff --git a/src/share/classes/java/math/BigInteger.java b/src/share/classes/java/math/BigInteger.java index 8972ac76ef9e054a6e6339cac16aa268062444a5..6569fcb1796b25bfe8f9fa843107986b5f9b2bf5 100644 --- a/src/share/classes/java/math/BigInteger.java +++ b/src/share/classes/java/math/BigInteger.java @@ -33,6 +33,7 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; +import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import sun.misc.DoubleConsts; @@ -213,6 +214,16 @@ public class BigInteger extends Number implements Comparable { */ private static final int TOOM_COOK_SQUARE_THRESHOLD = 140; + /** + * The threshold value for using Schoenhage recursive base conversion. If + * the number of ints in the number are larger than this value, + * the Schoenhage algorithm will be used. In practice, it appears that the + * Schoenhage routine is faster for any threshold down to 2, and is + * relatively flat for thresholds between 2-25, so this choice may be + * varied within this range for very small effect. + */ + private static final int SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 8; + //Constructors /** @@ -1026,6 +1037,19 @@ public class BigInteger extends Number implements Comparable { private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1]; private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1]; + /** + * The cache of powers of each radix. This allows us to not have to + * recalculate powers of radix^(2^n) more than once. This speeds + * Schoenhage recursive base conversion significantly. + */ + private static volatile BigInteger[][] powerCache; + + /** The cache of logarithms of radices for base conversion. */ + private static final double[] logCache; + + /** The natural log of 2. This is used in computing cache indices. */ + private static final double LOG_TWO = Math.log(2.0); + static { for (int i = 1; i <= MAX_CONSTANT; i++) { int[] magnitude = new int[1]; @@ -1033,6 +1057,20 @@ public class BigInteger extends Number implements Comparable { posConst[i] = new BigInteger(magnitude, 1); negConst[i] = new BigInteger(magnitude, -1); } + + /* + * Initialize the cache of radix^(2^x) values used for base conversion + * with just the very first value. Additional values will be created + * on demand. + */ + powerCache = new BigInteger[Character.MAX_RADIX+1][]; + logCache = new double[Character.MAX_RADIX+1]; + + for (int i=Character.MIN_RADIX; i<=Character.MAX_RADIX; i++) + { + powerCache[i] = new BigInteger[] { BigInteger.valueOf(i) }; + logCache[i] = Math.log(i); + } } /** @@ -1357,7 +1395,7 @@ public class BigInteger extends Number implements Comparable { if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) return multiplyKaratsuba(this, val); else - return multiplyToomCook3(this, val); + return multiplyToomCook3(this, val); } private static BigInteger multiplyByInt(int[] x, int y, int sign) { @@ -3299,6 +3337,28 @@ public class BigInteger extends Number implements Comparable { if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) radix = 10; + // If it's small enough, use smallToString. + if (mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) + return smallToString(radix); + + // Otherwise use recursive toString, which requires positive arguments. + // The results will be concatenated into this StringBuilder + StringBuilder sb = new StringBuilder(); + if (signum < 0) { + toString(this.negate(), sb, radix, 0); + sb.insert(0, '-'); + } + else + toString(this, sb, radix, 0); + + return sb.toString(); + } + + /** This method is used to perform toString when arguments are small. */ + private String smallToString(int radix) { + if (signum == 0) + return "0"; + // Compute upper bound on number of digit groups and allocate space int maxNumDigitGroups = (4*mag.length + 6)/7; String digitGroup[] = new String[maxNumDigitGroups]; @@ -3337,6 +3397,81 @@ public class BigInteger extends Number implements Comparable { return buf.toString(); } + /** + * Converts the specified BigInteger to a string and appends to + * sb. This implements the recursive Schoenhage algorithm + * for base conversions. + *

+ * See Knuth, Donald, _The Art of Computer Programming_, Vol. 2, + * Answers to Exercises (4.4) Question 14. + * + * @param u The number to convert to a string. + * @param sb The StringBuilder that will be appended to in place. + * @param radix The base to convert to. + * @param digits The minimum number of digits to pad to. + */ + private static void toString(BigInteger u, StringBuilder sb, int radix, + int digits) { + /* If we're smaller than a certain threshold, use the smallToString + method, padding with leading zeroes when necessary. */ + if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) { + String s = u.smallToString(radix); + + // Pad with internal zeros if necessary. + // Don't pad if we're at the beginning of the string. + if ((s.length() < digits) && (sb.length() > 0)) + for (int i=s.length(); i + * This could be changed to a more complicated caching method using + * Future. + */ + private static BigInteger getRadixConversionCache(int radix, int exponent) { + BigInteger[] cacheLine = powerCache[radix]; // volatile read + if (exponent < cacheLine.length) { + return cacheLine[exponent]; + } + + int oldLength = cacheLine.length; + cacheLine = Arrays.copyOf(cacheLine, exponent + 1); + for (int i = oldLength; i <= exponent; i++) { + cacheLine[i] = cacheLine[i - 1].pow(2); + } + + BigInteger[][] pc = powerCache; // volatile read again + if (exponent >= pc[radix].length) { + pc = pc.clone(); + pc[radix] = cacheLine; + powerCache = pc; // volatile write, publish + } + return cacheLine[exponent]; + } /* zero[i] is a string of i consecutive zeros. */ private static String zeros[] = new String[64]; diff --git a/src/share/classes/java/math/RoundingMode.java b/src/share/classes/java/math/RoundingMode.java index 69994a4c316c51146deb93f03f3aded2530b9d94..41493a200e267e3be9a63a093c8870f2761063a1 100644 --- a/src/share/classes/java/math/RoundingMode.java +++ b/src/share/classes/java/math/RoundingMode.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -101,6 +101,7 @@ public enum RoundingMode { * *

Example: * + * * * @@ -124,6 +125,7 @@ public enum RoundingMode { * *

Example: *

Rounding mode UP Examples
Input NumberInput rounded to one digit
with {@code UP} rounding *
5.5 6
+ * * * @@ -148,6 +150,7 @@ public enum RoundingMode { * *

Example: *

Rounding mode DOWN Examples
Input NumberInput rounded to one digit
with {@code DOWN} rounding *
5.5 5
+ * * * @@ -172,6 +175,7 @@ public enum RoundingMode { * *

Example: *

Rounding mode CEILING Examples
Input NumberInput rounded to one digit
with {@code CEILING} rounding *
5.5 6
+ * * * @@ -198,6 +202,7 @@ public enum RoundingMode { * *

Example: *

Rounding mode FLOOR Examples
Input NumberInput rounded to one digit
with {@code FLOOR} rounding *
5.5 5
+ * * * @@ -223,6 +228,7 @@ public enum RoundingMode { * *

Example: *

Rounding mode HALF_UP Examples
Input NumberInput rounded to one digit
with {@code HALF_UP} rounding *
5.5 6
+ * * * @@ -255,6 +261,7 @@ public enum RoundingMode { * *

Example: *

Rounding mode HALF_DOWN Examples
Input NumberInput rounded to one digit
with {@code HALF_DOWN} rounding *
5.5 5
+ * * * @@ -278,6 +285,7 @@ public enum RoundingMode { * {@code ArithmeticException} is thrown. *

Example: *

Rounding mode HALF_EVEN Examples
Input NumberInput rounded to one digit
with {@code HALF_EVEN} rounding *
5.5 6
+ * * * diff --git a/src/share/classes/java/nio/Buffer.java b/src/share/classes/java/nio/Buffer.java index 068444a975842dedfe120af02da1bd1cb50e90c9..f5a9cd4f6754332969b73ded55201e0636a8d319 100644 --- a/src/share/classes/java/nio/Buffer.java +++ b/src/share/classes/java/nio/Buffer.java @@ -52,7 +52,7 @@ import java.util.Spliterator; *

There is one subclass of this class for each non-boolean primitive type. * * - *

Transferring data

+ *

Transferring data

* *

Each subclass of this class defines two categories of get and * put operations:

@@ -78,7 +78,7 @@ import java.util.Spliterator; * current position. * * - *

Marking and resetting

+ *

Marking and resetting

* *

A buffer's mark is the index to which its position will be reset * when the {@link #reset reset} method is invoked. The mark is not always @@ -89,7 +89,7 @@ import java.util.Spliterator; * {@link InvalidMarkException} to be thrown. * * - *

Invariants

+ *

Invariants

* *

The following invariant holds for the mark, position, limit, and * capacity values: @@ -109,7 +109,7 @@ import java.util.Spliterator; * to zero. * * - *

Clearing, flipping, and rewinding

+ *

Clearing, flipping, and rewinding

* *

In addition to methods for accessing the position, limit, and capacity * values and for marking and resetting, this class also defines the following @@ -132,7 +132,7 @@ import java.util.Spliterator; * * * - *

Read-only buffers

+ *

Read-only buffers

* *

Every buffer is readable, but not every buffer is writable. The * mutation methods of each buffer class are specified as optional @@ -143,14 +143,14 @@ import java.util.Spliterator; * {@link #isReadOnly isReadOnly} method. * * - *

Thread safety

+ *

Thread safety

* *

Buffers are not safe for use by multiple concurrent threads. If a * buffer is to be used by more than one thread then access to the buffer * should be controlled by appropriate synchronization. * * - *

Invocation chaining

+ *

Invocation chaining

* *

Methods in this class that do not otherwise have a value to return are * specified to return the buffer upon which they are invoked. This allows diff --git a/src/share/classes/java/nio/CharBufferSpliterator.java b/src/share/classes/java/nio/CharBufferSpliterator.java index 19fd8a8f0ba8b858239f107d56769fc12b535b07..5b3977ae7646f2740e3dc2c9ae4b7e10651a4df5 100644 --- a/src/share/classes/java/nio/CharBufferSpliterator.java +++ b/src/share/classes/java/nio/CharBufferSpliterator.java @@ -5,7 +5,7 @@ * This code is free software; you can redistribute 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 + * 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 diff --git a/src/share/classes/java/nio/MappedByteBuffer.java b/src/share/classes/java/nio/MappedByteBuffer.java index 1d26276f10c344322684b9698a5282b0bd1037b2..25aa60e0b104663068f24bc8f0c7d401ab56aea0 100644 --- a/src/share/classes/java/nio/MappedByteBuffer.java +++ b/src/share/classes/java/nio/MappedByteBuffer.java @@ -45,7 +45,7 @@ import sun.misc.Unsafe; * this program or another. Whether or not such changes occur, and when they * occur, is operating-system dependent and therefore unspecified. * - *

All or part of a mapped byte buffer may become + *

All or part of a mapped byte buffer may become * inaccessible at any time, for example if the mapped file is truncated. An * attempt to access an inaccessible region of a mapped byte buffer will not * change the buffer's content and will cause an unspecified exception to be diff --git a/src/share/classes/java/nio/X-Buffer.java.template b/src/share/classes/java/nio/X-Buffer.java.template index c3037adb4d29973f883bc33904138f6b7ad7ffd8..03a7255c16a477dbf52044cf6e41391456b4bc17 100644 --- a/src/share/classes/java/nio/X-Buffer.java.template +++ b/src/share/classes/java/nio/X-Buffer.java.template @@ -44,23 +44,23 @@ import java.util.stream.$Streamtype$Stream; * *

    * - *
  • Absolute and relative {@link #get() get} and - * {@link #put($type$) put} methods that read and write + *

  • Absolute and relative {@link #get() get} and + * {@link #put($type$) put} methods that read and write * single $type$s;

  • * - *
  • Relative {@link #get($type$[]) bulk get} + *

  • Relative {@link #get($type$[]) bulk get} * methods that transfer contiguous sequences of $type$s from this buffer * into an array; {#if[!byte]?and}

  • * - *
  • Relative {@link #put($type$[]) bulk put} + *

  • Relative {@link #put($type$[]) bulk put} * methods that transfer contiguous sequences of $type$s from $a$ * $type$ array{#if[char]?, a string,} or some other $type$ * buffer into this buffer;{#if[!byte]? and}

  • * #if[byte] * - *
  • Absolute and relative {@link #getChar() get} - * and {@link #putChar(char) put} methods that read and + *

  • Absolute and relative {@link #getChar() get} + * and {@link #putChar(char) put} methods that read and * write values of other primitive types, translating them to and from * sequences of bytes in a particular byte order;

  • * @@ -70,23 +70,23 @@ import java.util.stream.$Streamtype$Stream; * #end[byte] * - *
  • Methods for {@link #compact compacting}, {@link - * #duplicate duplicating}, and {@link #slice - * slicing} $a$ $type$ buffer.

  • + *
  • Methods for {@link #compact compacting}, {@link + * #duplicate duplicating}, and {@link #slice slicing} + * $a$ $type$ buffer.

  • * *
* *

$Type$ buffers can be created either by {@link #allocate - * allocation}, which allocates space for the buffer's + * allocation}, which allocates space for the buffer's * #if[byte] * - * content, or by {@link #wrap($type$[]) wrapping} an + * content, or by {@link #wrap($type$[]) wrapping} an * existing $type$ array {#if[char]?or string} into a buffer. * #else[byte] * - * content, by {@link #wrap($type$[]) wrapping} an existing + * content, by {@link #wrap($type$[]) wrapping} an existing * $type$ array {#if[char]?or string} into a buffer, or by creating a * view of an existing byte buffer. * @@ -94,8 +94,8 @@ import java.util.stream.$Streamtype$Stream; * #if[byte] * - * - *

Direct vs. non-direct buffers

+ * + *

Direct vs. non-direct buffers

* *

A byte buffer is either direct or non-direct. Given a * direct byte buffer, the Java virtual machine will make a best effort to @@ -116,7 +116,7 @@ import java.util.stream.$Streamtype$Stream; * buffers only when they yield a measureable gain in program performance. * *

A direct byte buffer may also be created by {@link - * java.nio.channels.FileChannel#map mapping} a region of a file + * java.nio.channels.FileChannel#map mapping} a region of a file * directly into memory. An implementation of the Java platform may optionally * support the creation of direct byte buffers from native code via JNI. If an * instance of one of these kinds of buffers refers to an inaccessible region @@ -129,8 +129,8 @@ import java.util.stream.$Streamtype$Stream; * that explicit buffer management can be done in performance-critical code. * * - * - *

Access to binary data

+ * + *

Access to binary data

* *

This class defines methods for reading and writing values of all other * primitive types, except boolean. Primitive values are translated @@ -156,7 +156,7 @@ import java.util.stream.$Streamtype$Stream; * parameters of the absolute get and put methods are in terms of * bytes rather than of the type being read or written. * - * + * * *

For access to homogeneous binary data, that is, sequences of values of * the same type, this class defines methods that can create views of a @@ -214,7 +214,7 @@ import java.util.stream.$Streamtype$Stream; #end[char] * #if[byte] - *

Invocation chaining

+ *

Invocation chaining

#end[byte] * *

Methods in this class that do not otherwise have a value to return are @@ -297,7 +297,7 @@ public abstract class $Type$Buffer *

The new buffer's position will be zero, its limit will be its * capacity, its mark will be undefined, and each of its elements will be * initialized to zero. Whether or not it has a - * {@link #hasArray backing array} is unspecified. + * {@link #hasArray backing array} is unspecified. * * @param capacity * The new buffer's capacity, in $type$s @@ -318,9 +318,8 @@ public abstract class $Type$Buffer * *

The new buffer's position will be zero, its limit will be its * capacity, its mark will be undefined, and each of its elements will be - * initialized to zero. It will have a {@link #array - * backing array}, and its {@link #arrayOffset array - * offset} will be zero. + * initialized to zero. It will have a {@link #array backing array}, + * and its {@link #arrayOffset array offset} will be zero. * * @param capacity * The new buffer's capacity, in $type$s @@ -344,8 +343,8 @@ public abstract class $Type$Buffer * and vice versa. The new buffer's capacity will be * array.length, its position will be offset, its limit * will be offset + length, and its mark will be undefined. Its - * {@link #array backing array} will be the given array, and - * its {@link #arrayOffset array offset} will be zero.

+ * {@link #array backing array} will be the given array, and + * its {@link #arrayOffset array offset} will be zero.

* * @param array * The array that will back the new buffer @@ -384,8 +383,8 @@ public abstract class $Type$Buffer * that is, modifications to the buffer will cause the array to be modified * and vice versa. The new buffer's capacity and limit will be * array.length, its position will be zero, and its mark will be - * undefined. Its {@link #array
backing array} will be the - * given array, and its {@link #arrayOffset array offset} will + * undefined. Its {@link #array backing array} will be the + * given array, and its {@link #arrayOffset array offset>} will * be zero.

* * @param array @@ -703,6 +702,9 @@ public abstract class $Type$Buffer *
      *     src.get(a, 0, a.length) 
* + * @param dst + * The destination array + * * @return This buffer * * @throws BufferUnderflowException @@ -842,6 +844,9 @@ public abstract class $Type$Buffer *
      *     dst.put(a, 0, a.length) 
* + * @param src + * The source array + * * @return This buffer * * @throws BufferOverflowException @@ -930,6 +935,9 @@ public abstract class $Type$Buffer *
      *     dst.put(s, 0, s.length()) 
* + * @param src + * The source string + * * @return This buffer * * @throws BufferOverflowException @@ -1419,7 +1427,7 @@ public abstract class $Type$Buffer * *

The byte order of $a$ $type$ buffer created by allocation or by * wrapping an existing $type$ array is the {@link - * ByteOrder#nativeOrder native order} of the underlying + * ByteOrder#nativeOrder native order} of the underlying * hardware. The byte order of $a$ $type$ buffer created as a view of a byte buffer is that of the * byte buffer at the moment that the view is created.

diff --git a/src/share/classes/java/nio/channels/AsynchronousByteChannel.java b/src/share/classes/java/nio/channels/AsynchronousByteChannel.java index 9fdf7530d16aed6f412898b6c4b7ac6d20d3c1c5..47ffc87a80b6ad856c62e91aa03f5bd5cf18b62b 100644 --- a/src/share/classes/java/nio/channels/AsynchronousByteChannel.java +++ b/src/share/classes/java/nio/channels/AsynchronousByteChannel.java @@ -87,6 +87,8 @@ public interface AsynchronousByteChannel * initiates a read operation before a previous read operation has * completed then a {@link ReadPendingException} will be thrown. * + * @param + * The type of the attachment * @param dst * The buffer into which bytes are to be transferred * @param attachment @@ -166,6 +168,8 @@ public interface AsynchronousByteChannel * initiates a write operation before a previous write operation has * completed then a {@link WritePendingException} will be thrown. * + * @param + * The type of the attachment * @param src * The buffer from which bytes are to be retrieved * @param attachment diff --git a/src/share/classes/java/nio/channels/AsynchronousChannel.java b/src/share/classes/java/nio/channels/AsynchronousChannel.java index 5aa9fe23b3840ec1a4c6244efa96abc7c5429614..98e30d05e79b6082aa46852b747454f81ddd16ad 100644 --- a/src/share/classes/java/nio/channels/AsynchronousChannel.java +++ b/src/share/classes/java/nio/channels/AsynchronousChannel.java @@ -61,7 +61,7 @@ import java.util.concurrent.Future; // javadoc * may not allow more than one read and one write operation to be outstanding at * any given time. * - *

Cancellation

+ *

Cancellation

* *

The {@code Future} interface defines the {@link Future#cancel cancel} * method to cancel execution. This causes all threads waiting on the result of diff --git a/src/share/classes/java/nio/channels/AsynchronousChannelGroup.java b/src/share/classes/java/nio/channels/AsynchronousChannelGroup.java index 2eb4b5219d20137b8356f0be6c9f5f80c62cdbeb..ace607323cbc2e65d688cd4e2a22d5b8fc4c26e1 100644 --- a/src/share/classes/java/nio/channels/AsynchronousChannelGroup.java +++ b/src/share/classes/java/nio/channels/AsynchronousChannelGroup.java @@ -60,7 +60,7 @@ import java.util.concurrent.TimeUnit; * default group is not configured then the pooled threads of the default group * are {@link Thread#isDaemon daemon} threads. * - *

Rounding mode UNNECESSARY Examples
Input NumberInput rounded to one digit
with {@code UNNECESSARY} rounding *
5.5 throw {@code ArithmeticException}
+ *
* * * @@ -89,7 +89,7 @@ import java.util.concurrent.TimeUnit; * *
System propertyDescription
* - *

Threading

+ *

Threading

* *

The completion handler for an I/O operation initiated on a channel bound * to a group is guaranteed to be invoked by one of the pooled threads in the @@ -104,7 +104,7 @@ import java.util.concurrent.TimeUnit; * handler directly by the initiating thread (see {@link * AsynchronousServerSocketChannel#accept(Object,CompletionHandler) accept}). * - *

Shutdown and Termination

+ *

Shutdown and Termination

* *

The {@link #shutdown() shutdown} method is used to initiate an orderly * shutdown of a group. An orderly shutdown marks the group as shutdown; diff --git a/src/share/classes/java/nio/channels/AsynchronousFileChannel.java b/src/share/classes/java/nio/channels/AsynchronousFileChannel.java index b1c6e788c5020230dae5f866eb8c151bb6293469..c40fb3762878ad1daeb3bcffa7f2a37a60cee2f8 100644 --- a/src/share/classes/java/nio/channels/AsynchronousFileChannel.java +++ b/src/share/classes/java/nio/channels/AsynchronousFileChannel.java @@ -425,6 +425,8 @@ public abstract class AsynchronousFileChannel * They are not suitable for controlling access to a file by multiple * threads within the same virtual machine. * + * @param + * The type of the attachment * @param position * The position at which the locked region is to start; must be * non-negative @@ -473,6 +475,8 @@ public abstract class AsynchronousFileChannel * ch.{@link #lock(long,long,boolean,Object,CompletionHandler) lock}(0L, Long.MAX_VALUE, false, att, handler) * * + * @param + * The type of the attachment * @param attachment * The object to attach to the I/O operation; can be {@code null} * @param handler @@ -652,6 +656,8 @@ public abstract class AsynchronousFileChannel * If the given file position is greater than the file's size at the time * that the read is attempted then no bytes are read. * + * @param + * The type of the attachment * @param dst * The buffer into which bytes are to be transferred * @param position @@ -716,6 +722,8 @@ public abstract class AsynchronousFileChannel * bytes; the values of any bytes between the previous end-of-file and the * newly-written bytes are unspecified. * + * @param + * The type of the attachment * @param src * The buffer from which bytes are to be transferred * @param position diff --git a/src/share/classes/java/nio/channels/AsynchronousServerSocketChannel.java b/src/share/classes/java/nio/channels/AsynchronousServerSocketChannel.java index 477855572b5872e937445f152b22f90fffa5bf89..75882008bd1eb6ebb4687b8d7b77c3293b764ab6 100644 --- a/src/share/classes/java/nio/channels/AsynchronousServerSocketChannel.java +++ b/src/share/classes/java/nio/channels/AsynchronousServerSocketChannel.java @@ -52,7 +52,7 @@ import java.io.IOException; *

Socket options are configured using the {@link #setOption(SocketOption,Object) * setOption} method. Channels of this type support the following options: *

- * + *
* * * @@ -98,6 +98,9 @@ public abstract class AsynchronousServerSocketChannel /** * Initializes a new instance of this class. + * + * @param provider + * The provider that created this channel */ protected AsynchronousServerSocketChannel(AsynchronousChannelProvider provider) { this.provider = provider; @@ -105,6 +108,8 @@ public abstract class AsynchronousServerSocketChannel /** * Returns the provider that created this channel. + * + * @return The provider that created this channel */ public final AsynchronousChannelProvider provider() { return provider; @@ -263,6 +268,8 @@ public abstract class AsynchronousServerSocketChannel * the connection is closed and the operation completes with a {@link * SecurityException}. * + * @param + * The type of the attachment * @param attachment * The object to attach to the I/O operation; can be {@code null} * @param handler diff --git a/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java b/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java index 74c93c872afc9aff5ad0c2b4686a8e1163935b15..2c2a1a306d5bf5fab5a4c4d52ba970d3dea43256 100644 --- a/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java +++ b/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java @@ -62,7 +62,7 @@ import java.nio.ByteBuffer; *

Socket options are configured using the {@link #setOption(SocketOption,Object) * setOption} method. Asynchronous socket channels support the following options: *

- *
Option NameDescription
+ *
* * * @@ -91,7 +91,7 @@ import java.nio.ByteBuffer; * * Additional (implementation specific) options may also be supported. * - *

Timeouts

+ *

Timeouts

* *

The {@link #read(ByteBuffer,long,TimeUnit,Object,CompletionHandler) read} * and {@link #write(ByteBuffer,long,TimeUnit,Object,CompletionHandler) write} @@ -123,6 +123,9 @@ public abstract class AsynchronousSocketChannel /** * Initializes a new instance of this class. + * + * @param provider + * The provider that created this channel */ protected AsynchronousSocketChannel(AsynchronousChannelProvider provider) { this.provider = provider; @@ -130,6 +133,8 @@ public abstract class AsynchronousSocketChannel /** * Returns the provider that created this channel. + * + * @return The provider that created this channel */ public final AsynchronousChannelProvider provider() { return provider; @@ -287,6 +292,8 @@ public abstract class AsynchronousSocketChannel * java.lang.SecurityManager#checkConnect checkConnect} method permits * connecting to the address and port number of the given remote endpoint. * + * @param + * The type of the attachment * @param remote * The remote address to which this channel is to be connected * @param attachment @@ -365,6 +372,8 @@ public abstract class AsynchronousSocketChannel * AsynchronousByteChannel#read(ByteBuffer,Object,CompletionHandler)} * method. * + * @param + * The type of the attachment * @param dst * The buffer into which bytes are to be transferred * @param timeout @@ -461,6 +470,8 @@ public abstract class AsynchronousSocketChannel * read from the channel will cause an unspecific runtime exception to be * thrown. * + * @param + * The type of the attachment * @param dsts * The buffers into which bytes are to be transferred * @param offset @@ -520,6 +531,8 @@ public abstract class AsynchronousSocketChannel * AsynchronousByteChannel#write(ByteBuffer,Object,CompletionHandler)} * method. * + * @param + * The type of the attachment * @param src * The buffer from which bytes are to be retrieved * @param timeout @@ -610,6 +623,8 @@ public abstract class AsynchronousSocketChannel * to write to the channel will cause an unspecific runtime exception to be * thrown. * + * @param + * The type of the attachment * @param srcs * The buffers from which bytes are to be retrieved * @param offset diff --git a/src/share/classes/java/nio/channels/DatagramChannel.java b/src/share/classes/java/nio/channels/DatagramChannel.java index fd8b920eebdbbc7ee9f3929ba7d725a7d4d3bd98..3626317a9821837cdf1b66db33bf980d983332c5 100644 --- a/src/share/classes/java/nio/channels/DatagramChannel.java +++ b/src/share/classes/java/nio/channels/DatagramChannel.java @@ -57,7 +57,7 @@ import java.nio.channels.spi.SelectorProvider; * setOption} method. A datagram channel to an Internet Protocol socket supports * the following options: *

- *
Option NameDescription
+ *
* * * @@ -117,6 +117,9 @@ public abstract class DatagramChannel /** * Initializes a new instance of this class. + * + * @param provider + * The provider that created this channel */ protected DatagramChannel(SelectorProvider provider) { super(provider); diff --git a/src/share/classes/java/nio/channels/FileChannel.java b/src/share/classes/java/nio/channels/FileChannel.java index 02d9082d2309c1cba86d7f71ecf0304a937acc93..57ce3e10d9ea8970e5040a4d3ad19bd7f3d88167 100644 --- a/src/share/classes/java/nio/channels/FileChannel.java +++ b/src/share/classes/java/nio/channels/FileChannel.java @@ -46,7 +46,7 @@ import java.util.Collections; * of bytes that can be read and written and whose current {@link #size * size} can be queried. The size of the file increases * when bytes are written beyond its current size; the size of the file - * decreases when it is {@link #truncate truncated}. The + * decreases when it is {@link #truncate truncated}. The * file may also have some associated metadata such as access * permissions, content type, and last-modification time; this class does not * define methods for metadata access. @@ -830,7 +830,7 @@ public abstract class FileChannel *

A region of a file may be mapped into memory in one of three modes: *

* - *
    + *
      * *
    • Read-only: Any attempt to modify the resulting buffer * will cause a {@link java.nio.ReadOnlyBufferException} to be thrown. diff --git a/src/share/classes/java/nio/channels/FileLock.java b/src/share/classes/java/nio/channels/FileLock.java index e978af431792c14e16d765f93d2a1668dd492c3c..fb584ee163e35af63dff430adede8d7525fe4454 100644 --- a/src/share/classes/java/nio/channels/FileLock.java +++ b/src/share/classes/java/nio/channels/FileLock.java @@ -72,7 +72,7 @@ import java.io.IOException; *

      File-lock objects are safe for use by multiple concurrent threads. * * - *

      Platform dependencies

      + *

      Platform dependencies

      * *

      This file-locking API is intended to map directly to the native locking * facility of the underlying operating system. Thus the locks held on a file @@ -261,6 +261,11 @@ public abstract class FileLock implements AutoCloseable { /** * Tells whether or not this lock overlaps the given lock range. * + * @param position + * The starting position of the lock range + * @param size + * The size of the lock range + * * @return true if, and only if, this lock and the given lock * range overlap by at least one byte */ diff --git a/src/share/classes/java/nio/channels/MulticastChannel.java b/src/share/classes/java/nio/channels/MulticastChannel.java index 0e06633b51fd57729d4742638b7a2f7d5d10e143..ca17e2415ceffe25b98dbef7f99c392413c86f27 100644 --- a/src/share/classes/java/nio/channels/MulticastChannel.java +++ b/src/share/classes/java/nio/channels/MulticastChannel.java @@ -71,7 +71,7 @@ import java.net.StandardSocketOptions; // javadoc * MembershipKey#drop drop} method drops membership so that datagrams from the * source address can no longer be received. * - *

      Platform dependencies

      + *

      Platform dependencies

      * * The multicast implementation is intended to map directly to the native * multicasting facility. Consequently, the following items should be considered diff --git a/src/share/classes/java/nio/channels/NetworkChannel.java b/src/share/classes/java/nio/channels/NetworkChannel.java index 3900f9d284b19eac10c4fe653ac9b97678eb443a..b56b5e25cce24e073d3da25ada374b337ca7295b 100644 --- a/src/share/classes/java/nio/channels/NetworkChannel.java +++ b/src/share/classes/java/nio/channels/NetworkChannel.java @@ -106,6 +106,8 @@ public interface NetworkChannel /** * Sets the value of a socket option. * + * @param + * The type of the socket option value * @param name * The socket option * @param value @@ -130,6 +132,8 @@ public interface NetworkChannel /** * Returns the value of a socket option. * + * @param + * The type of the socket option value * @param name * The socket option * diff --git a/src/share/classes/java/nio/channels/Pipe.java b/src/share/classes/java/nio/channels/Pipe.java index af0722e99abd4affa434f959d7c0578de0d92c53..4b5a5a51ca71ee5fc21dd7ac7bf2846c613807f3 100644 --- a/src/share/classes/java/nio/channels/Pipe.java +++ b/src/share/classes/java/nio/channels/Pipe.java @@ -33,10 +33,9 @@ import java.nio.channels.spi.*; * A pair of channels that implements a unidirectional pipe. * *

      A pipe consists of a pair of channels: A writable {@link - * Pipe.SinkChannel sink} channel and a readable {@link - * Pipe.SourceChannel source} channel. Once some bytes are - * written to the sink channel they can be read from source channel in exactly - * the order in which they were written. + * Pipe.SinkChannel sink} channel and a readable {@link Pipe.SourceChannel source} + * channel. Once some bytes are written to the sink channel they can be read + * from source channel in exactlyAthe order in which they were written. * *

      Whether or not a thread writing bytes to a pipe will block until another * thread reads those bytes, or some previously-written bytes, from the pipe is @@ -63,6 +62,9 @@ public abstract class Pipe { { /** * Constructs a new instance of this class. + * + * @param provider + * The selector provider */ protected SourceChannel(SelectorProvider provider) { super(provider); @@ -94,6 +96,9 @@ public abstract class Pipe { { /** * Initializes a new instance of this class. + * + * @param provider + * The selector provider */ protected SinkChannel(SelectorProvider provider) { super(provider); diff --git a/src/share/classes/java/nio/channels/SelectableChannel.java b/src/share/classes/java/nio/channels/SelectableChannel.java index 7041c34e188f196bb6fce2fcfa9369e5a662f1b1..17f86831d6dd42c8b7b8f902934ce8dee7bcb85f 100644 --- a/src/share/classes/java/nio/channels/SelectableChannel.java +++ b/src/share/classes/java/nio/channels/SelectableChannel.java @@ -64,8 +64,8 @@ import java.nio.channels.spi.SelectorProvider; * threads.

      * * - * - *

      Blocking mode

      + *
      + *

      Blocking mode

      * * A selectable channel is either in blocking mode or in * non-blocking mode. In blocking mode, every I/O operation invoked @@ -142,6 +142,9 @@ public abstract class SelectableChannel * Retrieves the key representing the channel's registration with the given * selector. * + * @param sel + * The selector + * * @return The key returned when this channel was last registered with the * given selector, or null if this channel is not * currently registered with that selector diff --git a/src/share/classes/java/nio/channels/SelectionKey.java b/src/share/classes/java/nio/channels/SelectionKey.java index 7a0ab88ac3e1f41238254df5890fcc782db79915..e140ee61952d1fb31ce8449dc29f33232c3400b9 100644 --- a/src/share/classes/java/nio/channels/SelectionKey.java +++ b/src/share/classes/java/nio/channels/SelectionKey.java @@ -42,7 +42,7 @@ import java.io.IOException; * next selection operation. The validity of a key may be tested by invoking * its {@link #isValid isValid} method. * - * + * * *

      A selection key contains two operation sets represented as * integer values. Each bit of an operation set denotes a category of diff --git a/src/share/classes/java/nio/channels/Selector.java b/src/share/classes/java/nio/channels/Selector.java index d4c200e694283de36b779850b3e19151f84d4414..3f21727f220cc426423e5e99ba396f94f76ab254 100644 --- a/src/share/classes/java/nio/channels/Selector.java +++ b/src/share/classes/java/nio/channels/Selector.java @@ -36,13 +36,13 @@ import java.util.Set; * *

      A selector may be created by invoking the {@link #open open} method of * this class, which will use the system's default {@link - * java.nio.channels.spi.SelectorProvider selector provider} to + * java.nio.channels.spi.SelectorProvider selector provider} to * create a new selector. A selector may also be created by invoking the * {@link java.nio.channels.spi.SelectorProvider#openSelector openSelector} * method of a custom selector provider. A selector remains open until it is * closed via its {@link #close close} method. * - * + * * *

      A selectable channel's registration with a selector is represented by a * {@link SelectionKey} object. A selector maintains three sets of selection @@ -80,18 +80,18 @@ import java.util.Set; * during the next selection operation, at which time the key will removed from * all of the selector's key sets. * - *

      Keys are added to the selected-key set by selection + *

      Keys are added to the selected-key set by selection * operations. A key may be removed directly from the selected-key set by * invoking the set's {@link java.util.Set#remove(java.lang.Object) remove} * method or by invoking the {@link java.util.Iterator#remove() remove} method - * of an {@link java.util.Iterator iterator} obtained from the + * of an {@link java.util.Iterator iterator} obtained from the * set. Keys are never removed from the selected-key set in any other way; * they are not, in particular, removed as a side effect of selection * operations. Keys may not be added directly to the selected-key set.

      * * - * - *

      Selection

      + *
      + *

      Selection

      * *

      During each selection operation, keys may be added to and removed from a * selector's selected-key set and may be removed from its key and @@ -111,7 +111,7 @@ import java.util.Set; * operation began. For a channel that is ready for at least one such * operation, one of the following two actions is performed:

      * - *
        + *
          * *
        1. If the channel's key is not already in the selected-key set then * it is added to that set and its ready-operation set is modified to @@ -126,7 +126,7 @@ import java.util.Set; * words, the ready set returned by the underlying system is * bitwise-disjoined into the key's current ready set.

        2. * - *
        + *
      * * If all of the keys in the key set at the start of this step have empty * interest sets then neither the selected-key set nor any of the keys' @@ -142,7 +142,7 @@ import java.util.Set; * difference between the three selection methods.

      * * - *

      Concurrency

      + *

      Concurrency

      * *

      Selectors are themselves safe for use by multiple concurrent threads; * their key sets, however, are not. @@ -183,7 +183,7 @@ import java.util.Set; *

      The {@link #close close} method synchronizes on the selector and all * three key sets in the same order as in a selection operation. * - * + * * *

      A selector's key and selected-key sets are not, in general, safe for use * by multiple concurrent threads. If such a thread might modify one of these diff --git a/src/share/classes/java/nio/channels/ServerSocketChannel.java b/src/share/classes/java/nio/channels/ServerSocketChannel.java index 90e39b529a4dece30e03f51d1ac4be8c2ffe6380..aeda90df0319e3ca0c53721c09a6078c6474aa57 100644 --- a/src/share/classes/java/nio/channels/ServerSocketChannel.java +++ b/src/share/classes/java/nio/channels/ServerSocketChannel.java @@ -46,7 +46,7 @@ import java.nio.channels.spi.SelectorProvider; *

      Socket options are configured using the {@link #setOption(SocketOption,Object) * setOption} method. Server-socket channels support the following options: *

      - *
Option NameDescription
+ *
* * * @@ -78,6 +78,9 @@ public abstract class ServerSocketChannel /** * Initializes a new instance of this class. + * + * @param provider + * The provider that created this channel */ protected ServerSocketChannel(SelectorProvider provider) { super(provider); diff --git a/src/share/classes/java/nio/channels/SocketChannel.java b/src/share/classes/java/nio/channels/SocketChannel.java index 6203326490492f2f5db2516631e25c0638c1133e..091570cbf6424ab31464e1dd77a86d9ac56ebcf4 100644 --- a/src/share/classes/java/nio/channels/SocketChannel.java +++ b/src/share/classes/java/nio/channels/SocketChannel.java @@ -66,7 +66,7 @@ import java.nio.channels.spi.SelectorProvider; *

Socket options are configured using the {@link #setOption(SocketOption,Object) * setOption} method. Socket channels support the following options: *

- *
Option NameDescription
+ *
* * * @@ -120,6 +120,9 @@ public abstract class SocketChannel /** * Initializes a new instance of this class. + * + * @param provider + * The provider that created this channel */ protected SocketChannel(SelectorProvider provider) { super(provider); @@ -153,6 +156,8 @@ public abstract class SocketChannel * @param remote * The remote address to which the new channel is to be connected * + * @return A new, and connected, socket channel + * * @throws AsynchronousCloseException * If another thread closes this channel * while the connect operation is in progress diff --git a/src/share/classes/java/nio/channels/spi/AbstractInterruptibleChannel.java b/src/share/classes/java/nio/channels/spi/AbstractInterruptibleChannel.java index a5936832b7a3de05d84dd2865b05dba96c1e53ee..c8400692ee98bc3d628b813d7a57bc37d3b62313 100644 --- a/src/share/classes/java/nio/channels/spi/AbstractInterruptibleChannel.java +++ b/src/share/classes/java/nio/channels/spi/AbstractInterruptibleChannel.java @@ -46,7 +46,7 @@ import sun.nio.ch.Interruptible; * before and after, respectively, invoking an I/O operation that might block * indefinitely. In order to ensure that the {@link #end end} method is always * invoked, these methods should be used within a - * try ... finally block: + * try ... finally block: * *
  * boolean completed = false;
diff --git a/src/share/classes/java/nio/channels/spi/AbstractSelectableChannel.java b/src/share/classes/java/nio/channels/spi/AbstractSelectableChannel.java
index e674d501718b7850d17427722e320b3ccf966178..5d1b1ee99a14f8e2a971a95d7b43815249a59bec 100644
--- a/src/share/classes/java/nio/channels/spi/AbstractSelectableChannel.java
+++ b/src/share/classes/java/nio/channels/spi/AbstractSelectableChannel.java
@@ -72,6 +72,9 @@ public abstract class AbstractSelectableChannel
 
     /**
      * Initializes a new instance of this class.
+     *
+     * @param  provider
+     *         The provider that created this channel
      */
     protected AbstractSelectableChannel(SelectorProvider provider) {
         this.provider = provider;
@@ -251,6 +254,9 @@ public abstract class AbstractSelectableChannel
      * that is blocked in an I/O operation upon this channel to return
      * immediately, either by throwing an exception or by returning normally.
      * 

+ * + * @throws IOException + * If an I/O error occurs */ protected abstract void implCloseSelectableChannel() throws IOException; @@ -299,6 +305,10 @@ public abstract class AbstractSelectableChannel * changing the blocking mode. This method is only invoked if the new mode * is different from the current mode.

* + * @param block If true then this channel will be placed in + * blocking mode; if false then it will be placed + * non-blocking mode + * * @throws IOException * If an I/O error occurs */ diff --git a/src/share/classes/java/nio/channels/spi/AbstractSelector.java b/src/share/classes/java/nio/channels/spi/AbstractSelector.java index fea4b0972e93a024d6122adc8277513758f6fad1..f4f4a2a74de644cfa12bd564c54d1f21e86dc6c4 100644 --- a/src/share/classes/java/nio/channels/spi/AbstractSelector.java +++ b/src/share/classes/java/nio/channels/spi/AbstractSelector.java @@ -43,7 +43,7 @@ import java.util.concurrent.atomic.AtomicBoolean; * after, respectively, invoking an I/O operation that might block * indefinitely. In order to ensure that the {@link #end end} method is always * invoked, these methods should be used within a - * try ... finally block:
+ * try ... finally block: * *
  * try {
@@ -77,6 +77,9 @@ public abstract class AbstractSelector
 
     /**
      * Initializes a new instance of this class.
+     *
+     * @param  provider
+     *         The provider that created this selector
      */
     protected AbstractSelector(SelectorProvider provider) {
         this.provider = provider;
diff --git a/src/share/classes/java/nio/channels/spi/AsynchronousChannelProvider.java b/src/share/classes/java/nio/channels/spi/AsynchronousChannelProvider.java
index 827a2c5b981aece330c262f2537ec22827e702bb..e768e475c351f3a7705a8ceea92482a7c2f0a59c 100644
--- a/src/share/classes/java/nio/channels/spi/AsynchronousChannelProvider.java
+++ b/src/share/classes/java/nio/channels/spi/AsynchronousChannelProvider.java
@@ -174,6 +174,8 @@ public abstract class AsynchronousChannelProvider {
      * @param   threadFactory
      *          The factory to use when creating new threads
      *
+     * @return  A new asynchronous channel group
+     *
      * @throws  IllegalArgumentException
      *          If {@code nThreads <= 0}
      * @throws  IOException
@@ -193,6 +195,8 @@ public abstract class AsynchronousChannelProvider {
      *          A value {@code >=0} or a negative value for implementation
      *          specific default
      *
+     * @return  A new asynchronous channel group
+     *
      * @throws  IOException
      *          If an I/O error occurs
      *
diff --git a/src/share/classes/java/nio/channels/spi/SelectorProvider.java b/src/share/classes/java/nio/channels/spi/SelectorProvider.java
index 62d4bf6ffc0df58f96de7929369b4b245e2f75ed..8d74b43cf64d25f341bbc894ea0a50dd3adfd754 100644
--- a/src/share/classes/java/nio/channels/spi/SelectorProvider.java
+++ b/src/share/classes/java/nio/channels/spi/SelectorProvider.java
@@ -183,6 +183,9 @@ public abstract class SelectorProvider {
      * Opens a datagram channel.
      *
      * @return  The new channel
+     *
+     * @throws  IOException
+     *          If an I/O error occurs
      */
     public abstract DatagramChannel openDatagramChannel()
         throws IOException;
@@ -209,6 +212,9 @@ public abstract class SelectorProvider {
      * Opens a pipe.
      *
      * @return  The new pipe
+     *
+     * @throws  IOException
+     *          If an I/O error occurs
      */
     public abstract Pipe openPipe()
         throws IOException;
@@ -217,6 +223,9 @@ public abstract class SelectorProvider {
      * Opens a selector.
      *
      * @return  The new selector
+     *
+     * @throws  IOException
+     *          If an I/O error occurs
      */
     public abstract AbstractSelector openSelector()
         throws IOException;
@@ -225,6 +234,9 @@ public abstract class SelectorProvider {
      * Opens a server-socket channel.
      *
      * @return  The new channel
+     *
+     * @throws  IOException
+     *          If an I/O error occurs
      */
     public abstract ServerSocketChannel openServerSocketChannel()
         throws IOException;
@@ -233,6 +245,9 @@ public abstract class SelectorProvider {
      * Opens a socket channel.
      *
      * @return  The new channel
+     *
+     * @throws  IOException
+     *          If an I/O error occurs
      */
     public abstract SocketChannel openSocketChannel()
         throws IOException;
diff --git a/src/share/classes/java/nio/charset/Charset-X-Coder.java.template b/src/share/classes/java/nio/charset/Charset-X-Coder.java.template
index 34be4eb83754c72da839e41f726d4d8b87e5a3c0..335194eef5257cc92ee8758197f80fb088a21a83 100644
--- a/src/share/classes/java/nio/charset/Charset-X-Coder.java.template
+++ b/src/share/classes/java/nio/charset/Charset-X-Coder.java.template
@@ -163,6 +163,9 @@ public abstract class Charset$Coder$ {
      * Initializes a new $coder$.  The new $coder$ will have the given
      * $otypes-per-itype$ and replacement values.
      *
+     * @param  cs
+     *         The charset that created this $coder$
+     *
      * @param  average$ItypesPerOtype$
      *         A positive float value indicating the expected number of
      *         $otype$s that will be produced for each input $itype$
@@ -209,6 +212,9 @@ public abstract class Charset$Coder$ {
      * $otypes-per-itype$ values and its replacement will be the
      * $replTypeName$ $defaultReplName$.
      *
+     * @param  cs
+     *         The charset that created this $coder$
+     *
      * @param  average$ItypesPerOtype$
      *         A positive float value indicating the expected number of
      *         $otype$s that will be produced for each input $itype$
@@ -386,6 +392,8 @@ public abstract class Charset$Coder$ {
      * 

The default implementation of this method does nothing. This method * should be overridden by $coder$s that require notification of changes to * the malformed-input action.

+ * + * @param newAction The new action */ protected void implOnMalformedInput(CodingErrorAction newAction) { } @@ -428,6 +436,8 @@ public abstract class Charset$Coder$ { *

The default implementation of this method does nothing. This method * should be overridden by $coder$s that require notification of changes to * the unmappable-character action.

+ * + * @param newAction The new action */ protected void implOnUnmappableCharacter(CodingErrorAction newAction) { } @@ -925,6 +935,9 @@ public abstract class Charset$Coder$ { *

The default implementation of this method is not very efficient; it * should generally be overridden to improve performance.

* + * @param c + * The given character + * * @return true if, and only if, this encoder can encode * the given character * @@ -953,6 +966,9 @@ public abstract class Charset$Coder$ { *

The default implementation of this method is not very efficient; it * should generally be overridden to improve performance.

* + * @param cs + * The given character sequence + * * @return true if, and only if, this encoder can encode * the given character without throwing any exceptions and without * performing any replacements diff --git a/src/share/classes/java/nio/charset/Charset.java b/src/share/classes/java/nio/charset/Charset.java index 69c3ab0e19fecc314508a8fd12d053178e0fe741..278bacb17c501ebf617f99586f44add7b3459ef6 100644 --- a/src/share/classes/java/nio/charset/Charset.java +++ b/src/share/classes/java/nio/charset/Charset.java @@ -66,7 +66,7 @@ import sun.security.action.GetPropertyAction; * * *
- *

Charset names

+ *

Charset names

* *

Charsets are named by strings composed of the following characters: * @@ -140,7 +140,7 @@ import sun.security.action.GetPropertyAction; * previous canonical name be made into an alias. * * - *

Standard charsets

+ *

Standard charsets

* *
* @@ -217,7 +217,7 @@ import sun.security.action.GetPropertyAction; *

The {@link StandardCharsets} class defines constants for each of the * standard charsets. * - *

Terminology

+ *

Terminology

* *

The name of this class is taken from the terms used in * RFC 2278. @@ -737,6 +737,9 @@ public abstract class Charset * it is not necessarily the case that the given charset is not contained * in this charset. * + * @param cs + * The given charset + * * @return true if the given charset is contained in this charset */ public abstract boolean contains(Charset cs); diff --git a/src/share/classes/java/nio/charset/CoderResult.java b/src/share/classes/java/nio/charset/CoderResult.java index 5b2c4d41f89fc283f22a1398c6120c9f5fcbf1c2..15aad362c06c54a259f93b9cedae7e63c0c85337 100644 --- a/src/share/classes/java/nio/charset/CoderResult.java +++ b/src/share/classes/java/nio/charset/CoderResult.java @@ -227,6 +227,9 @@ public class CoderResult { * Static factory method that returns the unique object describing a * malformed-input error of the given length. * + * @param length + * The given length + * * @return The requested coder-result object */ public static CoderResult malformedForLength(int length) { @@ -243,6 +246,9 @@ public class CoderResult { * Static factory method that returns the unique result object describing * an unmappable-character error of the given length. * + * @param length + * The given length + * * @return The requested coder-result object */ public static CoderResult unmappableForLength(int length) { diff --git a/src/share/classes/java/nio/charset/spi/CharsetProvider.java b/src/share/classes/java/nio/charset/spi/CharsetProvider.java index 3525e201d8757d485bc132b9ce46f148cf34ecd4..1e31d75fe310269e611f90ac8fa512eb70b7e314 100644 --- a/src/share/classes/java/nio/charset/spi/CharsetProvider.java +++ b/src/share/classes/java/nio/charset/spi/CharsetProvider.java @@ -39,8 +39,8 @@ import java.util.Iterator; * the usual extension directories. Providers may also be made available by * adding them to the applet or application class path or by some other * platform-specific means. Charset providers are looked up via the current - * thread's {@link java.lang.Thread#getContextClassLoader() context - * class loader}. + * thread's {@link java.lang.Thread#getContextClassLoader() context class + * loader}. * *

A charset provider identifies itself with a provider-configuration file * named java.nio.charset.spi.CharsetProvider in the resource diff --git a/src/share/classes/java/nio/file/FileStore.java b/src/share/classes/java/nio/file/FileStore.java index 831dba8a5e961d1002679e342e6a0fe6dd1f6c2b..d0bdc013992e7ee7d8d7de2e9483293dd76f4004 100644 --- a/src/share/classes/java/nio/file/FileStore.java +++ b/src/share/classes/java/nio/file/FileStore.java @@ -173,6 +173,8 @@ public abstract class FileStore { * The {@code type} parameter is the type of the attribute view required and * the method returns an instance of that type if supported. * + * @param + * The {@code FileStoreAttributeView} type * @param type * the {@code Class} object corresponding to the attribute view * diff --git a/src/share/classes/java/nio/file/FileSystem.java b/src/share/classes/java/nio/file/FileSystem.java index e2166079831cdaa3c549e8258134bc7db8bedcbc..2296cada82959cdffecfc6a705a162b31707bbb1 100644 --- a/src/share/classes/java/nio/file/FileSystem.java +++ b/src/share/classes/java/nio/file/FileSystem.java @@ -315,7 +315,7 @@ public abstract class FileSystem * that resembles regular expressions but with a simpler syntax. For example: * *

- *
Option NameDescription
+ *
* * * diff --git a/src/share/classes/java/nio/file/FileSystems.java b/src/share/classes/java/nio/file/FileSystems.java index ef443640af016a33b283cc0d5636ef9ce9e89fca..d6b4496dda7b8aac10c4451b970e4048d69c1592 100644 --- a/src/share/classes/java/nio/file/FileSystems.java +++ b/src/share/classes/java/nio/file/FileSystems.java @@ -200,6 +200,10 @@ public final class FileSystems { * existing file system. In the case of the {@link FileSystems#getDefault * default} file system, no permission check is required. * + * @param uri the URI to locate the file system + * + * @return the reference to the file system + * * @throws IllegalArgumentException * if the pre-conditions for the {@code uri} parameter are not met * @throws FileSystemNotFoundException diff --git a/src/share/classes/java/nio/file/Files.java b/src/share/classes/java/nio/file/Files.java index c4065690aa5e34c771d2859243be5f2ac8973762..ca0263d0660b2ff4a332ca073b55f5aacc8821e4 100644 --- a/src/share/classes/java/nio/file/Files.java +++ b/src/share/classes/java/nio/file/Files.java @@ -194,7 +194,7 @@ public final class Files { *

In the addition to {@code READ} and {@code WRITE}, the following * options may be present: * - *

{@code *.java}Matches a path that represents a file name ending in {@code .java}
+ *
* * * @@ -1616,7 +1616,8 @@ public final class Files { * } * * - * + * @param + * The {@code FileAttributeView} type * @param path * the path to the file * @param type @@ -1665,6 +1666,8 @@ public final class Files { * PosixFileAttributes attrs = Files.readAttributes(path, PosixFileAttributes.class, NOFOLLOW_LINKS); * * + * @param + * The {@code BasicFileAttributes} type * @param path * the path to the file * @param type @@ -1863,7 +1866,7 @@ public final class Files { * attributes} parameter: * *
- *
Option Description
{@link StandardOpenOption#APPEND APPEND}
+ *
* * * @@ -1971,10 +1974,12 @@ public final class Files { * System Interface (POSIX) family of standards. * * @param path - * A file reference that locates the file + * The path to the file * @param perms * The new set of permissions * + * @return The path + * * @throws UnsupportedOperationException * if the associated file system does not support the {@code * PosixFileAttributeView} @@ -2009,7 +2014,7 @@ public final class Files { * access to a file attribute that is the owner of the file. * * @param path - * A file reference that locates the file + * The path to the file * @param options * options indicating how symbolic links are handled * @@ -2052,10 +2057,12 @@ public final class Files { * * * @param path - * A file reference that locates the file + * The path to the file * @param owner * The new file owner * + * @return The path + * * @throws UnsupportedOperationException * if the associated file system does not support the {@code * FileOwnerAttributeView} @@ -2090,6 +2097,8 @@ public final class Files { * readAttributes} method and the file type tested with the {@link * BasicFileAttributes#isSymbolicLink} method. * + * @param path The path to the file + * * @return {@code true} if the file is a symbolic link; {@code false} if * the file does not exist, is not a symbolic link, or it cannot * be determined if the file is a symbolic link or not. @@ -2239,7 +2248,7 @@ public final class Files { * @param time * the new last modified time * - * @return the file + * @return the path * * @throws IOException * if an I/O error occurs diff --git a/src/share/classes/java/nio/file/Path.java b/src/share/classes/java/nio/file/Path.java index 577827658549c1b926978547c26554061bb5a80e..39afd4d4255f5bfa402cc54593674e308b50fbaf 100644 --- a/src/share/classes/java/nio/file/Path.java +++ b/src/share/classes/java/nio/file/Path.java @@ -64,7 +64,7 @@ import java.util.Iterator; * those developing custom file system implementations. Methods may be added to * this interface in future releases.

* - *

Accessing Files

+ *

Accessing Files

*

Paths may be used with the {@link Files} class to operate on files, * directories, and other types of files. For example, suppose we want a {@link * java.io.BufferedReader} to read text from a file "{@code access.log}". The @@ -75,7 +75,7 @@ import java.util.Iterator; * BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8); * * - *

Interoperability

+ *

Interoperability

*

Paths associated with the default {@link * java.nio.file.spi.FileSystemProvider provider} are generally interoperable * with the {@link java.io.File java.io.File} class. Paths created by other @@ -87,7 +87,7 @@ import java.util.Iterator; * addition, the {@link #toFile toFile} method is useful to construct a {@code * File} from the {@code String} representation of a {@code Path}. * - *

Concurrency

+ *

Concurrency

*

Implementations of this interface are immutable and safe for use by * multiple concurrent threads. * diff --git a/src/share/classes/java/nio/file/SecureDirectoryStream.java b/src/share/classes/java/nio/file/SecureDirectoryStream.java index 6ef4882eae8a66d7fc5602bdef3b7dab5d8cde3a..2bfa2056b82c00f0168e805bbd1ff18492c19808 100644 --- a/src/share/classes/java/nio/file/SecureDirectoryStream.java +++ b/src/share/classes/java/nio/file/SecureDirectoryStream.java @@ -122,6 +122,8 @@ public interface SecureDirectoryStream * an optional list of attributes to set atomically when creating * the file * + * @return the seekable byte channel + * * @throws ClosedDirectoryStreamException * if the directory stream is closed * @throws IllegalArgumentException @@ -260,6 +262,8 @@ public interface SecureDirectoryStream * then all methods to read or update attributes will throw {@link * ClosedDirectoryStreamException ClosedDirectoryStreamException}. * + * @param + * The {@code FileAttributeView} type * @param type * the {@code Class} object corresponding to the file attribute view * @@ -288,6 +292,8 @@ public interface SecureDirectoryStream * is created but methods to read or update attributes of the file will * fail when invoked and the file does not exist. * + * @param + * The {@code FileAttributeView} type * @param path * the path of the file * @param type diff --git a/src/share/classes/java/nio/file/WatchEvent.java b/src/share/classes/java/nio/file/WatchEvent.java index cab199f0b572ead46b84d895dcafe9f1c789a4b8..508486851509008861de54c32b515648222c9758 100644 --- a/src/share/classes/java/nio/file/WatchEvent.java +++ b/src/share/classes/java/nio/file/WatchEvent.java @@ -55,11 +55,16 @@ public interface WatchEvent { public static interface Kind { /** * Returns the name of the event kind. + * + * @return the name of the event kind */ String name(); /** * Returns the type of the {@link WatchEvent#context context} value. + * + * + * @return the type of the context value */ Class type(); } @@ -76,6 +81,8 @@ public interface WatchEvent { public static interface Modifier { /** * Returns the name of the modifier. + * + * @return the name of the modifier */ String name(); } diff --git a/src/share/classes/java/nio/file/WatchService.java b/src/share/classes/java/nio/file/WatchService.java index 5a63fcd872227a5e127c3c45fde69f20c6d2aaff..c6440b208e474b960779b0a26424da0d0f8ccda6 100644 --- a/src/share/classes/java/nio/file/WatchService.java +++ b/src/share/classes/java/nio/file/WatchService.java @@ -78,7 +78,7 @@ import java.util.concurrent.TimeUnit; * The {@link java.nio.channels.FileChannel FileChannel} class defines methods * to lock regions of a file against access by other programs. * - *

Platform dependencies

+ *

Platform dependencies

* *

The implementation that observes events from the file system is intended * to map directly on to the native file event notification facility where diff --git a/src/share/classes/java/nio/file/attribute/AclEntry.java b/src/share/classes/java/nio/file/attribute/AclEntry.java index 9b4ef8a34c3cc4859b119d1e2d7d326360254085..49bf52924715ccc30112f1fcecf368837c6f0626 100644 --- a/src/share/classes/java/nio/file/attribute/AclEntry.java +++ b/src/share/classes/java/nio/file/attribute/AclEntry.java @@ -134,6 +134,7 @@ public final class AclEntry { /** * Sets the type component of this builder. * + * @param type the component type * @return this builder */ public Builder setType(AclEntryType type) { @@ -146,6 +147,7 @@ public final class AclEntry { /** * Sets the principal component of this builder. * + * @param who the principal component * @return this builder */ public Builder setPrincipal(UserPrincipal who) { @@ -168,6 +170,7 @@ public final class AclEntry { * Sets the permissions component of this builder. On return, the * permissions component of this builder is a copy of the given set. * + * @param perms the permissions component * @return this builder * * @throws ClassCastException @@ -193,6 +196,7 @@ public final class AclEntry { * permissions component of this builder is a copy of the permissions in * the given array. * + * @param perms the permissions component * @return this builder */ public Builder setPermissions(AclEntryPermission... perms) { @@ -211,6 +215,7 @@ public final class AclEntry { * Sets the flags component of this builder. On return, the flags * component of this builder is a copy of the given set. * + * @param flags the flags component * @return this builder * * @throws ClassCastException @@ -236,6 +241,7 @@ public final class AclEntry { * component of this builder is a copy of the flags in the given * array. * + * @param flags the flags component * @return this builder */ public Builder setFlags(AclEntryFlag... flags) { @@ -267,9 +273,7 @@ public final class AclEntry { /** * Constructs a new builder with the components of an existing ACL entry. * - * @param entry - * an ACL entry - * + * @param entry an ACL entry * @return a new builder */ public static Builder newBuilder(AclEntry entry) { @@ -278,6 +282,8 @@ public final class AclEntry { /** * Returns the ACL entry type. + * + * @return the ACL entry type */ public AclEntryType type() { return type; @@ -285,6 +291,8 @@ public final class AclEntry { /** * Returns the principal component. + * + * @return the principal component */ public UserPrincipal principal() { return who; @@ -294,6 +302,8 @@ public final class AclEntry { * Returns a copy of the permissions component. * *

The returned set is a modifiable copy of the permissions. + * + * @return the permissions component */ public Set permissions() { return new HashSet(perms); @@ -303,6 +313,8 @@ public final class AclEntry { * Returns a copy of the flags component. * *

The returned set is a modifiable copy of the flags. + * + * @return the flags component */ public Set flags() { return new HashSet(flags); diff --git a/src/share/classes/java/nio/file/attribute/AclFileAttributeView.java b/src/share/classes/java/nio/file/attribute/AclFileAttributeView.java index 2f94937b6c114b9d0fbc55ccf8faee36683342cc..f5d58d41f4a964eba5794f6a3912aa542900c1cd 100644 --- a/src/share/classes/java/nio/file/attribute/AclFileAttributeView.java +++ b/src/share/classes/java/nio/file/attribute/AclFileAttributeView.java @@ -54,7 +54,7 @@ import java.io.IOException; * supportsFileAttributeView} method can be used to test if a file system * supports ACLs. * - *

Interoperability

+ *

Interoperability

* * RFC 3530 allows for special user identities to be used on platforms that * support the POSIX defined access permissions. The special user identities @@ -65,7 +65,7 @@ import java.io.IOException; * UserPrincipalLookupService} may be used to obtain a {@link UserPrincipal} * to represent these special identities by invoking the {@link * UserPrincipalLookupService#lookupPrincipalByName lookupPrincipalByName} - * method.

+ * method. * *

Usage Example: * Suppose we wish to add an entry to an existing ACL to grant "joe" access: @@ -90,11 +90,11 @@ import java.io.IOException; * view.setAcl(acl); * * - *

Dynamic Access

+ *

Dynamic Access

*

Where dynamic access to file attributes is required, the attributes * supported by this attribute view are as follows: *

- *
{@code "*"} Read all {@link BasicFileAttributes basic-file-attributes}.
+ *
* * * @@ -118,7 +118,7 @@ import java.io.IOException; * update the ACL or owner attributes as if by invoking the {@link #setAcl setAcl} * or {@link #setOwner setOwner} methods. * - *

Setting the ACL when creating a file

+ *

Setting the ACL when creating a file

* *

Implementations supporting this attribute view may also support setting * the initial ACL when creating a file or directory. The initial ACL diff --git a/src/share/classes/java/nio/file/attribute/AttributeView.java b/src/share/classes/java/nio/file/attribute/AttributeView.java index 0b2951b960e270209cd384f0b51b4ba3eb9c8a36..d33f9764a79abaaab23deb06537a1f0a3c500354 100644 --- a/src/share/classes/java/nio/file/attribute/AttributeView.java +++ b/src/share/classes/java/nio/file/attribute/AttributeView.java @@ -38,6 +38,8 @@ package java.nio.file.attribute; public interface AttributeView { /** * Returns the name of the attribute view. + * + * @return the name of the attribute view */ String name(); } diff --git a/src/share/classes/java/nio/file/attribute/BasicFileAttributeView.java b/src/share/classes/java/nio/file/attribute/BasicFileAttributeView.java index 2a8e2c9585bfaebbe6fb37c9a43a39be313c04e5..3a9c7916969802c41fc5040e9f70bd2a2a3d7fe6 100644 --- a/src/share/classes/java/nio/file/attribute/BasicFileAttributeView.java +++ b/src/share/classes/java/nio/file/attribute/BasicFileAttributeView.java @@ -41,7 +41,7 @@ import java.io.IOException; *

Where dynamic access to file attributes is required, the attributes * supported by this attribute view have the following names and types: *

- *
Name Type
+ *
* * * diff --git a/src/share/classes/java/nio/file/attribute/BasicFileAttributes.java b/src/share/classes/java/nio/file/attribute/BasicFileAttributes.java index d1f715dcea267014a5c572f320b8d9048c48df6b..df2d10bb27cd312d98d421363b5ebd6c2ae87f65 100644 --- a/src/share/classes/java/nio/file/attribute/BasicFileAttributes.java +++ b/src/share/classes/java/nio/file/attribute/BasicFileAttributes.java @@ -87,22 +87,31 @@ public interface BasicFileAttributes { /** * Tells whether the file is a regular file with opaque content. + * + * @return {@code true} if the file is a regular file with opaque content */ boolean isRegularFile(); /** * Tells whether the file is a directory. + * + * @return {@code true} if the file is a directory */ boolean isDirectory(); /** * Tells whether the file is a symbolic link. + * + * @return {@code true} if the file is a symbolic link */ boolean isSymbolicLink(); /** * Tells whether the file is something other than a regular file, directory, * or symbolic link. + * + * @return {@code true} if the file something other than a regular file, + * directory or symbolic link */ boolean isOther(); @@ -138,6 +147,8 @@ public interface BasicFileAttributes { * and two files are the {@link java.nio.file.Files#isSameFile same} with * non-{@code null} file keys, then their file keys are equal. * + * @return an object that uniquely identifies the given file, or {@code null} + * * @see java.nio.file.Files#walkFileTree */ Object fileKey(); diff --git a/src/share/classes/java/nio/file/attribute/DosFileAttributeView.java b/src/share/classes/java/nio/file/attribute/DosFileAttributeView.java index aa99d23322ee67b47a86736d32c15a8ef30a60ef..1fb53853a618dc743d8a99eb70c7315a58fc1165 100644 --- a/src/share/classes/java/nio/file/attribute/DosFileAttributeView.java +++ b/src/share/classes/java/nio/file/attribute/DosFileAttributeView.java @@ -41,7 +41,7 @@ import java.io.IOException; * BasicFileAttributeView}, and in addition, the following attributes are * supported: *
- *
Name Type
+ *
* * * diff --git a/src/share/classes/java/nio/file/attribute/FileAttribute.java b/src/share/classes/java/nio/file/attribute/FileAttribute.java index d3704cbf8212217f6ec639e0efeb0ea2e2cb41cf..461687634872693da7b5864b11d7ea136cc23a11 100644 --- a/src/share/classes/java/nio/file/attribute/FileAttribute.java +++ b/src/share/classes/java/nio/file/attribute/FileAttribute.java @@ -40,11 +40,15 @@ package java.nio.file.attribute; public interface FileAttribute { /** * Returns the attribute name. + * + * @return The attribute name */ String name(); /** * Returns the attribute value. + * + * @return The attribute value */ T value(); } diff --git a/src/share/classes/java/nio/file/attribute/PosixFileAttributeView.java b/src/share/classes/java/nio/file/attribute/PosixFileAttributeView.java index ea5f1e2eaa64531ddb3df66eb2799827c1df0520..81a6a4156e7ffc8f118bd2e1fdac47614531e35e 100644 --- a/src/share/classes/java/nio/file/attribute/PosixFileAttributeView.java +++ b/src/share/classes/java/nio/file/attribute/PosixFileAttributeView.java @@ -68,13 +68,13 @@ import java.io.IOException; * PosixFilePermissions.toString(attrs.permissions())); * * - *

Dynamic Access

+ *

Dynamic Access

*

Where dynamic access to file attributes is required, the attributes * supported by this attribute view are as defined by {@link * BasicFileAttributeView} and {@link FileOwnerAttributeView}, and in addition, * the following attributes are supported: *

- *
Name Type
+ *
* * * @@ -102,7 +102,7 @@ import java.io.IOException; * #setPermissions setPermissions}, {@link #setOwner setOwner}, and {@link * #setGroup setGroup} methods respectively. * - *

Setting Initial Permissions

+ *

Setting Initial Permissions

*

Implementations supporting this attribute view may also support setting * the initial permissions when creating a file or directory. The * initial permissions are provided to the {@link Files#createFile createFile} diff --git a/src/share/classes/java/nio/file/spi/FileSystemProvider.java b/src/share/classes/java/nio/file/spi/FileSystemProvider.java index 84e92d9cb9296d71b34755f4331c2daf6bd6f872..5b95dcc390d7e1a04943e876a6b6bbf82db8e45b 100644 --- a/src/share/classes/java/nio/file/spi/FileSystemProvider.java +++ b/src/share/classes/java/nio/file/spi/FileSystemProvider.java @@ -287,6 +287,8 @@ public abstract class FileSystemProvider { * @param uri * The URI to convert * + * @return The resulting {@code Path} + * * @throws IllegalArgumentException * If the URI scheme does not identify this provider or other * preconditions on the uri parameter do not hold @@ -751,6 +753,8 @@ public abstract class FileSystemProvider { * @param link * the path to the symbolic link * + * @return The target of the symbolic link + * * @throws UnsupportedOperationException * if the implementation does not support symbolic links * @throws NotLinkException @@ -984,6 +988,8 @@ public abstract class FileSystemProvider { * exactly the manner specified by the {@link Files#getFileAttributeView} * method. * + * @param + * The {@code FileAttributeView} type * @param path * the path to the file * @param type @@ -1002,6 +1008,8 @@ public abstract class FileSystemProvider { * exactly the manner specified by the {@link * Files#readAttributes(Path,Class,LinkOption[])} method. * + * @param + * The {@code BasicFileAttributes} type * @param path * the path to the file * @param type diff --git a/src/share/classes/java/rmi/server/RMIClassLoader.java b/src/share/classes/java/rmi/server/RMIClassLoader.java index f064d617fcd84aa815cdff6693f14525efacc0da..f9f23ddd0190e4ae967b04283301ab5eb2d1abd6 100644 --- a/src/share/classes/java/rmi/server/RMIClassLoader.java +++ b/src/share/classes/java/rmi/server/RMIClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -424,7 +424,7 @@ public class RMIClassLoader { * *

* *

In case the client does not explicitly initialize the KeyPairGenerator - * (via a call to an initialize method), each provider must + * (via a call to an {@code initialize} method), each provider must * supply (and document) a default initialization. * For example, the Sun provider uses a default modulus size (keysize) * of 1024 bits. * *

Note that this class is abstract and extends from - * KeyPairGeneratorSpi for historical reasons. + * {@code KeyPairGeneratorSpi} for historical reasons. * Application developers should only take notice of the methods defined in - * this KeyPairGenerator class; all the methods in + * this {@code KeyPairGenerator} class; all the methods in * the superclass are intended for cryptographic service providers who wish to * supply their own implementations of key pair generators. * *

Every implementation of the Java platform is required to support the - * following standard KeyPairGenerator algorithms and keysizes in + * following standard {@code KeyPairGenerator} algorithms and keysizes in * parentheses: *

    - *
  • DiffieHellman (1024)
  • - *
  • DSA (1024)
  • - *
  • RSA (1024, 2048)
  • + *
  • {@code DiffieHellman} (1024)
  • + *
  • {@code DSA} (1024)
  • + *
  • {@code RSA} (1024, 2048)
  • *
* These algorithms are described in the
@@ -322,18 +322,18 @@ public abstract class KeyPairGenerator extends KeyPairGeneratorSpi { /** * Initializes the key pair generator for a certain keysize using - * a default parameter set and the SecureRandom + * a default parameter set and the {@code SecureRandom} * implementation of the highest-priority installed provider as the source * of randomness. * (If none of the installed providers supply an implementation of - * SecureRandom, a system-provided source of randomness is + * {@code SecureRandom}, a system-provided source of randomness is * used.) * * @param keysize the keysize. This is an * algorithm-specific metric, such as modulus length, specified in * number of bits. * - * @exception InvalidParameterException if the keysize is not + * @exception InvalidParameterException if the {@code keysize} is not * supported by this KeyPairGenerator object. */ public void initialize(int keysize) { @@ -349,7 +349,7 @@ public abstract class KeyPairGenerator extends KeyPairGeneratorSpi { * number of bits. * @param random the source of randomness. * - * @exception InvalidParameterException if the keysize is not + * @exception InvalidParameterException if the {@code keysize} is not * supported by this KeyPairGenerator object. * * @since 1.2 @@ -369,11 +369,11 @@ public abstract class KeyPairGenerator extends KeyPairGeneratorSpi { /** * Initializes the key pair generator using the specified parameter - * set and the SecureRandom + * set and the {@code SecureRandom} * implementation of the highest-priority installed provider as the source * of randomness. * (If none of the installed providers supply an implementation of - * SecureRandom, a system-provided source of randomness is + * {@code SecureRandom}, a system-provided source of randomness is * used.). * *

This concrete method has been added to this previously-defined @@ -382,10 +382,10 @@ public abstract class KeyPairGenerator extends KeyPairGeneratorSpi { * {@link KeyPairGeneratorSpi#initialize( * java.security.spec.AlgorithmParameterSpec, * java.security.SecureRandom) initialize} method, - * passing it params and a source of randomness (obtained + * passing it {@code params} and a source of randomness (obtained * from the highest-priority installed provider or system-provided if none * of the installed providers supply one). - * That initialize method always throws an + * That {@code initialize} method always throws an * UnsupportedOperationException if it is not overridden by the provider. * * @param params the parameter set used to generate the keys. @@ -410,8 +410,8 @@ public abstract class KeyPairGenerator extends KeyPairGeneratorSpi { * KeyPairGeneratorSpi#initialize( * java.security.spec.AlgorithmParameterSpec, * java.security.SecureRandom) initialize} method, - * passing it params and random. - * That initialize + * passing it {@code params} and {@code random}. + * That {@code initialize} * method always throws an * UnsupportedOperationException if it is not overridden by the provider. * diff --git a/src/share/classes/java/security/KeyPairGeneratorSpi.java b/src/share/classes/java/security/KeyPairGeneratorSpi.java index 28139adcf6888ead30c33659e0cf5daa3ed54edc..dfe8c04218dc1f0f734a06e7df94c6f2b651693e 100644 --- a/src/share/classes/java/security/KeyPairGeneratorSpi.java +++ b/src/share/classes/java/security/KeyPairGeneratorSpi.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,7 +29,7 @@ import java.security.spec.AlgorithmParameterSpec; /** *

This class defines the Service Provider Interface (SPI) - * for the KeyPairGenerator class, which is used to generate + * for the {@code KeyPairGenerator} class, which is used to generate * pairs of public and private keys. * *

All the abstract methods in this class must be implemented by each @@ -37,7 +37,7 @@ import java.security.spec.AlgorithmParameterSpec; * of a key pair generator for a particular algorithm. * *

In case the client does not explicitly initialize the KeyPairGenerator - * (via a call to an initialize method), each provider must + * (via a call to an {@code initialize} method), each provider must * supply (and document) a default initialization. * For example, the Sun provider uses a default modulus size (keysize) * of 1024 bits. @@ -61,7 +61,7 @@ public abstract class KeyPairGeneratorSpi { * * @param random the source of randomness for this generator. * - * @exception InvalidParameterException if the keysize is not + * @exception InvalidParameterException if the {@code keysize} is not * supported by this KeyPairGeneratorSpi object. */ public abstract void initialize(int keysize, SecureRandom random); @@ -100,7 +100,7 @@ public abstract class KeyPairGeneratorSpi { * will be used. This will generate a new key pair every time it * is called. * - * @return the newly generated KeyPair + * @return the newly generated {@code KeyPair} */ public abstract KeyPair generateKeyPair(); } diff --git a/src/share/classes/java/security/KeyRep.java b/src/share/classes/java/security/KeyRep.java index 6c0231c5497d065de9e4d3d653952fe34a9fc356..0b1412c1563c15e843d18d07b5b76b9fe5a81434 100644 --- a/src/share/classes/java/security/KeyRep.java +++ b/src/share/classes/java/security/KeyRep.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -116,17 +116,17 @@ public class KeyRep implements Serializable { * * @param type either one of Type.SECRET, Type.PUBLIC, or Type.PRIVATE * @param algorithm the algorithm returned from - * Key.getAlgorithm() + * {@code Key.getAlgorithm()} * @param format the encoding format returned from - * Key.getFormat() + * {@code Key.getFormat()} * @param encoded the encoded bytes returned from - * Key.getEncoded() + * {@code Key.getEncoded()} * * @exception NullPointerException - * if type is null, - * if algorithm is null, - * if format is null, - * or if encoded is null + * if type is {@code null}, + * if algorithm is {@code null}, + * if format is {@code null}, + * or if encoded is {@code null} */ public KeyRep(Type type, String algorithm, String format, byte[] encoded) { diff --git a/src/share/classes/java/security/KeyStore.java b/src/share/classes/java/security/KeyStore.java index 64bb4f261b5f987565dfaff5329add8f3a619655..c363d0719f7ea603e59d2b1f7cd39e48e60d6850 100644 --- a/src/share/classes/java/security/KeyStore.java +++ b/src/share/classes/java/security/KeyStore.java @@ -41,13 +41,13 @@ import javax.security.auth.callback.*; * This class represents a storage facility for cryptographic * keys and certificates. * - *

A KeyStore manages different types of entries. - * Each type of entry implements the KeyStore.Entry interface. - * Three basic KeyStore.Entry implementations are provided: + *

A {@code KeyStore} manages different types of entries. + * Each type of entry implements the {@code KeyStore.Entry} interface. + * Three basic {@code KeyStore.Entry} implementations are provided: * *

Name Type
+ * * - * - * - * - * - * - - * - * + * + * + * + * + * + + * + * *
Attributes Automatically Placed in a Provider Object
NameValue
Provider.id nameString.valueOf(provider.getName())
Provider.id versionString.valueOf(provider.getVersion())
Provider.id infoString.valueOf(provider.getInfo())
Provider.id classNameprovider.getClass().getName()
{@code Provider.id name}{@code String.valueOf(provider.getName())}
{@code Provider.id version}{@code String.valueOf(provider.getVersion())}
{@code Provider.id info}{@code String.valueOf(provider.getInfo())}
{@code Provider.id className}{@code provider.getClass().getName()}
* * @author Benjamin Renaud @@ -185,18 +186,18 @@ public abstract class Provider extends Properties { * used to look up facilities implemented by the provider. * *

First, if there is a security manager, its - * checkSecurityAccess method is called with the string - * "clearProviderProperties."+name (where name + * {@code checkSecurityAccess} method is called with the string + * {@code "clearProviderProperties."+name} (where {@code name} * is the provider name) to see if it's ok to clear this provider. - * If the default implementation of checkSecurityAccess + * If the default implementation of {@code checkSecurityAccess} * is used (that is, that method is not overriden), then this results in - * a call to the security manager's checkPermission method - * with a SecurityPermission("clearProviderProperties."+name) + * a call to the security manager's {@code checkPermission} method + * with a {@code SecurityPermission("clearProviderProperties."+name)} * permission. * * @throws SecurityException - * if a security manager exists and its {@link - * java.lang.SecurityManager#checkSecurityAccess} method + * if a security manager exists and its {@link + * java.lang.SecurityManager#checkSecurityAccess} method * denies access to clear this provider * * @since 1.2 @@ -292,17 +293,17 @@ public abstract class Provider extends Properties { } /** - * Sets the key property to have the specified - * value. + * Sets the {@code key} property to have the specified + * {@code value}. * *

First, if there is a security manager, its - * checkSecurityAccess method is called with the string - * "putProviderProperty."+name, where name is the + * {@code checkSecurityAccess} method is called with the string + * {@code "putProviderProperty."+name}, where {@code name} is the * provider name, to see if it's ok to set this provider's property values. - * If the default implementation of checkSecurityAccess + * If the default implementation of {@code checkSecurityAccess} * is used (that is, that method is not overriden), then this results in - * a call to the security manager's checkPermission method - * with a SecurityPermission("putProviderProperty."+name) + * a call to the security manager's {@code checkPermission} method + * with a {@code SecurityPermission("putProviderProperty."+name)} * permission. * * @param key the property key. @@ -310,11 +311,11 @@ public abstract class Provider extends Properties { * @param value the property value. * * @return the previous value of the specified property - * (key), or null if it did not have one. + * ({@code key}), or null if it did not have one. * * @throws SecurityException - * if a security manager exists and its {@link - * java.lang.SecurityManager#checkSecurityAccess} method + * if a security manager exists and its {@link + * java.lang.SecurityManager#checkSecurityAccess} method * denies access to set property values. * * @since 1.2 @@ -329,18 +330,18 @@ public abstract class Provider extends Properties { } /** - * Removes the key property (and its corresponding - * value). + * Removes the {@code key} property (and its corresponding + * {@code value}). * *

First, if there is a security manager, its - * checkSecurityAccess method is called with the string - * "removeProviderProperty."+name, where name is + * {@code checkSecurityAccess} method is called with the string + * {@code "removeProviderProperty."+name}, where {@code name} is * the provider name, to see if it's ok to remove this provider's * properties. If the default implementation of - * checkSecurityAccess is used (that is, that method is not + * {@code checkSecurityAccess} is used (that is, that method is not * overriden), then this results in a call to the security manager's - * checkPermission method with a - * SecurityPermission("removeProviderProperty."+name) + * {@code checkPermission} method with a + * {@code SecurityPermission("removeProviderProperty."+name)} * permission. * * @param key the key for the property to be removed. @@ -349,8 +350,8 @@ public abstract class Provider extends Properties { * or null if the key did not have a mapping. * * @throws SecurityException - * if a security manager exists and its {@link - * java.lang.SecurityManager#checkSecurityAccess} method + * if a security manager exists and its {@link + * java.lang.SecurityManager#checkSecurityAccess} method * denies access to remove this provider's properties. * * @since 1.2 @@ -662,9 +663,9 @@ public abstract class Provider extends Properties { * the service added via {@link #putService putService()} is returned. * * @param type the type of {@link Service service} requested - * (for example, MessageDigest) + * (for example, {@code MessageDigest}) * @param algorithm the case insensitive algorithm name (or alternate - * alias) of the service requested (for example, SHA-1) + * alias) of the service requested (for example, {@code SHA-1}) * * @return the service describing this Provider's matching service * or null if no such service exists @@ -739,20 +740,20 @@ public abstract class Provider extends Properties { * Java Cryptography Architecture API Specification & Reference . * *

Also, if there is a security manager, its - * checkSecurityAccess method is called with the string - * "putProviderProperty."+name, where name is + * {@code checkSecurityAccess} method is called with the string + * {@code "putProviderProperty."+name}, where {@code name} is * the provider name, to see if it's ok to set this provider's property - * values. If the default implementation of checkSecurityAccess + * values. If the default implementation of {@code checkSecurityAccess} * is used (that is, that method is not overriden), then this results in - * a call to the security manager's checkPermission method with - * a SecurityPermission("putProviderProperty."+name) + * a call to the security manager's {@code checkPermission} method with + * a {@code SecurityPermission("putProviderProperty."+name)} * permission. * * @param s the Service to add * * @throws SecurityException - * if a security manager exists and its {@link - * java.lang.SecurityManager#checkSecurityAccess} method denies + * if a security manager exists and its {@link + * java.lang.SecurityManager#checkSecurityAccess} method denies * access to set property values. * @throws NullPointerException if s is null * @@ -830,21 +831,21 @@ public abstract class Provider extends Properties { * from this provider's Hashtable. * *

Also, if there is a security manager, its - * checkSecurityAccess method is called with the string - * "removeProviderProperty."+name, where name is + * {@code checkSecurityAccess} method is called with the string + * {@code "removeProviderProperty."+name}, where {@code name} is * the provider name, to see if it's ok to remove this provider's * properties. If the default implementation of - * checkSecurityAccess is used (that is, that method is not + * {@code checkSecurityAccess} is used (that is, that method is not * overriden), then this results in a call to the security manager's - * checkPermission method with a - * SecurityPermission("removeProviderProperty."+name) + * {@code checkPermission} method with a + * {@code SecurityPermission("removeProviderProperty."+name)} * permission. * * @param s the Service to be removed * * @throws SecurityException - * if a security manager exists and its {@link - * java.lang.SecurityManager#checkSecurityAccess} method denies + * if a security manager exists and its {@link + * java.lang.SecurityManager#checkSecurityAccess} method denies * access to remove this provider's properties. * @throws NullPointerException if s is null * @@ -1122,7 +1123,7 @@ public abstract class Provider extends Properties { } /** - * Get the type of this service. For example, MessageDigest. + * Get the type of this service. For example, {@code MessageDigest}. * * @return the type of this service */ @@ -1132,7 +1133,7 @@ public abstract class Provider extends Properties { /** * Return the name of the algorithm of this service. For example, - * SHA-1. + * {@code SHA-1}. * * @return the algorithm of this service */ diff --git a/src/share/classes/java/security/ProviderException.java b/src/share/classes/java/security/ProviderException.java index 449c8c361686528495dec678d4264194ab48b62c..b372ee7575272a3ab0285c1ed0acc72c366c0727 100644 --- a/src/share/classes/java/security/ProviderException.java +++ b/src/share/classes/java/security/ProviderException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,13 +58,13 @@ public class ProviderException extends RuntimeException { } /** - * Creates a ProviderException with the specified + * Creates a {@code ProviderException} with the specified * detail message and cause. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, + * {@link #getCause()} method). (A {@code null} value is permitted, * and indicates that the cause is nonexistent or unknown.) * @since 1.5 */ @@ -73,13 +73,13 @@ public class ProviderException extends RuntimeException { } /** - * Creates a ProviderException with the specified cause - * and a detail message of (cause==null ? null : cause.toString()) + * Creates a {@code ProviderException} with the specified cause + * and a detail message of {@code (cause==null ? null : cause.toString())} * (which typically contains the class and detail message of - * cause). + * {@code cause}). * * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, + * {@link #getCause()} method). (A {@code null} value is permitted, * and indicates that the cause is nonexistent or unknown.) * @since 1.5 */ diff --git a/src/share/classes/java/security/PublicKey.java b/src/share/classes/java/security/PublicKey.java index c983ff611d985d36957ca8db75704b98bb826d8d..df49807eea4beb0986cf0bee73349931f2c03bc9 100644 --- a/src/share/classes/java/security/PublicKey.java +++ b/src/share/classes/java/security/PublicKey.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,7 @@ package java.security; * * Note: The specialized public key interfaces extend this interface. * See, for example, the DSAPublicKey interface in - * java.security.interfaces. + * {@code java.security.interfaces}. * * @see Key * @see PrivateKey diff --git a/src/share/classes/java/security/SecureClassLoader.java b/src/share/classes/java/security/SecureClassLoader.java index ffcd1a7160f195ae78ad897278564b33de737305..145f4fc482b5d9884369e67f5a4a6e419141a7b4 100644 --- a/src/share/classes/java/security/SecureClassLoader.java +++ b/src/share/classes/java/security/SecureClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -63,12 +63,12 @@ public class SecureClassLoader extends ClassLoader { * class loader for delegation. * *

If there is a security manager, this method first - * calls the security manager's checkCreateClassLoader + * calls the security manager's {@code checkCreateClassLoader} * method to ensure creation of a class loader is allowed. *

* @param parent the parent ClassLoader * @exception SecurityException if a security manager exists and its - * checkCreateClassLoader method doesn't allow + * {@code checkCreateClassLoader} method doesn't allow * creation of a class loader. * @see SecurityManager#checkCreateClassLoader */ @@ -87,11 +87,11 @@ public class SecureClassLoader extends ClassLoader { * loader for delegation. * *

If there is a security manager, this method first - * calls the security manager's checkCreateClassLoader + * calls the security manager's {@code checkCreateClassLoader} * method to ensure creation of a class loader is allowed. * * @exception SecurityException if a security manager exists and its - * checkCreateClassLoader method doesn't allow + * {@code checkCreateClassLoader} method doesn't allow * creation of a class loader. * @see SecurityManager#checkCreateClassLoader */ @@ -113,22 +113,22 @@ public class SecureClassLoader extends ClassLoader { * If a non-null CodeSource is supplied a ProtectionDomain is * constructed and associated with the class being defined. *

- * @param name the expected name of the class, or null + * @param name the expected name of the class, or {@code null} * if not known, using '.' and not '/' as the separator * and without a trailing ".class" suffix. * @param b the bytes that make up the class data. The bytes in - * positions off through off+len-1 + * positions {@code off} through {@code off+len-1} * should have the format of a valid class file as defined by * The Java™ Virtual Machine Specification. - * @param off the start offset in b of the class data + * @param off the start offset in {@code b} of the class data * @param len the length of the class data - * @param cs the associated CodeSource, or null if none - * @return the Class object created from the data, + * @param cs the associated CodeSource, or {@code null} if none + * @return the {@code Class} object created from the data, * and optional CodeSource. * @exception ClassFormatError if the data did not contain a valid class - * @exception IndexOutOfBoundsException if either off or - * len is negative, or if - * off+len is greater than b.length. + * @exception IndexOutOfBoundsException if either {@code off} or + * {@code len} is negative, or if + * {@code off+len} is greater than {@code b.length}. * * @exception SecurityException if an attempt is made to add this class * to a package that contains classes that were signed by @@ -143,22 +143,22 @@ public class SecureClassLoader extends ClassLoader { } /** - * Converts a {@link java.nio.ByteBuffer ByteBuffer} - * into an instance of class Class, with an optional CodeSource. + * Converts a {@link java.nio.ByteBuffer ByteBuffer} + * into an instance of class {@code Class}, with an optional CodeSource. * Before the class can be used it must be resolved. *

* If a non-null CodeSource is supplied a ProtectionDomain is * constructed and associated with the class being defined. *

- * @param name the expected name of the class, or null + * @param name the expected name of the class, or {@code null} * if not known, using '.' and not '/' as the separator * and without a trailing ".class" suffix. * @param b the bytes that make up the class data. The bytes from positions - * b.position() through b.position() + b.limit() -1 + * {@code b.position()} through {@code b.position() + b.limit() -1} * should have the format of a valid class file as defined by * The Java™ Virtual Machine Specification. - * @param cs the associated CodeSource, or null if none - * @return the Class object created from the data, + * @param cs the associated CodeSource, or {@code null} if none + * @return the {@code Class} object created from the data, * and optional CodeSource. * @exception ClassFormatError if the data did not contain a valid class * @exception SecurityException if an attempt is made to add this class diff --git a/src/share/classes/java/security/SecureRandom.java b/src/share/classes/java/security/SecureRandom.java index 7d25b147ed316d132806e7d7b7a4f8bcd702bdde..5afec7b0797d854571d282bf83e5d15cd839c75f 100644 --- a/src/share/classes/java/security/SecureRandom.java +++ b/src/share/classes/java/security/SecureRandom.java @@ -50,7 +50,7 @@ import sun.security.jca.GetInstance.Instance; * RFC 1750: Randomness Recommendations for Security. * *

A caller obtains a SecureRandom instance via the - * no-argument constructor or one of the getInstance methods: + * no-argument constructor or one of the {@code getInstance} methods: * *

  *      SecureRandom random = new SecureRandom();
@@ -71,15 +71,15 @@ import sun.security.jca.GetInstance.Instance;
  *      random.nextBytes(bytes);
  * 
* - *

Callers may also invoke the generateSeed method + *

Callers may also invoke the {@code generateSeed} method * to generate a given number of seed bytes (to seed other random number * generators, for example): *

  *      byte seed[] = random.generateSeed(20);
  * 
* - * Note: Depending on the implementation, the generateSeed and - * nextBytes methods may block as entropy is being gathered, + * Note: Depending on the implementation, the {@code generateSeed} and + * {@code nextBytes} methods may block as entropy is being gathered, * for example, if they need to read from /dev/random on various Unix-like * operating systems. * @@ -140,16 +140,16 @@ public class SecureRandom extends java.util.Random { * for information about standard RNG algorithm names. * *

The returned SecureRandom object has not been seeded. To seed the - * returned object, call the setSeed method. - * If setSeed is not called, the first call to - * nextBytes will force the SecureRandom object to seed itself. - * This self-seeding will not occur if setSeed was + * returned object, call the {@code setSeed} method. + * If {@code setSeed} is not called, the first call to + * {@code nextBytes} will force the SecureRandom object to seed itself. + * This self-seeding will not occur if {@code setSeed} was * previously called. */ public SecureRandom() { /* * This call to our superclass constructor will result in a call - * to our own setSeed method, which will return + * to our own {@code setSeed} method, which will return * immediately when it is passed zero. */ super(0); @@ -250,10 +250,10 @@ public class SecureRandom extends java.util.Random { * the {@link Security#getProviders() Security.getProviders()} method. * *

The returned SecureRandom object has not been seeded. To seed the - * returned object, call the setSeed method. - * If setSeed is not called, the first call to - * nextBytes will force the SecureRandom object to seed itself. - * This self-seeding will not occur if setSeed was + * returned object, call the {@code setSeed} method. + * If {@code setSeed} is not called, the first call to + * {@code nextBytes} will force the SecureRandom object to seed itself. + * This self-seeding will not occur if {@code setSeed} was * previously called. * * @param algorithm the name of the RNG algorithm. @@ -293,10 +293,10 @@ public class SecureRandom extends java.util.Random { * the {@link Security#getProviders() Security.getProviders()} method. * *

The returned SecureRandom object has not been seeded. To seed the - * returned object, call the setSeed method. - * If setSeed is not called, the first call to - * nextBytes will force the SecureRandom object to seed itself. - * This self-seeding will not occur if setSeed was + * returned object, call the {@code setSeed} method. + * If {@code setSeed} is not called, the first call to + * {@code nextBytes} will force the SecureRandom object to seed itself. + * This self-seeding will not occur if {@code setSeed} was * previously called. * * @param algorithm the name of the RNG algorithm. @@ -341,10 +341,10 @@ public class SecureRandom extends java.util.Random { * does not have to be registered in the provider list. * *

The returned SecureRandom object has not been seeded. To seed the - * returned object, call the setSeed method. - * If setSeed is not called, the first call to - * nextBytes will force the SecureRandom object to seed itself. - * This self-seeding will not occur if setSeed was + * returned object, call the {@code setSeed} method. + * If {@code setSeed} is not called, the first call to + * {@code nextBytes} will force the SecureRandom object to seed itself. + * This self-seeding will not occur if {@code setSeed} was * previously called. * * @param algorithm the name of the RNG algorithm. @@ -395,7 +395,7 @@ public class SecureRandom extends java.util.Random { * Returns the name of the algorithm implemented by this SecureRandom * object. * - * @return the name of the algorithm or unknown + * @return the name of the algorithm or {@code unknown} * if the algorithm name cannot be determined. * @since 1.5 */ @@ -418,12 +418,12 @@ public class SecureRandom extends java.util.Random { /** * Reseeds this random object, using the eight bytes contained - * in the given long seed. The given seed supplements, + * in the given {@code long seed}. The given seed supplements, * rather than replaces, the existing seed. Thus, repeated calls * are guaranteed never to reduce randomness. * *

This method is defined for compatibility with - * java.util.Random. + * {@code java.util.Random}. * * @param seed the seed. * @@ -445,10 +445,10 @@ public class SecureRandom extends java.util.Random { /** * Generates a user-specified number of random bytes. * - *

If a call to setSeed had not occurred previously, + *

If a call to {@code setSeed} had not occurred previously, * the first call to this method forces this SecureRandom object * to seed itself. This self-seeding will not occur if - * setSeed was previously called. + * {@code setSeed} was previously called. * * @param bytes the array to be filled in with random bytes. */ @@ -460,15 +460,15 @@ public class SecureRandom extends java.util.Random { /** * Generates an integer containing the user-specified number of * pseudo-random bits (right justified, with leading zeros). This - * method overrides a java.util.Random method, and serves + * method overrides a {@code java.util.Random} method, and serves * to provide a source of random bits to all of the methods inherited - * from that class (for example, nextInt, - * nextLong, and nextFloat). + * from that class (for example, {@code nextInt}, + * {@code nextLong}, and {@code nextFloat}). * * @param numBits number of pseudo-random bits to be generated, where * {@code 0 <= numBits <= 32}. * - * @return an int containing the user-specified number + * @return an {@code int} containing the user-specified number * of pseudo-random bits (right justified, with leading zeros). */ @Override @@ -492,8 +492,8 @@ public class SecureRandom extends java.util.Random { * *

This method is only included for backwards compatibility. * The caller is encouraged to use one of the alternative - * getInstance methods to obtain a SecureRandom object, and - * then call the generateSeed method to obtain seed bytes + * {@code getInstance} methods to obtain a SecureRandom object, and + * then call the {@code generateSeed} method to obtain seed bytes * from that object. * * @param numBytes the number of seed bytes to generate. diff --git a/src/share/classes/java/security/SecureRandomSpi.java b/src/share/classes/java/security/SecureRandomSpi.java index 12652e98a65f7eee4c535174a072db884a25d782..ef6c243363087f9c4713a567a6f48fc3e9341f41 100644 --- a/src/share/classes/java/security/SecureRandomSpi.java +++ b/src/share/classes/java/security/SecureRandomSpi.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,7 @@ package java.security; /** * This class defines the Service Provider Interface (SPI) - * for the SecureRandom class. + * for the {@code SecureRandom} class. * All the abstract methods in this class must be implemented by each * service provider who wishes to supply the implementation * of a cryptographically strong pseudo-random number generator. @@ -53,10 +53,10 @@ public abstract class SecureRandomSpi implements java.io.Serializable { /** * Generates a user-specified number of random bytes. * - *

If a call to engineSetSeed had not occurred previously, + *

If a call to {@code engineSetSeed} had not occurred previously, * the first call to this method forces this SecureRandom implementation * to seed itself. This self-seeding will not occur if - * engineSetSeed was previously called. + * {@code engineSetSeed} was previously called. * * @param bytes the array to be filled in with random bytes. */ diff --git a/src/share/classes/java/security/Security.java b/src/share/classes/java/security/Security.java index eccede10b203c251e9591cbdb935f1523f486bd4..98699da8149c4e1e3eeadf91553c3071d51d875a 100644 --- a/src/share/classes/java/security/Security.java +++ b/src/share/classes/java/security/Security.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -298,7 +298,7 @@ public final class Security { * property in the master file of the "SUN" Cryptographic Service * Provider in order to determine how to parse algorithm-specific * parameters. Use the new provider-based and algorithm-independent - * AlgorithmParameters and KeyFactory engine + * {@code AlgorithmParameters} and {@code KeyFactory} engine * classes (introduced in the J2SE version 1.2 platform) instead. */ @Deprecated @@ -321,21 +321,21 @@ public final class Security { * *

If the given provider is installed at the requested position, * the provider that used to be at that position, and all providers - * with a position greater than position, are shifted up + * with a position greater than {@code position}, are shifted up * one position (towards the end of the list of installed providers). * *

A provider cannot be added if it is already installed. * *

First, if there is a security manager, its - * checkSecurityAccess + * {@code checkSecurityAccess} * method is called with the string - * "insertProvider."+provider.getName() + * {@code "insertProvider."+provider.getName()} * to see if it's ok to add a new provider. - * If the default implementation of checkSecurityAccess + * If the default implementation of {@code checkSecurityAccess} * is used (i.e., that method is not overriden), then this will result in - * a call to the security manager's checkPermission method + * a call to the security manager's {@code checkPermission} method * with a - * SecurityPermission("insertProvider."+provider.getName()) + * {@code SecurityPermission("insertProvider."+provider.getName())} * permission. * * @param provider the provider to be added. @@ -349,8 +349,8 @@ public final class Security { * * @throws NullPointerException if provider is null * @throws SecurityException - * if a security manager exists and its {@link - * java.lang.SecurityManager#checkSecurityAccess} method + * if a security manager exists and its {@link + * java.lang.SecurityManager#checkSecurityAccess} method * denies access to add a new provider * * @see #getProvider @@ -374,15 +374,15 @@ public final class Security { * Adds a provider to the next position available. * *

First, if there is a security manager, its - * checkSecurityAccess + * {@code checkSecurityAccess} * method is called with the string - * "insertProvider."+provider.getName() + * {@code "insertProvider."+provider.getName()} * to see if it's ok to add a new provider. - * If the default implementation of checkSecurityAccess + * If the default implementation of {@code checkSecurityAccess} * is used (i.e., that method is not overriden), then this will result in - * a call to the security manager's checkPermission method + * a call to the security manager's {@code checkPermission} method * with a - * SecurityPermission("insertProvider."+provider.getName()) + * {@code SecurityPermission("insertProvider."+provider.getName())} * permission. * * @param provider the provider to be added. @@ -393,8 +393,8 @@ public final class Security { * * @throws NullPointerException if provider is null * @throws SecurityException - * if a security manager exists and its {@link - * java.lang.SecurityManager#checkSecurityAccess} method + * if a security manager exists and its {@link + * java.lang.SecurityManager#checkSecurityAccess} method * denies access to add a new provider * * @see #getProvider @@ -423,20 +423,20 @@ public final class Security { * if name is null. * *

First, if there is a security manager, its - * checkSecurityAccess - * method is called with the string "removeProvider."+name + * {@code checkSecurityAccess} + * method is called with the string {@code "removeProvider."+name} * to see if it's ok to remove the provider. - * If the default implementation of checkSecurityAccess + * If the default implementation of {@code checkSecurityAccess} * is used (i.e., that method is not overriden), then this will result in - * a call to the security manager's checkPermission method - * with a SecurityPermission("removeProvider."+name) + * a call to the security manager's {@code checkPermission} method + * with a {@code SecurityPermission("removeProvider."+name)} * permission. * * @param name the name of the provider to remove. * * @throws SecurityException - * if a security manager exists and its {@link - * java.lang.SecurityManager#checkSecurityAccess} method + * if a security manager exists and its {@link + * java.lang.SecurityManager#checkSecurityAccess} method * denies * access to remove the provider * @@ -480,8 +480,8 @@ public final class Security { * Returns an array containing all installed providers that satisfy the * specified selection criterion, or null if no such providers have been * installed. The returned providers are ordered - * according to their preference order. + * according to their + * {@linkplain #insertProviderAt(java.security.Provider, int) preference order}. * *

A cryptographic service is always associated with a particular * algorithm or type. For example, a digital signature service is @@ -492,8 +492,8 @@ public final class Security { *

The selection criterion must be specified in one of the following two * formats: *

    - *
  • <crypto_service>.<algorithm_or_type>

    The - * cryptographic service name must not contain any dots. + *

  • {@literal .} + *

    The cryptographic service name must not contain any dots. *

    A * provider satisfies the specified selection criterion iff the provider * implements the @@ -501,11 +501,12 @@ public final class Security { *

    For example, "CertificateFactory.X.509" * would be satisfied by any provider that supplied * a CertificateFactory implementation for X.509 certificates. - *

  • <crypto_service>.<algorithm_or_type> - * <attribute_name>:< attribute_value> + *
  • {@literal . + * :} *

    The cryptographic service name must not contain any dots. There * must be one or more space charaters between the - * <algorithm_or_type> and the <attribute_name>. + * {@literal } and the + * {@literal }. *

    A provider satisfies this selection criterion iff the * provider implements the specified algorithm or type for the specified * cryptographic service and its implementation meets the @@ -558,8 +559,9 @@ public final class Security { * Returns an array containing all installed providers that satisfy the * specified* selection criteria, or null if no such providers have been * installed. The returned providers are ordered - * according to their preference order. + * according to their + * {@linkplain #insertProviderAt(java.security.Provider, int) + * preference order}. * *

    The selection criteria are represented by a map. * Each map entry represents a selection criterion. @@ -567,16 +569,18 @@ public final class Security { * criteria. The key for any entry in such a map must be in one of the * following two formats: *

    * - * The java.security.acl package provides the + * The {@code java.security.acl } package provides the * interfaces to the ACL and related data structures (ACL entries, - * groups, permissions, etc.), and the sun.security.acl + * groups, permissions, etc.), and the {@code sun.security.acl } * classes provide a default implementation of the interfaces. For - * example, java.security.acl.Acl provides the - * interface to an ACL and the sun.security.acl.AclImpl + * example, {@code java.security.acl.Acl } provides the + * interface to an ACL and the {@code sun.security.acl.AclImpl } * class provides the default implementation of the interface.

    * - * The java.security.acl.Acl interface extends the - * java.security.acl.Owner interface. The Owner + * The {@code java.security.acl.Acl } interface extends the + * {@code java.security.acl.Owner } interface. The Owner * interface is used to maintain a list of owners for each ACL. Only * owners are allowed to modify an ACL. For example, only an owner can - * call the ACL's addEntry method to add a new ACL entry + * call the ACL's {@code addEntry} method to add a new ACL entry * to the ACL. * * @see java.security.acl.AclEntry @@ -217,7 +217,7 @@ public interface Acl extends Owner { * More specifically, this method checks whether the passed permission * is a member of the allowed permission set of the specified principal. * The allowed permission set is determined by the same algorithm as is - * used by the getPermissions method. + * used by the {@code getPermissions} method. * * @param principal the principal, assumed to be a valid authenticated * Principal. diff --git a/src/share/classes/java/security/acl/AclEntry.java b/src/share/classes/java/security/acl/AclEntry.java index f8dd3a752e006a1982aa0233d156db3f19554e1f..cd9675f34a15054dd39fd99ae7d5da0018cd2d04 100644 --- a/src/share/classes/java/security/acl/AclEntry.java +++ b/src/share/classes/java/security/acl/AclEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -84,7 +84,7 @@ public interface AclEntry extends Cloneable { * specified in the entry. * * Note: ACL entries are by default positive. An entry becomes a - * negative entry only if this setNegativePermissions + * negative entry only if this {@code setNegativePermissions} * method is called on it. */ public void setNegativePermissions(); diff --git a/src/share/classes/java/security/acl/Group.java b/src/share/classes/java/security/acl/Group.java index be3578b3c334fcb96496c0ed2f22f29f35193cf7..ebd9c445282e5dca5b3c7d51ab9b1f275ae0b804 100644 --- a/src/share/classes/java/security/acl/Group.java +++ b/src/share/classes/java/security/acl/Group.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,7 +35,7 @@ import java.security.Principal; * Note that Group extends Principal. Thus, either a Principal or a Group can * be passed as an argument to methods containing a Principal parameter. For * example, you can add either a Principal or a Group to a Group object by - * calling the object's addMember method, passing it the + * calling the object's {@code addMember} method, passing it the * Principal or Group. * * @author Satish Dharmaraj diff --git a/src/share/classes/java/security/acl/Owner.java b/src/share/classes/java/security/acl/Owner.java index 313889528d6cc18adab1721467b0c0a2018bde70..2f649d40b33ac5f9e295c5072adfb7102feb9950 100644 --- a/src/share/classes/java/security/acl/Owner.java +++ b/src/share/classes/java/security/acl/Owner.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 1997, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,7 @@ import java.security.Principal; /** * Interface for managing owners of Access Control Lists (ACLs) or ACL * configurations. (Note that the Acl interface in the - * java.security.acl package extends this Owner + * {@code java.security.acl} package extends this Owner * interface.) The initial owner Principal should be specified as an * argument to the constructor of the class implementing this interface. * diff --git a/src/share/classes/java/security/acl/package-info.java b/src/share/classes/java/security/acl/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..356c102e32327027dab18afb49187ecf662b0a32 --- /dev/null +++ b/src/share/classes/java/security/acl/package-info.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * The classes and interfaces in this package have been + * superseded by classes in the java.security package. + * See that package and, for example, java.security.Permission for details. + * + * @since JDK1.1 + */ +package java.security.acl; diff --git a/src/share/classes/java/security/acl/package.html b/src/share/classes/java/security/acl/package.html deleted file mode 100644 index 497dfe8323e5a637240fd021713f4f9f23595372..0000000000000000000000000000000000000000 --- a/src/share/classes/java/security/acl/package.html +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - -The classes and interfaces in this package have been -superseded by classes in the java.security package. -See that package and, for example, java.security.Permission for details. - - - -@since JDK1.1 - - diff --git a/src/share/classes/java/security/cert/CRLException.java b/src/share/classes/java/security/cert/CRLException.java index ca5b689d07c6271a027a16f74a875b361c620643..7a854316bbd8467c02a7436aa05b071bef3a3b15 100644 --- a/src/share/classes/java/security/cert/CRLException.java +++ b/src/share/classes/java/security/cert/CRLException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,13 +57,13 @@ public class CRLException extends GeneralSecurityException { } /** - * Creates a CRLException with the specified + * Creates a {@code CRLException} with the specified * detail message and cause. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, + * {@link #getCause()} method). (A {@code null} value is permitted, * and indicates that the cause is nonexistent or unknown.) * @since 1.5 */ @@ -72,13 +72,13 @@ public class CRLException extends GeneralSecurityException { } /** - * Creates a CRLException with the specified cause - * and a detail message of (cause==null ? null : cause.toString()) + * Creates a {@code CRLException} with the specified cause + * and a detail message of {@code (cause==null ? null : cause.toString())} * (which typically contains the class and detail message of - * cause). + * {@code cause}). * * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, + * {@link #getCause()} method). (A {@code null} value is permitted, * and indicates that the cause is nonexistent or unknown.) * @since 1.5 */ diff --git a/src/share/classes/java/security/cert/CRLSelector.java b/src/share/classes/java/security/cert/CRLSelector.java index 2c00f10bca72519bf4317239f7a715a9a4757738..7ab181d48c559c6178a990530e1387a177dade20 100644 --- a/src/share/classes/java/security/cert/CRLSelector.java +++ b/src/share/classes/java/security/cert/CRLSelector.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,9 +26,9 @@ package java.security.cert; /** - * A selector that defines a set of criteria for selecting CRLs. + * A selector that defines a set of criteria for selecting {@code CRL}s. * Classes that implement this interface are often used to specify - * which CRLs should be retrieved from a CertStore. + * which {@code CRL}s should be retrieved from a {@code CertStore}. *

    * Concurrent Access *

    @@ -48,19 +48,19 @@ package java.security.cert; public interface CRLSelector extends Cloneable { /** - * Decides whether a CRL should be selected. + * Decides whether a {@code CRL} should be selected. * - * @param crl the CRL to be checked - * @return true if the CRL should be selected, - * false otherwise + * @param crl the {@code CRL} to be checked + * @return {@code true} if the {@code CRL} should be selected, + * {@code false} otherwise */ boolean match(CRL crl); /** - * Makes a copy of this CRLSelector. Changes to the + * Makes a copy of this {@code CRLSelector}. Changes to the * copy will not affect the original and vice versa. * - * @return a copy of this CRLSelector + * @return a copy of this {@code CRLSelector} */ Object clone(); } diff --git a/src/share/classes/java/security/cert/CertPath.java b/src/share/classes/java/security/cert/CertPath.java index 052be2043c9ecab9fec6bf72911422ea294782d9..8717f94820318248479f667cce1c0d0a69cc7a2b 100644 --- a/src/share/classes/java/security/cert/CertPath.java +++ b/src/share/classes/java/security/cert/CertPath.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,59 +36,59 @@ import java.util.List; * An immutable sequence of certificates (a certification path). *

    * This is an abstract class that defines the methods common to all - * CertPaths. Subclasses can handle different kinds of + * {@code CertPath}s. Subclasses can handle different kinds of * certificates (X.509, PGP, etc.). *

    - * All CertPath objects have a type, a list of - * Certificates, and one or more supported encodings. Because the - * CertPath class is immutable, a CertPath cannot + * All {@code CertPath} objects have a type, a list of + * {@code Certificate}s, and one or more supported encodings. Because the + * {@code CertPath} class is immutable, a {@code CertPath} cannot * change in any externally visible way after being constructed. This * stipulation applies to all public fields and methods of this class and any * added or overridden by subclasses. *

    - * The type is a String that identifies the type of - * Certificates in the certification path. For each - * certificate cert in a certification path certPath, - * cert.getType().equals(certPath.getType()) must be - * true. + * The type is a {@code String} that identifies the type of + * {@code Certificate}s in the certification path. For each + * certificate {@code cert} in a certification path {@code certPath}, + * {@code cert.getType().equals(certPath.getType())} must be + * {@code true}. *

    - * The list of Certificates is an ordered List of - * zero or more Certificates. This List and all - * of the Certificates contained in it must be immutable. + * The list of {@code Certificate}s is an ordered {@code List} of + * zero or more {@code Certificate}s. This {@code List} and all + * of the {@code Certificate}s contained in it must be immutable. *

    - * Each CertPath object must support one or more encodings + * Each {@code CertPath} object must support one or more encodings * so that the object can be translated into a byte array for storage or * transmission to other parties. Preferably, these encodings should be * well-documented standards (such as PKCS#7). One of the encodings supported - * by a CertPath is considered the default encoding. This + * by a {@code CertPath} is considered the default encoding. This * encoding is used if no encoding is explicitly requested (for the * {@link #getEncoded() getEncoded()} method, for instance). *

    - * All CertPath objects are also Serializable. - * CertPath objects are resolved into an alternate + * All {@code CertPath} objects are also {@code Serializable}. + * {@code CertPath} objects are resolved into an alternate * {@link CertPathRep CertPathRep} object during serialization. This allows - * a CertPath object to be serialized into an equivalent + * a {@code CertPath} object to be serialized into an equivalent * representation regardless of its underlying implementation. *

    - * CertPath objects can be created with a - * CertificateFactory or they can be returned by other classes, - * such as a CertPathBuilder. + * {@code CertPath} objects can be created with a + * {@code CertificateFactory} or they can be returned by other classes, + * such as a {@code CertPathBuilder}. *

    - * By convention, X.509 CertPaths (consisting of - * X509Certificates), are ordered starting with the target + * By convention, X.509 {@code CertPath}s (consisting of + * {@code X509Certificate}s), are ordered starting with the target * certificate and ending with a certificate issued by the trust anchor. That * is, the issuer of one certificate is the subject of the following one. The * certificate representing the {@link TrustAnchor TrustAnchor} should not be - * included in the certification path. Unvalidated X.509 CertPaths - * may not follow these conventions. PKIX CertPathValidators will + * included in the certification path. Unvalidated X.509 {@code CertPath}s + * may not follow these conventions. PKIX {@code CertPathValidator}s will * detect any departure from these conventions that cause the certification - * path to be invalid and throw a CertPathValidatorException. + * path to be invalid and throw a {@code CertPathValidatorException}. * *

    Every implementation of the Java platform is required to support the - * following standard CertPath encodings: + * following standard {@code CertPath} encodings: *

      - *
    • PKCS7
    • - *
    • PkiPath
    • + *
    • {@code PKCS7}
    • + *
    • {@code PkiPath}
    • *
    * These encodings are described in the
    @@ -99,17 +99,17 @@ import java.util.List; *

    * Concurrent Access *

    - * All CertPath objects must be thread-safe. That is, multiple + * All {@code CertPath} objects must be thread-safe. That is, multiple * threads may concurrently invoke the methods defined in this class on a - * single CertPath object (or more than one) with no - * ill effects. This is also true for the List returned by - * CertPath.getCertificates. + * single {@code CertPath} object (or more than one) with no + * ill effects. This is also true for the {@code List} returned by + * {@code CertPath.getCertificates}. *

    - * Requiring CertPath objects to be immutable and thread-safe + * Requiring {@code CertPath} objects to be immutable and thread-safe * allows them to be passed around to various pieces of code without worrying * about coordinating access. Providing this thread-safety is - * generally not difficult, since the CertPath and - * List objects in question are immutable. + * generally not difficult, since the {@code CertPath} and + * {@code List} objects in question are immutable. * * @see CertificateFactory * @see CertPathBuilder @@ -124,25 +124,25 @@ public abstract class CertPath implements Serializable { private String type; // the type of certificates in this chain /** - * Creates a CertPath of the specified type. + * Creates a {@code CertPath} of the specified type. *

    * This constructor is protected because most users should use a - * CertificateFactory to create CertPaths. + * {@code CertificateFactory} to create {@code CertPath}s. * * @param type the standard name of the type of - * Certificates in this path + * {@code Certificate}s in this path */ protected CertPath(String type) { this.type = type; } /** - * Returns the type of Certificates in this certification + * Returns the type of {@code Certificate}s in this certification * path. This is the same string that would be returned by * {@link java.security.cert.Certificate#getType() cert.getType()} - * for all Certificates in the certification path. + * for all {@code Certificate}s in the certification path. * - * @return the type of Certificates in this certification + * @return the type of {@code Certificate}s in this certification * path (never null) */ public String getType() { @@ -152,21 +152,21 @@ public abstract class CertPath implements Serializable { /** * Returns an iteration of the encodings supported by this certification * path, with the default encoding first. Attempts to modify the returned - * Iterator via its remove method result in an - * UnsupportedOperationException. + * {@code Iterator} via its {@code remove} method result in an + * {@code UnsupportedOperationException}. * - * @return an Iterator over the names of the supported + * @return an {@code Iterator} over the names of the supported * encodings (as Strings) */ public abstract Iterator getEncodings(); /** * Compares this certification path for equality with the specified - * object. Two CertPaths are equal if and only if their - * types are equal and their certificate Lists (and by - * implication the Certificates in those Lists) - * are equal. A CertPath is never equal to an object that is - * not a CertPath. + * object. Two {@code CertPath}s are equal if and only if their + * types are equal and their certificate {@code List}s (and by + * implication the {@code Certificate}s in those {@code List}s) + * are equal. A {@code CertPath} is never equal to an object that is + * not a {@code CertPath}. *

    * This algorithm is implemented by this method. If it is overridden, * the behavior specified here must be maintained. @@ -195,14 +195,14 @@ public abstract class CertPath implements Serializable { * Returns the hashcode for this certification path. The hash code of * a certification path is defined to be the result of the following * calculation: - *

    
    +     * 
    {@code
          *  hashCode = path.getType().hashCode();
          *  hashCode = 31*hashCode + path.getCertificates().hashCode();
    -     * 
    - * This ensures that path1.equals(path2) implies that - * path1.hashCode()==path2.hashCode() for any two certification - * paths, path1 and path2, as required by the - * general contract of Object.hashCode. + * }
    + * This ensures that {@code path1.equals(path2)} implies that + * {@code path1.hashCode()==path2.hashCode()} for any two certification + * paths, {@code path1} and {@code path2}, as required by the + * general contract of {@code Object.hashCode}. * * @return the hashcode value for this certification path */ @@ -214,8 +214,8 @@ public abstract class CertPath implements Serializable { /** * Returns a string representation of this certification path. - * This calls the toString method on each of the - * Certificates in the path. + * This calls the {@code toString} method on each of the + * {@code Certificate}s in the path. * * @return a string representation of this certification path */ @@ -266,20 +266,20 @@ public abstract class CertPath implements Serializable { /** * Returns the list of certificates in this certification path. - * The List returned must be immutable and thread-safe. + * The {@code List} returned must be immutable and thread-safe. * - * @return an immutable List of Certificates + * @return an immutable {@code List} of {@code Certificate}s * (may be empty, but not null) */ public abstract List getCertificates(); /** - * Replaces the CertPath to be serialized with a - * CertPathRep object. + * Replaces the {@code CertPath} to be serialized with a + * {@code CertPathRep} object. * - * @return the CertPathRep to be serialized + * @return the {@code CertPathRep} to be serialized * - * @throws ObjectStreamException if a CertPathRep object + * @throws ObjectStreamException if a {@code CertPathRep} object * representing this certification path could not be created */ protected Object writeReplace() throws ObjectStreamException { @@ -295,7 +295,7 @@ public abstract class CertPath implements Serializable { } /** - * Alternate CertPath class for serialization. + * Alternate {@code CertPath} class for serialization. * @since 1.4 */ protected static class CertPathRep implements Serializable { @@ -308,10 +308,10 @@ public abstract class CertPath implements Serializable { private byte[] data; /** - * Creates a CertPathRep with the specified + * Creates a {@code CertPathRep} with the specified * type and encoded form of a certification path. * - * @param type the standard name of a CertPath type + * @param type the standard name of a {@code CertPath} type * @param data the encoded form of the certification path */ protected CertPathRep(String type, byte[] data) { @@ -320,11 +320,11 @@ public abstract class CertPath implements Serializable { } /** - * Returns a CertPath constructed from the type and data. + * Returns a {@code CertPath} constructed from the type and data. * - * @return the resolved CertPath object + * @return the resolved {@code CertPath} object * - * @throws ObjectStreamException if a CertPath could not + * @throws ObjectStreamException if a {@code CertPath} could not * be constructed */ protected Object readResolve() throws ObjectStreamException { diff --git a/src/share/classes/java/security/cert/CertPathBuilder.java b/src/share/classes/java/security/cert/CertPathBuilder.java index 998477b48143938f74e7bece8ee8636161e289e9..6008e9ec180d469a5cb1eb9356ac9c37b1f42ff2 100644 --- a/src/share/classes/java/security/cert/CertPathBuilder.java +++ b/src/share/classes/java/security/cert/CertPathBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,16 +41,16 @@ import sun.security.jca.GetInstance.Instance; * A class for building certification paths (also known as certificate chains). *

    * This class uses a provider-based architecture. - * To create a CertPathBuilder, call - * one of the static getInstance methods, passing in the - * algorithm name of the CertPathBuilder desired and optionally + * To create a {@code CertPathBuilder}, call + * one of the static {@code getInstance} methods, passing in the + * algorithm name of the {@code CertPathBuilder} desired and optionally * the name of the provider desired. * - *

    Once a CertPathBuilder object has been created, certification + *

    Once a {@code CertPathBuilder} object has been created, certification * paths can be constructed by calling the {@link #build build} method and * passing it an algorithm-specific set of parameters. If successful, the - * result (including the CertPath that was built) is returned - * in an object that implements the CertPathBuilderResult + * result (including the {@code CertPath} that was built) is returned + * in an object that implements the {@code CertPathBuilderResult} * interface. * *

    The {@link #getRevocationChecker} method allows an application to specify @@ -67,9 +67,9 @@ import sun.security.jca.GetInstance.Instance; * * *

    Every implementation of the Java platform is required to support the - * following standard CertPathBuilder algorithm: + * following standard {@code CertPathBuilder} algorithm: *

      - *
    • PKIX
    • + *
    • {@code PKIX}
    • *
    * This algorithm is described in the
    @@ -87,9 +87,9 @@ import sun.security.jca.GetInstance.Instance; *

    * However, this is not true for the non-static methods defined by this class. * Unless otherwise documented by a specific provider, threads that need to - * access a single CertPathBuilder instance concurrently should + * access a single {@code CertPathBuilder} instance concurrently should * synchronize amongst themselves and provide the necessary locking. Multiple - * threads each manipulating a different CertPathBuilder instance + * threads each manipulating a different {@code CertPathBuilder} instance * need not synchronize. * * @see CertPath @@ -114,7 +114,7 @@ public class CertPathBuilder { private final String algorithm; /** - * Creates a CertPathBuilder object of the given algorithm, + * Creates a {@code CertPathBuilder} object of the given algorithm, * and encapsulates the given provider implementation (SPI object) in it. * * @param builderSpi the provider implementation @@ -130,7 +130,7 @@ public class CertPathBuilder { } /** - * Returns a CertPathBuilder object that implements the + * Returns a {@code CertPathBuilder} object that implements the * specified algorithm. * *

    This method traverses the list of registered security Providers, @@ -142,13 +142,13 @@ public class CertPathBuilder { *

    Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * - * @param algorithm the name of the requested CertPathBuilder + * @param algorithm the name of the requested {@code CertPathBuilder} * algorithm. See the CertPathBuilder section in the * Java Cryptography Architecture Standard Algorithm Name Documentation * for information about standard algorithm names. * - * @return a CertPathBuilder object that implements the + * @return a {@code CertPathBuilder} object that implements the * specified algorithm. * * @throws NoSuchAlgorithmException if no Provider supports a @@ -166,7 +166,7 @@ public class CertPathBuilder { } /** - * Returns a CertPathBuilder object that implements the + * Returns a {@code CertPathBuilder} object that implements the * specified algorithm. * *

    A new CertPathBuilder object encapsulating the @@ -177,7 +177,7 @@ public class CertPathBuilder { *

    Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * - * @param algorithm the name of the requested CertPathBuilder + * @param algorithm the name of the requested {@code CertPathBuilder} * algorithm. See the CertPathBuilder section in the * Java Cryptography Architecture Standard Algorithm Name Documentation @@ -185,7 +185,7 @@ public class CertPathBuilder { * * @param provider the name of the provider. * - * @return a CertPathBuilder object that implements the + * @return a {@code CertPathBuilder} object that implements the * specified algorithm. * * @throws NoSuchAlgorithmException if a CertPathBuilderSpi @@ -195,7 +195,7 @@ public class CertPathBuilder { * @throws NoSuchProviderException if the specified provider is not * registered in the security provider list. * - * @exception IllegalArgumentException if the provider is + * @exception IllegalArgumentException if the {@code provider} is * null or empty. * * @see java.security.Provider @@ -209,7 +209,7 @@ public class CertPathBuilder { } /** - * Returns a CertPathBuilder object that implements the + * Returns a {@code CertPathBuilder} object that implements the * specified algorithm. * *

    A new CertPathBuilder object encapsulating the @@ -217,7 +217,7 @@ public class CertPathBuilder { * object is returned. Note that the specified Provider object * does not have to be registered in the provider list. * - * @param algorithm the name of the requested CertPathBuilder + * @param algorithm the name of the requested {@code CertPathBuilder} * algorithm. See the CertPathBuilder section in the * Java Cryptography Architecture Standard Algorithm Name Documentation @@ -225,14 +225,14 @@ public class CertPathBuilder { * * @param provider the provider. * - * @return a CertPathBuilder object that implements the + * @return a {@code CertPathBuilder} object that implements the * specified algorithm. * * @exception NoSuchAlgorithmException if a CertPathBuilderSpi * implementation for the specified algorithm is not available * from the specified Provider object. * - * @exception IllegalArgumentException if the provider is + * @exception IllegalArgumentException if the {@code provider} is * null. * * @see java.security.Provider @@ -246,18 +246,18 @@ public class CertPathBuilder { } /** - * Returns the provider of this CertPathBuilder. + * Returns the provider of this {@code CertPathBuilder}. * - * @return the provider of this CertPathBuilder + * @return the provider of this {@code CertPathBuilder} */ public final Provider getProvider() { return this.provider; } /** - * Returns the name of the algorithm of this CertPathBuilder. + * Returns the name of the algorithm of this {@code CertPathBuilder}. * - * @return the name of the algorithm of this CertPathBuilder + * @return the name of the algorithm of this {@code CertPathBuilder} */ public final String getAlgorithm() { return this.algorithm; @@ -272,7 +272,7 @@ public class CertPathBuilder { * @throws CertPathBuilderException if the builder is unable to construct * a certification path that satisfies the specified parameters * @throws InvalidAlgorithmParameterException if the specified parameters - * are inappropriate for this CertPathBuilder + * are inappropriate for this {@code CertPathBuilder} */ public final CertPathBuilderResult build(CertPathParameters params) throws CertPathBuilderException, InvalidAlgorithmParameterException diff --git a/src/share/classes/java/security/cert/CertPathBuilderException.java b/src/share/classes/java/security/cert/CertPathBuilderException.java index 4d460c66db9a955ba41ab944ce0ea972fe7e865f..cf95847922b4d86370ef8af321c2f8051644e8de 100644 --- a/src/share/classes/java/security/cert/CertPathBuilderException.java +++ b/src/share/classes/java/security/cert/CertPathBuilderException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,9 +29,9 @@ import java.security.GeneralSecurityException; /** * An exception indicating one of a variety of problems encountered when - * building a certification path with a CertPathBuilder. + * building a certification path with a {@code CertPathBuilder}. *

    - * A CertPathBuilderException provides support for wrapping + * A {@code CertPathBuilderException} provides support for wrapping * exceptions. The {@link #getCause getCause} method returns the throwable, * if any, that caused this exception to be thrown. *

    @@ -53,7 +53,7 @@ public class CertPathBuilderException extends GeneralSecurityException { private static final long serialVersionUID = 5316471420178794402L; /** - * Creates a CertPathBuilderException with null + * Creates a {@code CertPathBuilderException} with {@code null} * as its detail message. */ public CertPathBuilderException() { @@ -61,8 +61,8 @@ public class CertPathBuilderException extends GeneralSecurityException { } /** - * Creates a CertPathBuilderException with the given - * detail message. The detail message is a String that + * Creates a {@code CertPathBuilderException} with the given + * detail message. The detail message is a {@code String} that * describes this particular exception in more detail. * * @param msg the detail message @@ -72,16 +72,16 @@ public class CertPathBuilderException extends GeneralSecurityException { } /** - * Creates a CertPathBuilderException that wraps the specified + * Creates a {@code CertPathBuilderException} that wraps the specified * throwable. This allows any exception to be converted into a - * CertPathBuilderException, while retaining information + * {@code CertPathBuilderException}, while retaining information * about the wrapped exception, which may be useful for debugging. The - * detail message is set to (cause==null ? null : cause.toString() - * ) (which typically contains the class and detail message of + * detail message is set to ({@code cause==null ? null : cause.toString()}) + * (which typically contains the class and detail message of * cause). * * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause getCause()} method). (A null value is + * {@link #getCause getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or unknown.) */ public CertPathBuilderException(Throwable cause) { @@ -89,12 +89,12 @@ public class CertPathBuilderException extends GeneralSecurityException { } /** - * Creates a CertPathBuilderException with the specified + * Creates a {@code CertPathBuilderException} with the specified * detail message and cause. * * @param msg the detail message * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause getCause()} method). (A null value is + * {@link #getCause getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or unknown.) */ public CertPathBuilderException(String msg, Throwable cause) { diff --git a/src/share/classes/java/security/cert/CertPathBuilderResult.java b/src/share/classes/java/security/cert/CertPathBuilderResult.java index 71eed201ac4b01273193327f42f3dc0d455e7264..ecf53bbe750bcb4caab23e6ecf806efa6fc30013 100644 --- a/src/share/classes/java/security/cert/CertPathBuilderResult.java +++ b/src/share/classes/java/security/cert/CertPathBuilderResult.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,8 +30,8 @@ package java.security.cert; * All results returned by the {@link CertPathBuilder#build * CertPathBuilder.build} method must implement this interface. *

    - * At a minimum, a CertPathBuilderResult contains the - * CertPath built by the CertPathBuilder instance. + * At a minimum, a {@code CertPathBuilderResult} contains the + * {@code CertPath} built by the {@code CertPathBuilder} instance. * Implementations of this interface may add methods to return implementation * or algorithm specific information, such as debugging information or * certification path validation results. @@ -54,15 +54,15 @@ public interface CertPathBuilderResult extends Cloneable { /** * Returns the built certification path. * - * @return the certification path (never null) + * @return the certification path (never {@code null}) */ CertPath getCertPath(); /** - * Makes a copy of this CertPathBuilderResult. Changes to the + * Makes a copy of this {@code CertPathBuilderResult}. Changes to the * copy will not affect the original and vice versa. * - * @return a copy of this CertPathBuilderResult + * @return a copy of this {@code CertPathBuilderResult} */ Object clone(); } diff --git a/src/share/classes/java/security/cert/CertPathBuilderSpi.java b/src/share/classes/java/security/cert/CertPathBuilderSpi.java index 49a35b36e906ae67548bd0fd08c94aede73f16dc..87908c03bd9f239f343a19ff4fb116d44dcfd92f 100644 --- a/src/share/classes/java/security/cert/CertPathBuilderSpi.java +++ b/src/share/classes/java/security/cert/CertPathBuilderSpi.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,23 +30,23 @@ import java.security.InvalidAlgorithmParameterException; /** * The Service Provider Interface (SPI) * for the {@link CertPathBuilder CertPathBuilder} class. All - * CertPathBuilder implementations must include a class (the - * SPI class) that extends this class (CertPathBuilderSpi) and + * {@code CertPathBuilder} implementations must include a class (the + * SPI class) that extends this class ({@code CertPathBuilderSpi}) and * implements all of its methods. In general, instances of this class should - * only be accessed through the CertPathBuilder class. For + * only be accessed through the {@code CertPathBuilder} class. For * details, see the Java Cryptography Architecture. *

    * Concurrent Access *

    * Instances of this class need not be protected against concurrent * access from multiple threads. Threads that need to access a single - * CertPathBuilderSpi instance concurrently should synchronize + * {@code CertPathBuilderSpi} instance concurrently should synchronize * amongst themselves and provide the necessary locking before calling the - * wrapping CertPathBuilder object. + * wrapping {@code CertPathBuilder} object. *

    - * However, implementations of CertPathBuilderSpi may still + * However, implementations of {@code CertPathBuilderSpi} may still * encounter concurrency issues, since multiple threads each - * manipulating a different CertPathBuilderSpi instance need not + * manipulating a different {@code CertPathBuilderSpi} instance need not * synchronize. * * @since 1.4 @@ -68,7 +68,7 @@ public abstract class CertPathBuilderSpi { * @throws CertPathBuilderException if the builder is unable to construct * a certification path that satisfies the specified parameters * @throws InvalidAlgorithmParameterException if the specified parameters - * are inappropriate for this CertPathBuilder + * are inappropriate for this {@code CertPathBuilder} */ public abstract CertPathBuilderResult engineBuild(CertPathParameters params) throws CertPathBuilderException, InvalidAlgorithmParameterException; diff --git a/src/share/classes/java/security/cert/CertPathParameters.java b/src/share/classes/java/security/cert/CertPathParameters.java index 46f9d8841bc3f4268481d94f1fad3550b94e8266..ace1b21f63f6182d2b4932ab92c6d1a9080818ca 100644 --- a/src/share/classes/java/security/cert/CertPathParameters.java +++ b/src/share/classes/java/security/cert/CertPathParameters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,8 +28,8 @@ package java.security.cert; /** * A specification of certification path algorithm parameters. * The purpose of this interface is to group (and provide type safety for) - * all CertPath parameter specifications. All - * CertPath parameter specifications must implement this + * all {@code CertPath} parameter specifications. All + * {@code CertPath} parameter specifications must implement this * interface. * * @author Yassir Elley @@ -40,10 +40,10 @@ package java.security.cert; public interface CertPathParameters extends Cloneable { /** - * Makes a copy of this CertPathParameters. Changes to the + * Makes a copy of this {@code CertPathParameters}. Changes to the * copy will not affect the original and vice versa. * - * @return a copy of this CertPathParameters + * @return a copy of this {@code CertPathParameters} */ Object clone(); } diff --git a/src/share/classes/java/security/cert/CertPathValidator.java b/src/share/classes/java/security/cert/CertPathValidator.java index 99ecb1e1603903862b5ccd239a7523c0c0cf694f..bd2ff56dd0cd5e93fb7cfd73b1e617e550313218 100644 --- a/src/share/classes/java/security/cert/CertPathValidator.java +++ b/src/share/classes/java/security/cert/CertPathValidator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,17 +42,17 @@ import sun.security.jca.GetInstance.Instance; * chains). *

    * This class uses a provider-based architecture. - * To create a CertPathValidator, - * call one of the static getInstance methods, passing in the - * algorithm name of the CertPathValidator desired and + * To create a {@code CertPathValidator}, + * call one of the static {@code getInstance} methods, passing in the + * algorithm name of the {@code CertPathValidator} desired and * optionally the name of the provider desired. * - *

    Once a CertPathValidator object has been created, it can + *

    Once a {@code CertPathValidator} object has been created, it can * be used to validate certification paths by calling the {@link #validate - * validate} method and passing it the CertPath to be validated + * validate} method and passing it the {@code CertPath} to be validated * and an algorithm-specific set of parameters. If successful, the result is * returned in an object that implements the - * CertPathValidatorResult interface. + * {@code CertPathValidatorResult} interface. * *

    The {@link #getRevocationChecker} method allows an application to specify * additional algorithm-specific parameters and options used by the @@ -69,9 +69,9 @@ import sun.security.jca.GetInstance.Instance; * * *

    Every implementation of the Java platform is required to support the - * following standard CertPathValidator algorithm: + * following standard {@code CertPathValidator} algorithm: *

      - *
    • PKIX
    • + *
    • {@code PKIX}
    • *
    * This algorithm is described in the @@ -89,9 +89,9 @@ import sun.security.jca.GetInstance.Instance; *

    * However, this is not true for the non-static methods defined by this class. * Unless otherwise documented by a specific provider, threads that need to - * access a single CertPathValidator instance concurrently should + * access a single {@code CertPathValidator} instance concurrently should * synchronize amongst themselves and provide the necessary locking. Multiple - * threads each manipulating a different CertPathValidator + * threads each manipulating a different {@code CertPathValidator} * instance need not synchronize. * * @see CertPath @@ -115,7 +115,7 @@ public class CertPathValidator { private final String algorithm; /** - * Creates a CertPathValidator object of the given algorithm, + * Creates a {@code CertPathValidator} object of the given algorithm, * and encapsulates the given provider implementation (SPI object) in it. * * @param validatorSpi the provider implementation @@ -131,7 +131,7 @@ public class CertPathValidator { } /** - * Returns a CertPathValidator object that implements the + * Returns a {@code CertPathValidator} object that implements the * specified algorithm. * *

    This method traverses the list of registered security Providers, @@ -143,13 +143,13 @@ public class CertPathValidator { *

    Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * - * @param algorithm the name of the requested CertPathValidator + * @param algorithm the name of the requested {@code CertPathValidator} * algorithm. See the CertPathValidator section in the * Java Cryptography Architecture Standard Algorithm Name Documentation * for information about standard algorithm names. * - * @return a CertPathValidator object that implements the + * @return a {@code CertPathValidator} object that implements the * specified algorithm. * * @exception NoSuchAlgorithmException if no Provider supports a @@ -167,7 +167,7 @@ public class CertPathValidator { } /** - * Returns a CertPathValidator object that implements the + * Returns a {@code CertPathValidator} object that implements the * specified algorithm. * *

    A new CertPathValidator object encapsulating the @@ -178,7 +178,7 @@ public class CertPathValidator { *

    Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * - * @param algorithm the name of the requested CertPathValidator + * @param algorithm the name of the requested {@code CertPathValidator} * algorithm. See the CertPathValidator section in the * Java Cryptography Architecture Standard Algorithm Name Documentation @@ -186,7 +186,7 @@ public class CertPathValidator { * * @param provider the name of the provider. * - * @return a CertPathValidator object that implements the + * @return a {@code CertPathValidator} object that implements the * specified algorithm. * * @exception NoSuchAlgorithmException if a CertPathValidatorSpi @@ -196,7 +196,7 @@ public class CertPathValidator { * @exception NoSuchProviderException if the specified provider is not * registered in the security provider list. * - * @exception IllegalArgumentException if the provider is + * @exception IllegalArgumentException if the {@code provider} is * null or empty. * * @see java.security.Provider @@ -211,7 +211,7 @@ public class CertPathValidator { } /** - * Returns a CertPathValidator object that implements the + * Returns a {@code CertPathValidator} object that implements the * specified algorithm. * *

    A new CertPathValidator object encapsulating the @@ -219,7 +219,7 @@ public class CertPathValidator { * object is returned. Note that the specified Provider object * does not have to be registered in the provider list. * - * @param algorithm the name of the requested CertPathValidator + * @param algorithm the name of the requested {@code CertPathValidator} * algorithm. See the CertPathValidator section in the * Java Cryptography Architecture Standard Algorithm Name Documentation @@ -227,14 +227,14 @@ public class CertPathValidator { * * @param provider the provider. * - * @return a CertPathValidator object that implements the + * @return a {@code CertPathValidator} object that implements the * specified algorithm. * * @exception NoSuchAlgorithmException if a CertPathValidatorSpi * implementation for the specified algorithm is not available * from the specified Provider object. * - * @exception IllegalArgumentException if the provider is + * @exception IllegalArgumentException if the {@code provider} is * null. * * @see java.security.Provider @@ -248,19 +248,19 @@ public class CertPathValidator { } /** - * Returns the Provider of this - * CertPathValidator. + * Returns the {@code Provider} of this + * {@code CertPathValidator}. * - * @return the Provider of this CertPathValidator + * @return the {@code Provider} of this {@code CertPathValidator} */ public final Provider getProvider() { return this.provider; } /** - * Returns the algorithm name of this CertPathValidator. + * Returns the algorithm name of this {@code CertPathValidator}. * - * @return the algorithm name of this CertPathValidator + * @return the algorithm name of this {@code CertPathValidator} */ public final String getAlgorithm() { return this.algorithm; @@ -270,20 +270,20 @@ public class CertPathValidator { * Validates the specified certification path using the specified * algorithm parameter set. *

    - * The CertPath specified must be of a type that is + * The {@code CertPath} specified must be of a type that is * supported by the validation algorithm, otherwise an - * InvalidAlgorithmParameterException will be thrown. For - * example, a CertPathValidator that implements the PKIX - * algorithm validates CertPath objects of type X.509. + * {@code InvalidAlgorithmParameterException} will be thrown. For + * example, a {@code CertPathValidator} that implements the PKIX + * algorithm validates {@code CertPath} objects of type X.509. * - * @param certPath the CertPath to be validated + * @param certPath the {@code CertPath} to be validated * @param params the algorithm parameters * @return the result of the validation algorithm - * @exception CertPathValidatorException if the CertPath + * @exception CertPathValidatorException if the {@code CertPath} * does not validate * @exception InvalidAlgorithmParameterException if the specified - * parameters or the type of the specified CertPath are - * inappropriate for this CertPathValidator + * parameters or the type of the specified {@code CertPath} are + * inappropriate for this {@code CertPathValidator} */ public final CertPathValidatorResult validate(CertPath certPath, CertPathParameters params) diff --git a/src/share/classes/java/security/cert/CertPathValidatorException.java b/src/share/classes/java/security/cert/CertPathValidatorException.java index 03cae751a0fecdbbe26c2b3874e17000246a875f..7e6b9165faecb3e394bcd669ffcab959907b0734 100644 --- a/src/share/classes/java/security/cert/CertPathValidatorException.java +++ b/src/share/classes/java/security/cert/CertPathValidatorException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,11 +34,11 @@ import java.security.GeneralSecurityException; * An exception indicating one of a variety of problems encountered when * validating a certification path. *

    - * A CertPathValidatorException provides support for wrapping + * A {@code CertPathValidatorException} provides support for wrapping * exceptions. The {@link #getCause getCause} method returns the throwable, * if any, that caused this exception to be thrown. *

    - * A CertPathValidatorException may also include the + * A {@code CertPathValidatorException} may also include the * certification path that was being validated when the exception was thrown, * the index of the certificate in the certification path that caused the * exception to be thrown, and the reason that caused the failure. Use the @@ -70,7 +70,7 @@ public class CertPathValidatorException extends GeneralSecurityException { private int index = -1; /** - * @serial the CertPath that was being validated when + * @serial the {@code CertPath} that was being validated when * the exception was thrown */ private CertPath certPath; @@ -81,7 +81,7 @@ public class CertPathValidatorException extends GeneralSecurityException { private Reason reason = BasicReason.UNSPECIFIED; /** - * Creates a CertPathValidatorException with + * Creates a {@code CertPathValidatorException} with * no detail message. */ public CertPathValidatorException() { @@ -89,8 +89,8 @@ public class CertPathValidatorException extends GeneralSecurityException { } /** - * Creates a CertPathValidatorException with the given - * detail message. A detail message is a String that + * Creates a {@code CertPathValidatorException} with the given + * detail message. A detail message is a {@code String} that * describes this particular exception. * * @param msg the detail message @@ -100,16 +100,16 @@ public class CertPathValidatorException extends GeneralSecurityException { } /** - * Creates a CertPathValidatorException that wraps the + * Creates a {@code CertPathValidatorException} that wraps the * specified throwable. This allows any exception to be converted into a - * CertPathValidatorException, while retaining information + * {@code CertPathValidatorException}, while retaining information * about the wrapped exception, which may be useful for debugging. The - * detail message is set to (cause==null ? null : cause.toString() - * ) (which typically contains the class and detail message of + * detail message is set to ({@code cause==null ? null : cause.toString()}) + * (which typically contains the class and detail message of * cause). * * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause getCause()} method). (A null value is + * {@link #getCause getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or unknown.) */ public CertPathValidatorException(Throwable cause) { @@ -117,12 +117,12 @@ public class CertPathValidatorException extends GeneralSecurityException { } /** - * Creates a CertPathValidatorException with the specified + * Creates a {@code CertPathValidatorException} with the specified * detail message and cause. * * @param msg the detail message * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause getCause()} method). (A null value is + * {@link #getCause getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or unknown.) */ public CertPathValidatorException(String msg, Throwable cause) { @@ -130,21 +130,21 @@ public class CertPathValidatorException extends GeneralSecurityException { } /** - * Creates a CertPathValidatorException with the specified + * Creates a {@code CertPathValidatorException} with the specified * detail message, cause, certification path, and index. * - * @param msg the detail message (or null if none) - * @param cause the cause (or null if none) + * @param msg the detail message (or {@code null} if none) + * @param cause the cause (or {@code null} if none) * @param certPath the certification path that was in the process of * being validated when the error was encountered * @param index the index of the certificate in the certification path * that caused the error (or -1 if not applicable). Note that - * the list of certificates in a CertPath is zero based. + * the list of certificates in a {@code CertPath} is zero based. * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < -1 || (certPath != null && index >= * certPath.getCertificates().size()) } - * @throws IllegalArgumentException if certPath is - * null and index is not -1 + * @throws IllegalArgumentException if {@code certPath} is + * {@code null} and {@code index} is not -1 */ public CertPathValidatorException(String msg, Throwable cause, CertPath certPath, int index) { @@ -152,23 +152,23 @@ public class CertPathValidatorException extends GeneralSecurityException { } /** - * Creates a CertPathValidatorException with the specified + * Creates a {@code CertPathValidatorException} with the specified * detail message, cause, certification path, index, and reason. * - * @param msg the detail message (or null if none) - * @param cause the cause (or null if none) + * @param msg the detail message (or {@code null} if none) + * @param cause the cause (or {@code null} if none) * @param certPath the certification path that was in the process of * being validated when the error was encountered * @param index the index of the certificate in the certification path * that caused the error (or -1 if not applicable). Note that - * the list of certificates in a CertPath is zero based. + * the list of certificates in a {@code CertPath} is zero based. * @param reason the reason the validation failed * @throws IndexOutOfBoundsException if the index is out of range * {@code (index < -1 || (certPath != null && index >= * certPath.getCertificates().size()) } - * @throws IllegalArgumentException if certPath is - * null and index is not -1 - * @throws NullPointerException if reason is null + * @throws IllegalArgumentException if {@code certPath} is + * {@code null} and {@code index} is not -1 + * @throws NullPointerException if {@code reason} is {@code null} * * @since 1.7 */ @@ -194,8 +194,8 @@ public class CertPathValidatorException extends GeneralSecurityException { * Returns the certification path that was being validated when * the exception was thrown. * - * @return the CertPath that was being validated when - * the exception was thrown (or null if not specified) + * @return the {@code CertPath} that was being validated when + * the exception was thrown (or {@code null} if not specified) */ public CertPath getCertPath() { return this.certPath; @@ -204,7 +204,7 @@ public class CertPathValidatorException extends GeneralSecurityException { /** * Returns the index of the certificate in the certification path * that caused the exception to be thrown. Note that the list of - * certificates in a CertPath is zero based. If no + * certificates in a {@code CertPath} is zero based. If no * index has been set, -1 is returned. * * @return the index that has been set, or -1 if none has been set @@ -219,7 +219,7 @@ public class CertPathValidatorException extends GeneralSecurityException { * {@link #getIndex}. * * @return the reason that the validation failed, or - * BasicReason.UNSPECIFIED if a reason has not been + * {@code BasicReason.UNSPECIFIED} if a reason has not been * specified * * @since 1.7 diff --git a/src/share/classes/java/security/cert/CertPathValidatorResult.java b/src/share/classes/java/security/cert/CertPathValidatorResult.java index 1756db6329ffc2525b19463c46a2ff582e186008..ae07dc497a9128f90aa45f3d76340acc9ec3d2ca 100644 --- a/src/share/classes/java/security/cert/CertPathValidatorResult.java +++ b/src/share/classes/java/security/cert/CertPathValidatorResult.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,10 +41,10 @@ package java.security.cert; public interface CertPathValidatorResult extends Cloneable { /** - * Makes a copy of this CertPathValidatorResult. Changes to the + * Makes a copy of this {@code CertPathValidatorResult}. Changes to the * copy will not affect the original and vice versa. * - * @return a copy of this CertPathValidatorResult + * @return a copy of this {@code CertPathValidatorResult} */ Object clone(); } diff --git a/src/share/classes/java/security/cert/CertPathValidatorSpi.java b/src/share/classes/java/security/cert/CertPathValidatorSpi.java index 6d3bd8c9968dd335410c954555237ab5094c57d3..50ad9c85c9bb86801339f4fb25bb2a4e54812270 100644 --- a/src/share/classes/java/security/cert/CertPathValidatorSpi.java +++ b/src/share/classes/java/security/cert/CertPathValidatorSpi.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,23 +31,23 @@ import java.security.InvalidAlgorithmParameterException; * * The Service Provider Interface (SPI) * for the {@link CertPathValidator CertPathValidator} class. All - * CertPathValidator implementations must include a class (the - * SPI class) that extends this class (CertPathValidatorSpi) + * {@code CertPathValidator} implementations must include a class (the + * SPI class) that extends this class ({@code CertPathValidatorSpi}) * and implements all of its methods. In general, instances of this class - * should only be accessed through the CertPathValidator class. + * should only be accessed through the {@code CertPathValidator} class. * For details, see the Java Cryptography Architecture. *

    * Concurrent Access *

    * Instances of this class need not be protected against concurrent * access from multiple threads. Threads that need to access a single - * CertPathValidatorSpi instance concurrently should synchronize + * {@code CertPathValidatorSpi} instance concurrently should synchronize * amongst themselves and provide the necessary locking before calling the - * wrapping CertPathValidator object. + * wrapping {@code CertPathValidator} object. *

    - * However, implementations of CertPathValidatorSpi may still + * However, implementations of {@code CertPathValidatorSpi} may still * encounter concurrency issues, since multiple threads each - * manipulating a different CertPathValidatorSpi instance need not + * manipulating a different {@code CertPathValidatorSpi} instance need not * synchronize. * * @since 1.4 @@ -64,20 +64,20 @@ public abstract class CertPathValidatorSpi { * Validates the specified certification path using the specified * algorithm parameter set. *

    - * The CertPath specified must be of a type that is + * The {@code CertPath} specified must be of a type that is * supported by the validation algorithm, otherwise an - * InvalidAlgorithmParameterException will be thrown. For - * example, a CertPathValidator that implements the PKIX - * algorithm validates CertPath objects of type X.509. + * {@code InvalidAlgorithmParameterException} will be thrown. For + * example, a {@code CertPathValidator} that implements the PKIX + * algorithm validates {@code CertPath} objects of type X.509. * - * @param certPath the CertPath to be validated + * @param certPath the {@code CertPath} to be validated * @param params the algorithm parameters * @return the result of the validation algorithm - * @exception CertPathValidatorException if the CertPath + * @exception CertPathValidatorException if the {@code CertPath} * does not validate * @exception InvalidAlgorithmParameterException if the specified - * parameters or the type of the specified CertPath are - * inappropriate for this CertPathValidator + * parameters or the type of the specified {@code CertPath} are + * inappropriate for this {@code CertPathValidator} */ public abstract CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) diff --git a/src/share/classes/java/security/cert/CertSelector.java b/src/share/classes/java/security/cert/CertSelector.java index 5ee1f7156cdc8ca522dd94f43f89df8ee12d5a05..a06cc848019d4bec6a55e06121e8700c71ea87a2 100644 --- a/src/share/classes/java/security/cert/CertSelector.java +++ b/src/share/classes/java/security/cert/CertSelector.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,9 +27,9 @@ package java.security.cert; /** * A selector that defines a set of criteria for selecting - * Certificates. Classes that implement this interface - * are often used to specify which Certificates should - * be retrieved from a CertStore. + * {@code Certificate}s. Classes that implement this interface + * are often used to specify which {@code Certificate}s should + * be retrieved from a {@code CertStore}. *

    * Concurrent Access *

    @@ -49,19 +49,19 @@ package java.security.cert; public interface CertSelector extends Cloneable { /** - * Decides whether a Certificate should be selected. + * Decides whether a {@code Certificate} should be selected. * - * @param cert the Certificate to be checked - * @return true if the Certificate - * should be selected, false otherwise + * @param cert the {@code Certificate} to be checked + * @return {@code true} if the {@code Certificate} + * should be selected, {@code false} otherwise */ boolean match(Certificate cert); /** - * Makes a copy of this CertSelector. Changes to the + * Makes a copy of this {@code CertSelector}. Changes to the * copy will not affect the original and vice versa. * - * @return a copy of this CertSelector + * @return a copy of this {@code CertSelector} */ Object clone(); } diff --git a/src/share/classes/java/security/cert/CertStore.java b/src/share/classes/java/security/cert/CertStore.java index 1c6dedbf53cc32fff3b372238dc9fa2edad6b7ee..1a8ed628c137be644d18e359e634907dce37b601 100644 --- a/src/share/classes/java/security/cert/CertStore.java +++ b/src/share/classes/java/security/cert/CertStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,32 +38,32 @@ import sun.security.jca.*; import sun.security.jca.GetInstance.Instance; /** - * A class for retrieving Certificates and CRLs + * A class for retrieving {@code Certificate}s and {@code CRL}s * from a repository. *

    * This class uses a provider-based architecture. - * To create a CertStore, call one of the static - * getInstance methods, passing in the type of - * CertStore desired, any applicable initialization parameters + * To create a {@code CertStore}, call one of the static + * {@code getInstance} methods, passing in the type of + * {@code CertStore} desired, any applicable initialization parameters * and optionally the name of the provider desired. *

    - * Once the CertStore has been created, it can be used to - * retrieve Certificates and CRLs by calling its + * Once the {@code CertStore} has been created, it can be used to + * retrieve {@code Certificate}s and {@code CRL}s by calling its * {@link #getCertificates(CertSelector selector) getCertificates} and * {@link #getCRLs(CRLSelector selector) getCRLs} methods. *

    * Unlike a {@link java.security.KeyStore KeyStore}, which provides access * to a cache of private keys and trusted certificates, a - * CertStore is designed to provide access to a potentially + * {@code CertStore} is designed to provide access to a potentially * vast repository of untrusted certificates and CRLs. For example, an LDAP - * implementation of CertStore provides access to certificates + * implementation of {@code CertStore} provides access to certificates * and CRLs stored in one or more directories using the LDAP protocol and the * schema as defined in the RFC service attribute. * *

    Every implementation of the Java platform is required to support the - * following standard CertStore type: + * following standard {@code CertStore} type: *

      - *
    • Collection
    • + *
    • {@code Collection}
    • *
    * This type is described in the @@ -75,10 +75,10 @@ import sun.security.jca.GetInstance.Instance; *

    * Concurrent Access *

    - * All public methods of CertStore objects must be thread-safe. + * All public methods of {@code CertStore} objects must be thread-safe. * That is, multiple threads may concurrently invoke these methods on a - * single CertStore object (or more than one) with no - * ill effects. This allows a CertPathBuilder to search for a + * single {@code CertStore} object (or more than one) with no + * ill effects. This allows a {@code CertPathBuilder} to search for a * CRL while simultaneously searching for further certificates, for instance. *

    * The static methods of this class are also guaranteed to be thread-safe. @@ -104,13 +104,13 @@ public class CertStore { private CertStoreParameters params; /** - * Creates a CertStore object of the given type, and + * Creates a {@code CertStore} object of the given type, and * encapsulates the given provider implementation (SPI object) in it. * * @param storeSpi the provider implementation * @param provider the provider * @param type the type - * @param params the initialization parameters (may be null) + * @param params the initialization parameters (may be {@code null}) */ protected CertStore(CertStoreSpi storeSpi, Provider provider, String type, CertStoreParameters params) { @@ -122,28 +122,28 @@ public class CertStore { } /** - * Returns a Collection of Certificates that - * match the specified selector. If no Certificates - * match the selector, an empty Collection will be returned. + * Returns a {@code Collection} of {@code Certificate}s that + * match the specified selector. If no {@code Certificate}s + * match the selector, an empty {@code Collection} will be returned. *

    - * For some CertStore types, the resulting - * Collection may not contain all of the - * Certificates that match the selector. For instance, - * an LDAP CertStore may not search all entries in the + * For some {@code CertStore} types, the resulting + * {@code Collection} may not contain all of the + * {@code Certificate}s that match the selector. For instance, + * an LDAP {@code CertStore} may not search all entries in the * directory. Instead, it may just search entries that are likely to - * contain the Certificates it is looking for. + * contain the {@code Certificate}s it is looking for. *

    - * Some CertStore implementations (especially LDAP - * CertStores) may throw a CertStoreException - * unless a non-null CertSelector is provided that + * Some {@code CertStore} implementations (especially LDAP + * {@code CertStore}s) may throw a {@code CertStoreException} + * unless a non-null {@code CertSelector} is provided that * includes specific criteria that can be used to find the certificates. * Issuer and/or subject names are especially useful criteria. * - * @param selector A CertSelector used to select which - * Certificates should be returned. Specify null - * to return all Certificates (if supported). - * @return A Collection of Certificates that - * match the specified selector (never null) + * @param selector A {@code CertSelector} used to select which + * {@code Certificate}s should be returned. Specify {@code null} + * to return all {@code Certificate}s (if supported). + * @return A {@code Collection} of {@code Certificate}s that + * match the specified selector (never {@code null}) * @throws CertStoreException if an exception occurs */ public final Collection getCertificates @@ -152,28 +152,28 @@ public class CertStore { } /** - * Returns a Collection of CRLs that - * match the specified selector. If no CRLs - * match the selector, an empty Collection will be returned. + * Returns a {@code Collection} of {@code CRL}s that + * match the specified selector. If no {@code CRL}s + * match the selector, an empty {@code Collection} will be returned. *

    - * For some CertStore types, the resulting - * Collection may not contain all of the - * CRLs that match the selector. For instance, - * an LDAP CertStore may not search all entries in the + * For some {@code CertStore} types, the resulting + * {@code Collection} may not contain all of the + * {@code CRL}s that match the selector. For instance, + * an LDAP {@code CertStore} may not search all entries in the * directory. Instead, it may just search entries that are likely to - * contain the CRLs it is looking for. + * contain the {@code CRL}s it is looking for. *

    - * Some CertStore implementations (especially LDAP - * CertStores) may throw a CertStoreException - * unless a non-null CRLSelector is provided that + * Some {@code CertStore} implementations (especially LDAP + * {@code CertStore}s) may throw a {@code CertStoreException} + * unless a non-null {@code CRLSelector} is provided that * includes specific criteria that can be used to find the CRLs. * Issuer names and/or the certificate to be checked are especially useful. * - * @param selector A CRLSelector used to select which - * CRLs should be returned. Specify null - * to return all CRLs (if supported). - * @return A Collection of CRLs that - * match the specified selector (never null) + * @param selector A {@code CRLSelector} used to select which + * {@code CRL}s should be returned. Specify {@code null} + * to return all {@code CRL}s (if supported). + * @return A {@code Collection} of {@code CRL}s that + * match the specified selector (never {@code null}) * @throws CertStoreException if an exception occurs */ public final Collection getCRLs(CRLSelector selector) @@ -182,8 +182,8 @@ public class CertStore { } /** - * Returns a CertStore object that implements the specified - * CertStore type and is initialized with the specified + * Returns a {@code CertStore} object that implements the specified + * {@code CertStore} type and is initialized with the specified * parameters. * *

    This method traverses the list of registered security Providers, @@ -195,29 +195,29 @@ public class CertStore { *

    Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * - *

    The CertStore that is returned is initialized with the - * specified CertStoreParameters. The type of parameters - * needed may vary between different types of CertStores. - * Note that the specified CertStoreParameters object is + *

    The {@code CertStore} that is returned is initialized with the + * specified {@code CertStoreParameters}. The type of parameters + * needed may vary between different types of {@code CertStore}s. + * Note that the specified {@code CertStoreParameters} object is * cloned. * - * @param type the name of the requested CertStore type. + * @param type the name of the requested {@code CertStore} type. * See the CertStore section in the * Java Cryptography Architecture Standard Algorithm Name Documentation * for information about standard types. * - * @param params the initialization parameters (may be null). + * @param params the initialization parameters (may be {@code null}). * - * @return a CertStore object that implements the specified - * CertStore type. + * @return a {@code CertStore} object that implements the specified + * {@code CertStore} type. * * @throws NoSuchAlgorithmException if no Provider supports a * CertStoreSpi implementation for the specified type. * * @throws InvalidAlgorithmParameterException if the specified * initialization parameters are inappropriate for this - * CertStore. + * {@code CertStore}. * * @see java.security.Provider */ @@ -244,8 +244,8 @@ public class CertStore { } /** - * Returns a CertStore object that implements the specified - * CertStore type. + * Returns a {@code CertStore} object that implements the specified + * {@code CertStore} type. * *

    A new CertStore object encapsulating the * CertStoreSpi implementation from the specified provider @@ -255,23 +255,23 @@ public class CertStore { *

    Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * - *

    The CertStore that is returned is initialized with the - * specified CertStoreParameters. The type of parameters - * needed may vary between different types of CertStores. - * Note that the specified CertStoreParameters object is + *

    The {@code CertStore} that is returned is initialized with the + * specified {@code CertStoreParameters}. The type of parameters + * needed may vary between different types of {@code CertStore}s. + * Note that the specified {@code CertStoreParameters} object is * cloned. * - * @param type the requested CertStore type. + * @param type the requested {@code CertStore} type. * See the CertStore section in the * Java Cryptography Architecture Standard Algorithm Name Documentation * for information about standard types. * - * @param params the initialization parameters (may be null). + * @param params the initialization parameters (may be {@code null}). * * @param provider the name of the provider. * - * @return a CertStore object that implements the + * @return a {@code CertStore} object that implements the * specified type. * * @throws NoSuchAlgorithmException if a CertStoreSpi @@ -280,12 +280,12 @@ public class CertStore { * * @throws InvalidAlgorithmParameterException if the specified * initialization parameters are inappropriate for this - * CertStore. + * {@code CertStore}. * * @throws NoSuchProviderException if the specified provider is not * registered in the security provider list. * - * @exception IllegalArgumentException if the provider is + * @exception IllegalArgumentException if the {@code provider} is * null or empty. * * @see java.security.Provider @@ -305,31 +305,31 @@ public class CertStore { } /** - * Returns a CertStore object that implements the specified - * CertStore type. + * Returns a {@code CertStore} object that implements the specified + * {@code CertStore} type. * *

    A new CertStore object encapsulating the * CertStoreSpi implementation from the specified Provider * object is returned. Note that the specified Provider object * does not have to be registered in the provider list. * - *

    The CertStore that is returned is initialized with the - * specified CertStoreParameters. The type of parameters - * needed may vary between different types of CertStores. - * Note that the specified CertStoreParameters object is + *

    The {@code CertStore} that is returned is initialized with the + * specified {@code CertStoreParameters}. The type of parameters + * needed may vary between different types of {@code CertStore}s. + * Note that the specified {@code CertStoreParameters} object is * cloned. * - * @param type the requested CertStore type. + * @param type the requested {@code CertStore} type. * See the CertStore section in the * Java Cryptography Architecture Standard Algorithm Name Documentation * for information about standard types. * - * @param params the initialization parameters (may be null). + * @param params the initialization parameters (may be {@code null}). * * @param provider the provider. * - * @return a CertStore object that implements the + * @return a {@code CertStore} object that implements the * specified type. * * @exception NoSuchAlgorithmException if a CertStoreSpi @@ -338,9 +338,9 @@ public class CertStore { * * @throws InvalidAlgorithmParameterException if the specified * initialization parameters are inappropriate for this - * CertStore + * {@code CertStore} * - * @exception IllegalArgumentException if the provider is + * @exception IllegalArgumentException if the {@code provider} is * null. * * @see java.security.Provider @@ -359,30 +359,30 @@ public class CertStore { } /** - * Returns the parameters used to initialize this CertStore. - * Note that the CertStoreParameters object is cloned before + * Returns the parameters used to initialize this {@code CertStore}. + * Note that the {@code CertStoreParameters} object is cloned before * it is returned. * - * @return the parameters used to initialize this CertStore - * (may be null) + * @return the parameters used to initialize this {@code CertStore} + * (may be {@code null}) */ public final CertStoreParameters getCertStoreParameters() { return (params == null ? null : (CertStoreParameters) params.clone()); } /** - * Returns the type of this CertStore. + * Returns the type of this {@code CertStore}. * - * @return the type of this CertStore + * @return the type of this {@code CertStore} */ public final String getType() { return this.type; } /** - * Returns the provider of this CertStore. + * Returns the provider of this {@code CertStore}. * - * @return the provider of this CertStore + * @return the provider of this {@code CertStore} */ public final Provider getProvider() { return this.provider; diff --git a/src/share/classes/java/security/cert/CertStoreException.java b/src/share/classes/java/security/cert/CertStoreException.java index 31baf644e302342e18a77bd5fe2e12480fa337ba..77b1c234664486d45d96a7b9ed7b8f91ddd62717 100644 --- a/src/share/classes/java/security/cert/CertStoreException.java +++ b/src/share/classes/java/security/cert/CertStoreException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,9 +29,9 @@ import java.security.GeneralSecurityException; /** * An exception indicating one of a variety of problems retrieving - * certificates and CRLs from a CertStore. + * certificates and CRLs from a {@code CertStore}. *

    - * A CertStoreException provides support for wrapping + * A {@code CertStoreException} provides support for wrapping * exceptions. The {@link #getCause getCause} method returns the throwable, * if any, that caused this exception to be thrown. *

    @@ -53,7 +53,7 @@ public class CertStoreException extends GeneralSecurityException { private static final long serialVersionUID = 2395296107471573245L; /** - * Creates a CertStoreException with null as + * Creates a {@code CertStoreException} with {@code null} as * its detail message. */ public CertStoreException() { @@ -61,8 +61,8 @@ public class CertStoreException extends GeneralSecurityException { } /** - * Creates a CertStoreException with the given detail - * message. A detail message is a String that describes this + * Creates a {@code CertStoreException} with the given detail + * message. A detail message is a {@code String} that describes this * particular exception. * * @param msg the detail message @@ -72,15 +72,15 @@ public class CertStoreException extends GeneralSecurityException { } /** - * Creates a CertStoreException that wraps the specified + * Creates a {@code CertStoreException} that wraps the specified * throwable. This allows any exception to be converted into a - * CertStoreException, while retaining information about the + * {@code CertStoreException}, while retaining information about the * cause, which may be useful for debugging. The detail message is - * set to (cause==null ? null : cause.toString()) (which + * set to ({@code cause==null ? null : cause.toString()}) (which * typically contains the class and detail message of cause). * * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause getCause()} method). (A null value is + * {@link #getCause getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or unknown.) */ public CertStoreException(Throwable cause) { @@ -88,12 +88,12 @@ public class CertStoreException extends GeneralSecurityException { } /** - * Creates a CertStoreException with the specified detail + * Creates a {@code CertStoreException} with the specified detail * message and cause. * * @param msg the detail message * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause getCause()} method). (A null value is + * {@link #getCause getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or unknown.) */ public CertStoreException(String msg, Throwable cause) { diff --git a/src/share/classes/java/security/cert/CertStoreParameters.java b/src/share/classes/java/security/cert/CertStoreParameters.java index d410dc7f3320c9e18cd5ea0d38065466e8958504..9938ba2543880fc803ff3de76f51020becd2b38f 100644 --- a/src/share/classes/java/security/cert/CertStoreParameters.java +++ b/src/share/classes/java/security/cert/CertStoreParameters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,20 +26,20 @@ package java.security.cert; /** - * A specification of CertStore parameters. + * A specification of {@code CertStore} parameters. *

    * The purpose of this interface is to group (and provide type safety for) - * all CertStore parameter specifications. All - * CertStore parameter specifications must implement this + * all {@code CertStore} parameter specifications. All + * {@code CertStore} parameter specifications must implement this * interface. *

    - * Typically, a CertStoreParameters object is passed as a parameter + * Typically, a {@code CertStoreParameters} object is passed as a parameter * to one of the {@link CertStore#getInstance CertStore.getInstance} methods. - * The getInstance method returns a CertStore that - * is used for retrieving Certificates and CRLs. The - * CertStore that is returned is initialized with the specified + * The {@code getInstance} method returns a {@code CertStore} that + * is used for retrieving {@code Certificate}s and {@code CRL}s. The + * {@code CertStore} that is returned is initialized with the specified * parameters. The type of parameters needed may vary between different types - * of CertStores. + * of {@code CertStore}s. * * @see CertStore#getInstance * @@ -49,32 +49,32 @@ package java.security.cert; public interface CertStoreParameters extends Cloneable { /** - * Makes a copy of this CertStoreParameters. + * Makes a copy of this {@code CertStoreParameters}. *

    * The precise meaning of "copy" may depend on the class of - * the CertStoreParameters object. A typical implementation + * the {@code CertStoreParameters} object. A typical implementation * performs a "deep copy" of this object, but this is not an absolute * requirement. Some implementations may perform a "shallow copy" of some * or all of the fields of this object. *

    - * Note that the CertStore.getInstance methods make a copy - * of the specified CertStoreParameters. A deep copy - * implementation of clone is safer and more robust, as it - * prevents the caller from corrupting a shared CertStore by + * Note that the {@code CertStore.getInstance} methods make a copy + * of the specified {@code CertStoreParameters}. A deep copy + * implementation of {@code clone} is safer and more robust, as it + * prevents the caller from corrupting a shared {@code CertStore} by * subsequently modifying the contents of its initialization parameters. - * However, a shallow copy implementation of clone is more + * However, a shallow copy implementation of {@code clone} is more * appropriate for applications that need to hold a reference to a - * parameter contained in the CertStoreParameters. For example, + * parameter contained in the {@code CertStoreParameters}. For example, * a shallow copy clone allows an application to release the resources of - * a particular CertStore initialization parameter immediately, + * a particular {@code CertStore} initialization parameter immediately, * rather than waiting for the garbage collection mechanism. This should - * be done with the utmost care, since the CertStore may still + * be done with the utmost care, since the {@code CertStore} may still * be in use by other threads. *

    * Each subclass should state the precise behavior of this method so * that users and developers know what to expect. * - * @return a copy of this CertStoreParameters + * @return a copy of this {@code CertStoreParameters} */ Object clone(); } diff --git a/src/share/classes/java/security/cert/CertStoreSpi.java b/src/share/classes/java/security/cert/CertStoreSpi.java index ddcf2bc3f37b2f3c737d5338a2ba725379fd2976..fc98e9ebcf0b7da06349b219f73e1ab985e0cff2 100644 --- a/src/share/classes/java/security/cert/CertStoreSpi.java +++ b/src/share/classes/java/security/cert/CertStoreSpi.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,26 +30,26 @@ import java.util.Collection; /** * The Service Provider Interface (SPI) - * for the {@link CertStore CertStore} class. All CertStore + * for the {@link CertStore CertStore} class. All {@code CertStore} * implementations must include a class (the SPI class) that extends - * this class (CertStoreSpi), provides a constructor with - * a single argument of type CertStoreParameters, and implements + * this class ({@code CertStoreSpi}), provides a constructor with + * a single argument of type {@code CertStoreParameters}, and implements * all of its methods. In general, instances of this class should only be - * accessed through the CertStore class. + * accessed through the {@code CertStore} class. * For details, see the Java Cryptography Architecture. *

    * Concurrent Access *

    - * The public methods of all CertStoreSpi objects must be + * The public methods of all {@code CertStoreSpi} objects must be * thread-safe. That is, multiple threads may concurrently invoke these - * methods on a single CertStoreSpi object (or more than one) - * with no ill effects. This allows a CertPathBuilder to search + * methods on a single {@code CertStoreSpi} object (or more than one) + * with no ill effects. This allows a {@code CertPathBuilder} to search * for a CRL while simultaneously searching for further certificates, for * instance. *

    - * Simple CertStoreSpi implementations will probably ensure - * thread safety by adding a synchronized keyword to their - * engineGetCertificates and engineGetCRLs methods. + * Simple {@code CertStoreSpi} implementations will probably ensure + * thread safety by adding a {@code synchronized} keyword to their + * {@code engineGetCertificates} and {@code engineGetCRLs} methods. * More sophisticated ones may allow truly concurrent access. * * @since 1.4 @@ -60,64 +60,64 @@ public abstract class CertStoreSpi { /** * The sole constructor. * - * @param params the initialization parameters (may be null) + * @param params the initialization parameters (may be {@code null}) * @throws InvalidAlgorithmParameterException if the initialization - * parameters are inappropriate for this CertStoreSpi + * parameters are inappropriate for this {@code CertStoreSpi} */ public CertStoreSpi(CertStoreParameters params) throws InvalidAlgorithmParameterException { } /** - * Returns a Collection of Certificates that - * match the specified selector. If no Certificates - * match the selector, an empty Collection will be returned. + * Returns a {@code Collection} of {@code Certificate}s that + * match the specified selector. If no {@code Certificate}s + * match the selector, an empty {@code Collection} will be returned. *

    - * For some CertStore types, the resulting - * Collection may not contain all of the - * Certificates that match the selector. For instance, - * an LDAP CertStore may not search all entries in the + * For some {@code CertStore} types, the resulting + * {@code Collection} may not contain all of the + * {@code Certificate}s that match the selector. For instance, + * an LDAP {@code CertStore} may not search all entries in the * directory. Instead, it may just search entries that are likely to - * contain the Certificates it is looking for. + * contain the {@code Certificate}s it is looking for. *

    - * Some CertStore implementations (especially LDAP - * CertStores) may throw a CertStoreException - * unless a non-null CertSelector is provided that includes + * Some {@code CertStore} implementations (especially LDAP + * {@code CertStore}s) may throw a {@code CertStoreException} + * unless a non-null {@code CertSelector} is provided that includes * specific criteria that can be used to find the certificates. Issuer * and/or subject names are especially useful criteria. * - * @param selector A CertSelector used to select which - * Certificates should be returned. Specify null - * to return all Certificates (if supported). - * @return A Collection of Certificates that - * match the specified selector (never null) + * @param selector A {@code CertSelector} used to select which + * {@code Certificate}s should be returned. Specify {@code null} + * to return all {@code Certificate}s (if supported). + * @return A {@code Collection} of {@code Certificate}s that + * match the specified selector (never {@code null}) * @throws CertStoreException if an exception occurs */ public abstract Collection engineGetCertificates (CertSelector selector) throws CertStoreException; /** - * Returns a Collection of CRLs that - * match the specified selector. If no CRLs - * match the selector, an empty Collection will be returned. + * Returns a {@code Collection} of {@code CRL}s that + * match the specified selector. If no {@code CRL}s + * match the selector, an empty {@code Collection} will be returned. *

    - * For some CertStore types, the resulting - * Collection may not contain all of the - * CRLs that match the selector. For instance, - * an LDAP CertStore may not search all entries in the + * For some {@code CertStore} types, the resulting + * {@code Collection} may not contain all of the + * {@code CRL}s that match the selector. For instance, + * an LDAP {@code CertStore} may not search all entries in the * directory. Instead, it may just search entries that are likely to - * contain the CRLs it is looking for. + * contain the {@code CRL}s it is looking for. *

    - * Some CertStore implementations (especially LDAP - * CertStores) may throw a CertStoreException - * unless a non-null CRLSelector is provided that includes + * Some {@code CertStore} implementations (especially LDAP + * {@code CertStore}s) may throw a {@code CertStoreException} + * unless a non-null {@code CRLSelector} is provided that includes * specific criteria that can be used to find the CRLs. Issuer names * and/or the certificate to be checked are especially useful. * - * @param selector A CRLSelector used to select which - * CRLs should be returned. Specify null - * to return all CRLs (if supported). - * @return A Collection of CRLs that - * match the specified selector (never null) + * @param selector A {@code CRLSelector} used to select which + * {@code CRL}s should be returned. Specify {@code null} + * to return all {@code CRL}s (if supported). + * @return A {@code Collection} of {@code CRL}s that + * match the specified selector (never {@code null}) * @throws CertStoreException if an exception occurs */ public abstract Collection engineGetCRLs diff --git a/src/share/classes/java/security/cert/Certificate.java b/src/share/classes/java/security/cert/Certificate.java index 80390ac129c3f09af59ee2e57a5611f7c354d4bc..638a02e6f806686024f96a389dc9aef0b26364d7 100644 --- a/src/share/classes/java/security/cert/Certificate.java +++ b/src/share/classes/java/security/cert/Certificate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -90,8 +90,8 @@ public abstract class Certificate implements java.io.Serializable { /** * Compares this certificate for equality with the specified - * object. If the other object is an - * instanceof Certificate, then + * object. If the {@code other} object is an + * {@code instanceof} {@code Certificate}, then * its encoded form is retrieved and compared with the * encoded form of this certificate. * @@ -196,8 +196,8 @@ public abstract class Certificate implements java.io.Serializable { * *

    This method was added to version 1.8 of the Java Platform * Standard Edition. In order to maintain backwards compatibility with - * existing service providers, this method cannot be abstract - * and by default throws an UnsupportedOperationException. + * existing service providers, this method cannot be {@code abstract} + * and by default throws an {@code UnsupportedOperationException}. * * @param key the PublicKey used to carry out the verification. * @param sigProvider the signature provider. diff --git a/src/share/classes/java/security/cert/CertificateEncodingException.java b/src/share/classes/java/security/cert/CertificateEncodingException.java index dbfc22ca8cea5a592fade2f40488f6957fca609b..618ee0a55b93410f12e99d961d99987b581fe01e 100644 --- a/src/share/classes/java/security/cert/CertificateEncodingException.java +++ b/src/share/classes/java/security/cert/CertificateEncodingException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -56,13 +56,13 @@ public class CertificateEncodingException extends CertificateException { } /** - * Creates a CertificateEncodingException with the specified + * Creates a {@code CertificateEncodingException} with the specified * detail message and cause. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, + * {@link #getCause()} method). (A {@code null} value is permitted, * and indicates that the cause is nonexistent or unknown.) * @since 1.5 */ @@ -71,14 +71,14 @@ public class CertificateEncodingException extends CertificateException { } /** - * Creates a CertificateEncodingException + * Creates a {@code CertificateEncodingException} * with the specified cause and a detail message of - * (cause==null ? null : cause.toString()) + * {@code (cause==null ? null : cause.toString())} * (which typically contains the class and detail message of - * cause). + * {@code cause}). * * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, + * {@link #getCause()} method). (A {@code null} value is permitted, * and indicates that the cause is nonexistent or unknown.) * @since 1.5 */ diff --git a/src/share/classes/java/security/cert/CertificateException.java b/src/share/classes/java/security/cert/CertificateException.java index 1c91f9f0ebb0c997af491960720a438ea8168e3d..f663054000b1130c98c4fbd5a61336e19fad9b0a 100644 --- a/src/share/classes/java/security/cert/CertificateException.java +++ b/src/share/classes/java/security/cert/CertificateException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,13 +57,13 @@ public class CertificateException extends GeneralSecurityException { } /** - * Creates a CertificateException with the specified + * Creates a {@code CertificateException} with the specified * detail message and cause. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, + * {@link #getCause()} method). (A {@code null} value is permitted, * and indicates that the cause is nonexistent or unknown.) * @since 1.5 */ @@ -72,13 +72,13 @@ public class CertificateException extends GeneralSecurityException { } /** - * Creates a CertificateException with the specified cause - * and a detail message of (cause==null ? null : cause.toString()) + * Creates a {@code CertificateException} with the specified cause + * and a detail message of {@code (cause==null ? null : cause.toString())} * (which typically contains the class and detail message of - * cause). + * {@code cause}). * * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, + * {@link #getCause()} method). (A {@code null} value is permitted, * and indicates that the cause is nonexistent or unknown.) * @since 1.5 */ diff --git a/src/share/classes/java/security/cert/CertificateExpiredException.java b/src/share/classes/java/security/cert/CertificateExpiredException.java index e5644fa7ff098445c2fa8b1a1eacaaeb94d85b43..9de0c236c1373bf7f8c3a6358b1e69f518e7098d 100644 --- a/src/share/classes/java/security/cert/CertificateExpiredException.java +++ b/src/share/classes/java/security/cert/CertificateExpiredException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,8 +27,8 @@ package java.security.cert; /** * Certificate Expired Exception. This is thrown whenever the current - * Date or the specified Date is after the - * notAfter date/time specified in the validity period + * {@code Date} or the specified {@code Date} is after the + * {@code notAfter} date/time specified in the validity period * of the certificate. * * @author Hemma Prafullchandra diff --git a/src/share/classes/java/security/cert/CertificateFactory.java b/src/share/classes/java/security/cert/CertificateFactory.java index d0762df16be2a656a05901216a55c457de3f04e0..83ff9fbee927562674c5d00b2e9ca26a0d2d196b 100644 --- a/src/share/classes/java/security/cert/CertificateFactory.java +++ b/src/share/classes/java/security/cert/CertificateFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,27 +41,27 @@ import sun.security.jca.GetInstance.Instance; /** * This class defines the functionality of a certificate factory, which is - * used to generate certificate, certification path (CertPath) + * used to generate certificate, certification path ({@code CertPath}) * and certificate revocation list (CRL) objects from their encodings. * *

    For encodings consisting of multiple certificates, use - * generateCertificates when you want to + * {@code generateCertificates} when you want to * parse a collection of possibly unrelated certificates. Otherwise, - * use generateCertPath when you want to generate - * a CertPath (a certificate chain) and subsequently - * validate it with a CertPathValidator. + * use {@code generateCertPath} when you want to generate + * a {@code CertPath} (a certificate chain) and subsequently + * validate it with a {@code CertPathValidator}. * *

    A certificate factory for X.509 must return certificates that are an - * instance of java.security.cert.X509Certificate, and CRLs - * that are an instance of java.security.cert.X509CRL. + * instance of {@code java.security.cert.X509Certificate}, and CRLs + * that are an instance of {@code java.security.cert.X509CRL}. * *

    The following example reads a file with Base64 encoded certificates, * which are each bounded at the beginning by -----BEGIN CERTIFICATE-----, and * bounded at the end by -----END CERTIFICATE-----. We convert the - * FileInputStream (which does not support mark - * and reset) to a BufferedInputStream (which + * {@code FileInputStream} (which does not support {@code mark} + * and {@code reset}) to a {@code BufferedInputStream} (which * supports those methods), so that each call to - * generateCertificate consumes only one certificate, and the + * {@code generateCertificate} consumes only one certificate, and the * read position of the input stream is positioned to the next certificate in * the file:

    * @@ -92,14 +92,14 @@ import sun.security.jca.GetInstance.Instance; * * *

    Every implementation of the Java platform is required to support the - * following standard CertificateFactory type: + * following standard {@code CertificateFactory} type: *

      - *
    • X.509
    • + *
    • {@code X.509}
    • *
    - * and the following standard CertPath encodings: + * and the following standard {@code CertPath} encodings: *
      - *
    • PKCS7
    • - *
    • PkiPath
    • + *
    • {@code PKCS7}
    • + *
    • {@code PkiPath}
    • *
    * The type and encodings are described in the @@ -258,7 +258,7 @@ public class CertificateFactory { * implementation for the specified algorithm is not available * from the specified Provider object. * - * @exception IllegalArgumentException if the provider is + * @exception IllegalArgumentException if the {@code provider} is * null. * * @see java.security.Provider @@ -299,17 +299,17 @@ public class CertificateFactory { /** * Generates a certificate object and initializes it with - * the data read from the input stream inStream. + * the data read from the input stream {@code inStream}. * *

    In order to take advantage of the specialized certificate format * supported by this certificate factory, * the returned certificate object can be typecast to the corresponding * certificate class. For example, if this certificate * factory implements X.509 certificates, the returned certificate object - * can be typecast to the X509Certificate class. + * can be typecast to the {@code X509Certificate} class. * *

    In the case of a certificate factory for X.509 certificates, the - * certificate provided in inStream must be DER-encoded and + * certificate provided in {@code inStream} must be DER-encoded and * may be supplied in binary or printable (Base64) encoding. If the * certificate is provided in Base64 encoding, it must be bounded at * the beginning by -----BEGIN CERTIFICATE-----, and must be bounded at @@ -324,7 +324,7 @@ public class CertificateFactory { * the inherent end-of-certificate marker. If the data in the input stream * does not contain an inherent end-of-certificate marker (other * than EOF) and there is trailing data after the certificate is parsed, a - * CertificateException is thrown. + * {@code CertificateException} is thrown. * * @param inStream an input stream with the certificate data. * @@ -340,19 +340,19 @@ public class CertificateFactory { } /** - * Returns an iteration of the CertPath encodings supported + * Returns an iteration of the {@code CertPath} encodings supported * by this certificate factory, with the default encoding first. See * the CertPath Encodings section in the * Java Cryptography Architecture Standard Algorithm Name Documentation * for information about standard encoding names and their formats. *

    - * Attempts to modify the returned Iterator via its - * remove method result in an - * UnsupportedOperationException. + * Attempts to modify the returned {@code Iterator} via its + * {@code remove} method result in an + * {@code UnsupportedOperationException}. * - * @return an Iterator over the names of the supported - * CertPath encodings (as Strings) + * @return an {@code Iterator} over the names of the supported + * {@code CertPath} encodings (as {@code String}s) * @since 1.4 */ public final Iterator getCertPathEncodings() { @@ -360,15 +360,15 @@ public class CertificateFactory { } /** - * Generates a CertPath object and initializes it with - * the data read from the InputStream inStream. The data + * Generates a {@code CertPath} object and initializes it with + * the data read from the {@code InputStream} inStream. The data * is assumed to be in the default encoding. The name of the default - * encoding is the first element of the Iterator returned by + * encoding is the first element of the {@code Iterator} returned by * the {@link #getCertPathEncodings getCertPathEncodings} method. * - * @param inStream an InputStream containing the data - * @return a CertPath initialized with the data from the - * InputStream + * @param inStream an {@code InputStream} containing the data + * @return a {@code CertPath} initialized with the data from the + * {@code InputStream} * @exception CertificateException if an exception occurs while decoding * @since 1.4 */ @@ -379,18 +379,18 @@ public class CertificateFactory { } /** - * Generates a CertPath object and initializes it with - * the data read from the InputStream inStream. The data + * Generates a {@code CertPath} object and initializes it with + * the data read from the {@code InputStream} inStream. The data * is assumed to be in the specified encoding. See * the CertPath Encodings section in the * Java Cryptography Architecture Standard Algorithm Name Documentation * for information about standard encoding names and their formats. * - * @param inStream an InputStream containing the data + * @param inStream an {@code InputStream} containing the data * @param encoding the encoding used for the data - * @return a CertPath initialized with the data from the - * InputStream + * @return a {@code CertPath} initialized with the data from the + * {@code InputStream} * @exception CertificateException if an exception occurs while decoding or * the encoding requested is not supported * @since 1.4 @@ -402,15 +402,15 @@ public class CertificateFactory { } /** - * Generates a CertPath object and initializes it with - * a List of Certificates. + * Generates a {@code CertPath} object and initializes it with + * a {@code List} of {@code Certificate}s. *

    * The certificates supplied must be of a type supported by the - * CertificateFactory. They will be copied out of the supplied - * List object. + * {@code CertificateFactory}. They will be copied out of the supplied + * {@code List} object. * - * @param certificates a List of Certificates - * @return a CertPath initialized with the supplied list of + * @param certificates a {@code List} of {@code Certificate}s + * @return a {@code CertPath} initialized with the supplied list of * certificates * @exception CertificateException if an exception occurs * @since 1.4 @@ -424,20 +424,20 @@ public class CertificateFactory { /** * Returns a (possibly empty) collection view of the certificates read - * from the given input stream inStream. + * from the given input stream {@code inStream}. * *

    In order to take advantage of the specialized certificate format * supported by this certificate factory, each element in * the returned collection view can be typecast to the corresponding * certificate class. For example, if this certificate * factory implements X.509 certificates, the elements in the returned - * collection can be typecast to the X509Certificate class. + * collection can be typecast to the {@code X509Certificate} class. * *

    In the case of a certificate factory for X.509 certificates, - * inStream may contain a sequence of DER-encoded certificates + * {@code inStream} may contain a sequence of DER-encoded certificates * in the formats described for * {@link #generateCertificate(java.io.InputStream) generateCertificate}. - * In addition, inStream may contain a PKCS#7 certificate + * In addition, {@code inStream} may contain a PKCS#7 certificate * chain. This is a PKCS#7 SignedData object, with the only * significant field being certificates. In particular, the * signature and the contents are ignored. This format allows multiple @@ -464,14 +464,14 @@ public class CertificateFactory { /** * Generates a certificate revocation list (CRL) object and initializes it - * with the data read from the input stream inStream. + * with the data read from the input stream {@code inStream}. * *

    In order to take advantage of the specialized CRL format * supported by this certificate factory, * the returned CRL object can be typecast to the corresponding * CRL class. For example, if this certificate * factory implements X.509 CRLs, the returned CRL object - * can be typecast to the X509CRL class. + * can be typecast to the {@code X509CRL} class. * *

    Note that if the given input stream does not support * {@link java.io.InputStream#mark(int) mark} and @@ -482,7 +482,7 @@ public class CertificateFactory { * end-of-CRL marker. If the data in the * input stream does not contain an inherent end-of-CRL marker (other * than EOF) and there is trailing data after the CRL is parsed, a - * CRLException is thrown. + * {@code CRLException} is thrown. * * @param inStream an input stream with the CRL data. * @@ -499,18 +499,18 @@ public class CertificateFactory { /** * Returns a (possibly empty) collection view of the CRLs read - * from the given input stream inStream. + * from the given input stream {@code inStream}. * *

    In order to take advantage of the specialized CRL format * supported by this certificate factory, each element in * the returned collection view can be typecast to the corresponding * CRL class. For example, if this certificate * factory implements X.509 CRLs, the elements in the returned - * collection can be typecast to the X509CRL class. + * collection can be typecast to the {@code X509CRL} class. * *

    In the case of a certificate factory for X.509 CRLs, - * inStream may contain a sequence of DER-encoded CRLs. - * In addition, inStream may contain a PKCS#7 CRL + * {@code inStream} may contain a sequence of DER-encoded CRLs. + * In addition, {@code inStream} may contain a PKCS#7 CRL * set. This is a PKCS#7 SignedData object, with the only * significant field being crls. In particular, the * signature and the contents are ignored. This format allows multiple diff --git a/src/share/classes/java/security/cert/CertificateFactorySpi.java b/src/share/classes/java/security/cert/CertificateFactorySpi.java index 0912ba2a9f925d6b98dc8a21c837dd3ef4e651bb..35aee847bb83c5756771821484acf8484325612f 100644 --- a/src/share/classes/java/security/cert/CertificateFactorySpi.java +++ b/src/share/classes/java/security/cert/CertificateFactorySpi.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,18 +35,18 @@ import java.security.NoSuchProviderException; /** * This class defines the Service Provider Interface (SPI) - * for the CertificateFactory class. + * for the {@code CertificateFactory} class. * All the abstract methods in this class must be implemented by each * cryptographic service provider who wishes to supply the implementation * of a certificate factory for a particular certificate type, e.g., X.509. * *

    Certificate factories are used to generate certificate, certification path - * (CertPath) and certificate revocation list (CRL) objects from + * ({@code CertPath}) and certificate revocation list (CRL) objects from * their encodings. * *

    A certificate factory for X.509 must return certificates that are an - * instance of java.security.cert.X509Certificate, and CRLs - * that are an instance of java.security.cert.X509CRL. + * instance of {@code java.security.cert.X509Certificate}, and CRLs + * that are an instance of {@code java.security.cert.X509CRL}. * * @author Hemma Prafullchandra * @author Jan Luehe @@ -67,17 +67,17 @@ public abstract class CertificateFactorySpi { /** * Generates a certificate object and initializes it with - * the data read from the input stream inStream. + * the data read from the input stream {@code inStream}. * *

    In order to take advantage of the specialized certificate format * supported by this certificate factory, * the returned certificate object can be typecast to the corresponding * certificate class. For example, if this certificate * factory implements X.509 certificates, the returned certificate object - * can be typecast to the X509Certificate class. + * can be typecast to the {@code X509Certificate} class. * *

    In the case of a certificate factory for X.509 certificates, the - * certificate provided in inStream must be DER-encoded and + * certificate provided in {@code inStream} must be DER-encoded and * may be supplied in binary or printable (Base64) encoding. If the * certificate is provided in Base64 encoding, it must be bounded at * the beginning by -----BEGIN CERTIFICATE-----, and must be bounded at @@ -92,7 +92,7 @@ public abstract class CertificateFactorySpi { * end-of-certificate marker. If the data in the * input stream does not contain an inherent end-of-certificate marker (other * than EOF) and there is trailing data after the certificate is parsed, a - * CertificateException is thrown. + * {@code CertificateException} is thrown. * * @param inStream an input stream with the certificate data. * @@ -105,18 +105,18 @@ public abstract class CertificateFactorySpi { throws CertificateException; /** - * Generates a CertPath object and initializes it with - * the data read from the InputStream inStream. The data + * Generates a {@code CertPath} object and initializes it with + * the data read from the {@code InputStream} inStream. The data * is assumed to be in the default encoding. * *

    This method was added to version 1.4 of the Java 2 Platform * Standard Edition. In order to maintain backwards compatibility with - * existing service providers, this method cannot be abstract - * and by default throws an UnsupportedOperationException. + * existing service providers, this method cannot be {@code abstract} + * and by default throws an {@code UnsupportedOperationException}. * - * @param inStream an InputStream containing the data - * @return a CertPath initialized with the data from the - * InputStream + * @param inStream an {@code InputStream} containing the data + * @return a {@code CertPath} initialized with the data from the + * {@code InputStream} * @exception CertificateException if an exception occurs while decoding * @exception UnsupportedOperationException if the method is not supported * @since 1.4 @@ -128,19 +128,19 @@ public abstract class CertificateFactorySpi { } /** - * Generates a CertPath object and initializes it with - * the data read from the InputStream inStream. The data + * Generates a {@code CertPath} object and initializes it with + * the data read from the {@code InputStream} inStream. The data * is assumed to be in the specified encoding. * *

    This method was added to version 1.4 of the Java 2 Platform * Standard Edition. In order to maintain backwards compatibility with - * existing service providers, this method cannot be abstract - * and by default throws an UnsupportedOperationException. + * existing service providers, this method cannot be {@code abstract} + * and by default throws an {@code UnsupportedOperationException}. * - * @param inStream an InputStream containing the data + * @param inStream an {@code InputStream} containing the data * @param encoding the encoding used for the data - * @return a CertPath initialized with the data from the - * InputStream + * @return a {@code CertPath} initialized with the data from the + * {@code InputStream} * @exception CertificateException if an exception occurs while decoding or * the encoding requested is not supported * @exception UnsupportedOperationException if the method is not supported @@ -153,20 +153,20 @@ public abstract class CertificateFactorySpi { } /** - * Generates a CertPath object and initializes it with - * a List of Certificates. + * Generates a {@code CertPath} object and initializes it with + * a {@code List} of {@code Certificate}s. *

    * The certificates supplied must be of a type supported by the - * CertificateFactory. They will be copied out of the supplied - * List object. + * {@code CertificateFactory}. They will be copied out of the supplied + * {@code List} object. * *

    This method was added to version 1.4 of the Java 2 Platform * Standard Edition. In order to maintain backwards compatibility with - * existing service providers, this method cannot be abstract - * and by default throws an UnsupportedOperationException. + * existing service providers, this method cannot be {@code abstract} + * and by default throws an {@code UnsupportedOperationException}. * - * @param certificates a List of Certificates - * @return a CertPath initialized with the supplied list of + * @param certificates a {@code List} of {@code Certificate}s + * @return a {@code CertPath} initialized with the supplied list of * certificates * @exception CertificateException if an exception occurs * @exception UnsupportedOperationException if the method is not supported @@ -180,24 +180,24 @@ public abstract class CertificateFactorySpi { } /** - * Returns an iteration of the CertPath encodings supported + * Returns an iteration of the {@code CertPath} encodings supported * by this certificate factory, with the default encoding first. See * the CertPath Encodings section in the * Java Cryptography Architecture Standard Algorithm Name Documentation * for information about standard encoding names. *

    - * Attempts to modify the returned Iterator via its - * remove method result in an - * UnsupportedOperationException. + * Attempts to modify the returned {@code Iterator} via its + * {@code remove} method result in an + * {@code UnsupportedOperationException}. * *

    This method was added to version 1.4 of the Java 2 Platform * Standard Edition. In order to maintain backwards compatibility with - * existing service providers, this method cannot be abstract - * and by default throws an UnsupportedOperationException. + * existing service providers, this method cannot be {@code abstract} + * and by default throws an {@code UnsupportedOperationException}. * - * @return an Iterator over the names of the supported - * CertPath encodings (as Strings) + * @return an {@code Iterator} over the names of the supported + * {@code CertPath} encodings (as {@code String}s) * @exception UnsupportedOperationException if the method is not supported * @since 1.4 */ @@ -207,21 +207,21 @@ public abstract class CertificateFactorySpi { /** * Returns a (possibly empty) collection view of the certificates read - * from the given input stream inStream. + * from the given input stream {@code inStream}. * *

    In order to take advantage of the specialized certificate format * supported by this certificate factory, each element in * the returned collection view can be typecast to the corresponding * certificate class. For example, if this certificate * factory implements X.509 certificates, the elements in the returned - * collection can be typecast to the X509Certificate class. + * collection can be typecast to the {@code X509Certificate} class. * *

    In the case of a certificate factory for X.509 certificates, - * inStream may contain a single DER-encoded certificate + * {@code inStream} may contain a single DER-encoded certificate * in the formats described for * {@link CertificateFactory#generateCertificate(java.io.InputStream) * generateCertificate}. - * In addition, inStream may contain a PKCS#7 certificate + * In addition, {@code inStream} may contain a PKCS#7 certificate * chain. This is a PKCS#7 SignedData object, with the only * significant field being certificates. In particular, the * signature and the contents are ignored. This format allows multiple @@ -247,14 +247,14 @@ public abstract class CertificateFactorySpi { /** * Generates a certificate revocation list (CRL) object and initializes it - * with the data read from the input stream inStream. + * with the data read from the input stream {@code inStream}. * *

    In order to take advantage of the specialized CRL format * supported by this certificate factory, * the returned CRL object can be typecast to the corresponding * CRL class. For example, if this certificate * factory implements X.509 CRLs, the returned CRL object - * can be typecast to the X509CRL class. + * can be typecast to the {@code X509CRL} class. * *

    Note that if the given input stream does not support * {@link java.io.InputStream#mark(int) mark} and @@ -265,7 +265,7 @@ public abstract class CertificateFactorySpi { * end-of-CRL marker. If the data in the * input stream does not contain an inherent end-of-CRL marker (other * than EOF) and there is trailing data after the CRL is parsed, a - * CRLException is thrown. + * {@code CRLException} is thrown. * * @param inStream an input stream with the CRL data. * @@ -279,18 +279,18 @@ public abstract class CertificateFactorySpi { /** * Returns a (possibly empty) collection view of the CRLs read - * from the given input stream inStream. + * from the given input stream {@code inStream}. * *

    In order to take advantage of the specialized CRL format * supported by this certificate factory, each element in * the returned collection view can be typecast to the corresponding * CRL class. For example, if this certificate * factory implements X.509 CRLs, the elements in the returned - * collection can be typecast to the X509CRL class. + * collection can be typecast to the {@code X509CRL} class. * *

    In the case of a certificate factory for X.509 CRLs, - * inStream may contain a single DER-encoded CRL. - * In addition, inStream may contain a PKCS#7 CRL + * {@code inStream} may contain a single DER-encoded CRL. + * In addition, {@code inStream} may contain a PKCS#7 CRL * set. This is a PKCS#7 SignedData object, with the only * significant field being crls. In particular, the * signature and the contents are ignored. This format allows multiple diff --git a/src/share/classes/java/security/cert/CertificateNotYetValidException.java b/src/share/classes/java/security/cert/CertificateNotYetValidException.java index 13da51d06f3c8e4348010d5e009b4ccb9b66f5d7..e8722bd339ddba5a98699021d431f1cc81497816 100644 --- a/src/share/classes/java/security/cert/CertificateNotYetValidException.java +++ b/src/share/classes/java/security/cert/CertificateNotYetValidException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,8 +27,8 @@ package java.security.cert; /** * Certificate is not yet valid exception. This is thrown whenever - * the current Date or the specified Date - * is before the notBefore date/time in the Certificate + * the current {@code Date} or the specified {@code Date} + * is before the {@code notBefore} date/time in the Certificate * validity period. * * @author Hemma Prafullchandra diff --git a/src/share/classes/java/security/cert/CertificateParsingException.java b/src/share/classes/java/security/cert/CertificateParsingException.java index 3432fb09af6847a4b9476623488dd1927008bc48..06a7d603f29eef9b486e861751570de393d07934 100644 --- a/src/share/classes/java/security/cert/CertificateParsingException.java +++ b/src/share/classes/java/security/cert/CertificateParsingException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,13 +57,13 @@ public class CertificateParsingException extends CertificateException { } /** - * Creates a CertificateParsingException with the specified + * Creates a {@code CertificateParsingException} with the specified * detail message and cause. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, + * {@link #getCause()} method). (A {@code null} value is permitted, * and indicates that the cause is nonexistent or unknown.) * @since 1.5 */ @@ -72,14 +72,14 @@ public class CertificateParsingException extends CertificateException { } /** - * Creates a CertificateParsingException with the + * Creates a {@code CertificateParsingException} with the * specified cause and a detail message of - * (cause==null ? null : cause.toString()) + * {@code (cause==null ? null : cause.toString())} * (which typically contains the class and detail message of - * cause). + * {@code cause}). * * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, + * {@link #getCause()} method). (A {@code null} value is permitted, * and indicates that the cause is nonexistent or unknown.) * @since 1.5 */ diff --git a/src/share/classes/java/security/cert/CertificateRevokedException.java b/src/share/classes/java/security/cert/CertificateRevokedException.java index b812689ee6e5366fab61d550924c688c733818f2..c50a224861ab2c8c7e870c8373ca965aac991665 100644 --- a/src/share/classes/java/security/cert/CertificateRevokedException.java +++ b/src/share/classes/java/security/cert/CertificateRevokedException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,7 +39,7 @@ import sun.security.x509.InvalidityDateExtension; /** * An exception that indicates an X.509 certificate is revoked. A - * CertificateRevokedException contains additional information + * {@code CertificateRevokedException} contains additional information * about the revoked certificate, such as the date on which the * certificate was revoked and the reason it was revoked. * @@ -60,7 +60,7 @@ public class CertificateRevokedException extends CertificateException { */ private final CRLReason reason; /** - * @serial the X500Principal that represents the name of the + * @serial the {@code X500Principal} that represents the name of the * authority that signed the certificate's revocation status information */ private final X500Principal authority; @@ -68,7 +68,7 @@ public class CertificateRevokedException extends CertificateException { private transient Map extensions; /** - * Constructs a CertificateRevokedException with + * Constructs a {@code CertificateRevokedException} with * the specified revocation date, reason code, authority name, and map * of extensions. * @@ -78,12 +78,12 @@ public class CertificateRevokedException extends CertificateException { * @param extensions a map of X.509 Extensions. Each key is an OID String * that maps to the corresponding Extension. The map is copied to * prevent subsequent modification. - * @param authority the X500Principal that represents the name + * @param authority the {@code X500Principal} that represents the name * of the authority that signed the certificate's revocation status * information - * @throws NullPointerException if revocationDate, - * reason, authority, or - * extensions is null + * @throws NullPointerException if {@code revocationDate}, + * {@code reason}, {@code authority}, or + * {@code extensions} is {@code null} */ public CertificateRevokedException(Date revocationDate, CRLReason reason, X500Principal authority, Map extensions) { @@ -121,7 +121,7 @@ public class CertificateRevokedException extends CertificateException { * Returns the name of the authority that signed the certificate's * revocation status information. * - * @return the X500Principal that represents the name of the + * @return the {@code X500Principal} that represents the name of the * authority that signed the certificate's revocation status information */ public X500Principal getAuthorityName() { @@ -130,16 +130,16 @@ public class CertificateRevokedException extends CertificateException { /** * Returns the invalidity date, as specifed in the Invalidity Date - * extension of this CertificateRevokedException. The + * extension of this {@code CertificateRevokedException}. The * invalidity date is the date on which it is known or suspected that the * private key was compromised or that the certificate otherwise became - * invalid. This implementation calls getExtensions() and + * invalid. This implementation calls {@code getExtensions()} and * checks the returned map for an entry for the Invalidity Date extension * OID ("2.5.29.24"). If found, it returns the invalidity date in the * extension; otherwise null. A new Date object is returned each time the * method is invoked to protect against subsequent modification. * - * @return the invalidity date, or null if not specified + * @return the invalidity date, or {@code null} if not specified */ public Date getInvalidityDate() { Extension ext = getExtensions().get("2.5.29.24"); @@ -176,7 +176,7 @@ public class CertificateRevokedException extends CertificateException { } /** - * Serialize this CertificateRevokedException instance. + * Serialize this {@code CertificateRevokedException} instance. * * @serialData the size of the extensions map (int), followed by all of * the extensions in the map, in no particular order. For each extension, @@ -208,7 +208,7 @@ public class CertificateRevokedException extends CertificateException { } /** - * Deserialize the CertificateRevokedException instance. + * Deserialize the {@code CertificateRevokedException} instance. */ private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { diff --git a/src/share/classes/java/security/cert/CollectionCertStoreParameters.java b/src/share/classes/java/security/cert/CollectionCertStoreParameters.java index 56e25c94778c2003b539b1e33cc3212e06041539..12bd358cfff1ab13d967dcb384402d64c9c28d32 100644 --- a/src/share/classes/java/security/cert/CollectionCertStoreParameters.java +++ b/src/share/classes/java/security/cert/CollectionCertStoreParameters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,13 +30,13 @@ import java.util.Collection; import java.util.Collections; /** - * Parameters used as input for the Collection CertStore + * Parameters used as input for the Collection {@code CertStore} * algorithm. *

    * This class is used to provide necessary configuration parameters - * to implementations of the Collection CertStore + * to implementations of the Collection {@code CertStore} * algorithm. The only parameter included in this class is the - * Collection from which the CertStore will + * {@code Collection} from which the {@code CertStore} will * retrieve certificates and CRLs. *

    * Concurrent Access @@ -58,30 +58,30 @@ public class CollectionCertStoreParameters private Collection coll; /** - * Creates an instance of CollectionCertStoreParameters + * Creates an instance of {@code CollectionCertStoreParameters} * which will allow certificates and CRLs to be retrieved from the - * specified Collection. If the specified - * Collection contains an object that is not a - * Certificate or CRL, that object will be - * ignored by the Collection CertStore. + * specified {@code Collection}. If the specified + * {@code Collection} contains an object that is not a + * {@code Certificate} or {@code CRL}, that object will be + * ignored by the Collection {@code CertStore}. *

    - * The Collection is not copied. Instead, a + * The {@code Collection} is not copied. Instead, a * reference is used. This allows the caller to subsequently add or - * remove Certificates or CRLs from the - * Collection, thus changing the set of - * Certificates or CRLs available to the - * Collection CertStore. The Collection CertStore - * will not modify the contents of the Collection. + * remove {@code Certificates} or {@code CRL}s from the + * {@code Collection}, thus changing the set of + * {@code Certificates} or {@code CRL}s available to the + * Collection {@code CertStore}. The Collection {@code CertStore} + * will not modify the contents of the {@code Collection}. *

    - * If the Collection will be modified by one thread while - * another thread is calling a method of a Collection CertStore - * that has been initialized with this Collection, the - * Collection must have fail-fast iterators. + * If the {@code Collection} will be modified by one thread while + * another thread is calling a method of a Collection {@code CertStore} + * that has been initialized with this {@code Collection}, the + * {@code Collection} must have fail-fast iterators. * - * @param collection a Collection of - * Certificates and CRLs - * @exception NullPointerException if collection is - * null + * @param collection a {@code Collection} of + * {@code Certificate}s and {@code CRL}s + * @exception NullPointerException if {@code collection} is + * {@code null} */ public CollectionCertStoreParameters(Collection collection) { if (collection == null) @@ -90,22 +90,22 @@ public class CollectionCertStoreParameters } /** - * Creates an instance of CollectionCertStoreParameters with + * Creates an instance of {@code CollectionCertStoreParameters} with * the default parameter values (an empty and immutable - * Collection). + * {@code Collection}). */ public CollectionCertStoreParameters() { coll = Collections.EMPTY_SET; } /** - * Returns the Collection from which Certificates - * and CRLs are retrieved. This is not a copy of the - * Collection, it is a reference. This allows the caller to - * subsequently add or remove Certificates or - * CRLs from the Collection. + * Returns the {@code Collection} from which {@code Certificate}s + * and {@code CRL}s are retrieved. This is not a copy of the + * {@code Collection}, it is a reference. This allows the caller to + * subsequently add or remove {@code Certificates} or + * {@code CRL}s from the {@code Collection}. * - * @return the Collection (never null) + * @return the {@code Collection} (never null) */ public Collection getCollection() { return coll; @@ -113,7 +113,7 @@ public class CollectionCertStoreParameters /** * Returns a copy of this object. Note that only a reference to the - * Collection is copied, and not the contents. + * {@code Collection} is copied, and not the contents. * * @return the copy */ diff --git a/src/share/classes/java/security/cert/Extension.java b/src/share/classes/java/security/cert/Extension.java index cbf89d5cdba6f1570386032dcc7871e531949f6a..98e827c59192c0db0301ee4c47dcbbc366535373 100644 --- a/src/share/classes/java/security/cert/Extension.java +++ b/src/share/classes/java/security/cert/Extension.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -84,7 +84,7 @@ public interface Extension { * that are encoded as an OCTET STRING. It does not include the OCTET * STRING tag and length. * - * @return a copy of the extension's value, or null if no + * @return a copy of the extension's value, or {@code null} if no * extension value is present. */ byte[] getValue(); @@ -95,7 +95,7 @@ public interface Extension { * * @param out the output stream * @exception IOException on encoding or output error. - * @exception NullPointerException if out is null. + * @exception NullPointerException if {@code out} is {@code null}. */ void encode(OutputStream out) throws IOException; } diff --git a/src/share/classes/java/security/cert/LDAPCertStoreParameters.java b/src/share/classes/java/security/cert/LDAPCertStoreParameters.java index 5d8b4d599274df49ca9ae3eaa1e1cd36da52fd27..96fe9cd0939b09d9f41180cc92ee3feb2157247e 100644 --- a/src/share/classes/java/security/cert/LDAPCertStoreParameters.java +++ b/src/share/classes/java/security/cert/LDAPCertStoreParameters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,10 +26,10 @@ package java.security.cert; /** - * Parameters used as input for the LDAP CertStore algorithm. + * Parameters used as input for the LDAP {@code CertStore} algorithm. *

    * This class is used to provide necessary configuration parameters (server - * name and port number) to implementations of the LDAP CertStore + * name and port number) to implementations of the LDAP {@code CertStore} * algorithm. *

    * Concurrent Access @@ -59,13 +59,13 @@ public class LDAPCertStoreParameters implements CertStoreParameters { private String serverName; /** - * Creates an instance of LDAPCertStoreParameters with the + * Creates an instance of {@code LDAPCertStoreParameters} with the * specified parameter values. * * @param serverName the DNS name of the LDAP server * @param port the port number of the LDAP server - * @exception NullPointerException if serverName is - * null + * @exception NullPointerException if {@code serverName} is + * {@code null} */ public LDAPCertStoreParameters(String serverName, int port) { if (serverName == null) @@ -75,19 +75,19 @@ public class LDAPCertStoreParameters implements CertStoreParameters { } /** - * Creates an instance of LDAPCertStoreParameters with the + * Creates an instance of {@code LDAPCertStoreParameters} with the * specified server name and a default port of 389. * * @param serverName the DNS name of the LDAP server - * @exception NullPointerException if serverName is - * null + * @exception NullPointerException if {@code serverName} is + * {@code null} */ public LDAPCertStoreParameters(String serverName) { this(serverName, LDAP_DEFAULT_PORT); } /** - * Creates an instance of LDAPCertStoreParameters with the + * Creates an instance of {@code LDAPCertStoreParameters} with the * default parameter values (server name "localhost", port 389). */ public LDAPCertStoreParameters() { @@ -97,7 +97,7 @@ public class LDAPCertStoreParameters implements CertStoreParameters { /** * Returns the DNS name of the LDAP server. * - * @return the name (not null) + * @return the name (not {@code null}) */ public String getServerName() { return serverName; @@ -117,7 +117,7 @@ public class LDAPCertStoreParameters implements CertStoreParameters { * the original and vice versa. *

    * Note: this method currently performs a shallow copy of the object - * (simply calls Object.clone()). This may be changed in a + * (simply calls {@code Object.clone()}). This may be changed in a * future revision to perform a deep copy if new parameters are added * that should not be shared. * diff --git a/src/share/classes/java/security/cert/PKIXBuilderParameters.java b/src/share/classes/java/security/cert/PKIXBuilderParameters.java index d1b27c6ffba65d0f79e55e9d12c23fa922bb6303..b33e1f8c1e20242ce34548d83b585047d0e1c158 100644 --- a/src/share/classes/java/security/cert/PKIXBuilderParameters.java +++ b/src/share/classes/java/security/cert/PKIXBuilderParameters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,35 +32,35 @@ import java.security.InvalidParameterException; import java.util.Set; /** - * Parameters used as input for the PKIX CertPathBuilder + * Parameters used as input for the PKIX {@code CertPathBuilder} * algorithm. *

    - * A PKIX CertPathBuilder uses these parameters to {@link - * CertPathBuilder#build build} a CertPath which has been + * A PKIX {@code CertPathBuilder} uses these parameters to {@link + * CertPathBuilder#build build} a {@code CertPath} which has been * validated according to the PKIX certification path validation algorithm. * - *

    To instantiate a PKIXBuilderParameters object, an + *

    To instantiate a {@code PKIXBuilderParameters} object, an * application must specify one or more most-trusted CAs as defined by * the PKIX certification path validation algorithm. The most-trusted CA * can be specified using one of two constructors. An application * can call {@link #PKIXBuilderParameters(Set, CertSelector) * PKIXBuilderParameters(Set, CertSelector)}, specifying a - * Set of TrustAnchor objects, each of which + * {@code Set} of {@code TrustAnchor} objects, each of which * identifies a most-trusted CA. Alternatively, an application can call * {@link #PKIXBuilderParameters(KeyStore, CertSelector) * PKIXBuilderParameters(KeyStore, CertSelector)}, specifying a - * KeyStore instance containing trusted certificate entries, each + * {@code KeyStore} instance containing trusted certificate entries, each * of which will be considered as a most-trusted CA. * *

    In addition, an application must specify constraints on the target - * certificate that the CertPathBuilder will attempt + * certificate that the {@code CertPathBuilder} will attempt * to build a path to. The constraints are specified as a - * CertSelector object. These constraints should provide the - * CertPathBuilder with enough search criteria to find the target - * certificate. Minimal criteria for an X509Certificate usually + * {@code CertSelector} object. These constraints should provide the + * {@code CertPathBuilder} with enough search criteria to find the target + * certificate. Minimal criteria for an {@code X509Certificate} usually * include the subject name and/or one or more subject alternative names. - * If enough criteria is not specified, the CertPathBuilder - * may throw a CertPathBuilderException. + * If enough criteria is not specified, the {@code CertPathBuilder} + * may throw a {@code CertPathBuilderException}. *

    * Concurrent Access *

    @@ -80,23 +80,23 @@ public class PKIXBuilderParameters extends PKIXParameters { private int maxPathLength = 5; /** - * Creates an instance of PKIXBuilderParameters with - * the specified Set of most-trusted CAs. + * Creates an instance of {@code PKIXBuilderParameters} with + * the specified {@code Set} of most-trusted CAs. * Each element of the set is a {@link TrustAnchor TrustAnchor}. * - *

    Note that the Set is copied to protect against + *

    Note that the {@code Set} is copied to protect against * subsequent modifications. * - * @param trustAnchors a Set of TrustAnchors - * @param targetConstraints a CertSelector specifying the + * @param trustAnchors a {@code Set} of {@code TrustAnchor}s + * @param targetConstraints a {@code CertSelector} specifying the * constraints on the target certificate - * @throws InvalidAlgorithmParameterException if trustAnchors - * is empty (trustAnchors.isEmpty() == true) - * @throws NullPointerException if trustAnchors is - * null + * @throws InvalidAlgorithmParameterException if {@code trustAnchors} + * is empty {@code (trustAnchors.isEmpty() == true)} + * @throws NullPointerException if {@code trustAnchors} is + * {@code null} * @throws ClassCastException if any of the elements of - * trustAnchors are not of type - * java.security.cert.TrustAnchor + * {@code trustAnchors} are not of type + * {@code java.security.cert.TrustAnchor} */ public PKIXBuilderParameters(Set trustAnchors, CertSelector targetConstraints) throws InvalidAlgorithmParameterException @@ -106,22 +106,22 @@ public class PKIXBuilderParameters extends PKIXParameters { } /** - * Creates an instance of PKIXBuilderParameters that + * Creates an instance of {@code PKIXBuilderParameters} that * populates the set of most-trusted CAs from the trusted - * certificate entries contained in the specified KeyStore. - * Only keystore entries that contain trusted X509Certificates + * certificate entries contained in the specified {@code KeyStore}. + * Only keystore entries that contain trusted {@code X509Certificate}s * are considered; all other certificate types are ignored. * - * @param keystore a KeyStore from which the set of + * @param keystore a {@code KeyStore} from which the set of * most-trusted CAs will be populated - * @param targetConstraints a CertSelector specifying the + * @param targetConstraints a {@code CertSelector} specifying the * constraints on the target certificate - * @throws KeyStoreException if keystore has not been + * @throws KeyStoreException if {@code keystore} has not been * initialized - * @throws InvalidAlgorithmParameterException if keystore does + * @throws InvalidAlgorithmParameterException if {@code keystore} does * not contain at least one trusted certificate entry - * @throws NullPointerException if keystore is - * null + * @throws NullPointerException if {@code keystore} is + * {@code null} */ public PKIXBuilderParameters(KeyStore keystore, CertSelector targetConstraints) @@ -139,7 +139,7 @@ public class PKIXBuilderParameters extends PKIXParameters { * in a certification path is not an intermediate certificate, and is not * included in this limit. Usually the last certificate is an end entity * certificate, but it can be a CA certificate. A PKIX - * CertPathBuilder instance must not build + * {@code CertPathBuilder} instance must not build * paths longer than the length specified. * *

    A value of 0 implies that the path can only contain @@ -149,14 +149,14 @@ public class PKIXBuilderParameters extends PKIXParameters { * Setting a value less than -1 will cause an exception to be thrown. * *

    If any of the CA certificates contain the - * BasicConstraintsExtension, the value of the - * pathLenConstraint field of the extension overrides + * {@code BasicConstraintsExtension}, the value of the + * {@code pathLenConstraint} field of the extension overrides * the maximum path length parameter whenever the result is a * certification path of smaller length. * * @param maxPathLength the maximum number of non-self-issued intermediate * certificates that may exist in a certification path - * @throws InvalidParameterException if maxPathLength is set + * @throws InvalidParameterException if {@code maxPathLength} is set * to a value less than -1 * * @see #getMaxPathLength diff --git a/src/share/classes/java/security/cert/PKIXCertPathBuilderResult.java b/src/share/classes/java/security/cert/PKIXCertPathBuilderResult.java index d5efbb35ad226f04acdc9861237219fd9b0e2e1e..3255a3bbda6e45f09b08c5aea2ca8bc7453f5f37 100644 --- a/src/share/classes/java/security/cert/PKIXCertPathBuilderResult.java +++ b/src/share/classes/java/security/cert/PKIXCertPathBuilderResult.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,14 +33,14 @@ import java.security.PublicKey; * returned using this algorithm are also validated according to the PKIX * certification path validation algorithm. * - *

    Instances of PKIXCertPathBuilderResult are returned by - * the build method of CertPathBuilder + *

    Instances of {@code PKIXCertPathBuilderResult} are returned by + * the {@code build} method of {@code CertPathBuilder} * objects implementing the PKIX algorithm. * - *

    All PKIXCertPathBuilderResult objects contain the + *

    All {@code PKIXCertPathBuilderResult} objects contain the * certification path constructed by the build algorithm, the * valid policy tree and subject public key resulting from the build - * algorithm, and a TrustAnchor describing the certification + * algorithm, and a {@code TrustAnchor} describing the certification * authority (CA) that served as a trust anchor for the certification path. *

    * Concurrent Access @@ -62,18 +62,18 @@ public class PKIXCertPathBuilderResult extends PKIXCertPathValidatorResult private CertPath certPath; /** - * Creates an instance of PKIXCertPathBuilderResult + * Creates an instance of {@code PKIXCertPathBuilderResult} * containing the specified parameters. * - * @param certPath the validated CertPath - * @param trustAnchor a TrustAnchor describing the CA that + * @param certPath the validated {@code CertPath} + * @param trustAnchor a {@code TrustAnchor} describing the CA that * served as a trust anchor for the certification path - * @param policyTree the immutable valid policy tree, or null + * @param policyTree the immutable valid policy tree, or {@code null} * if there are no valid policies * @param subjectPublicKey the public key of the subject - * @throws NullPointerException if the certPath, - * trustAnchor or subjectPublicKey parameters - * are null + * @throws NullPointerException if the {@code certPath}, + * {@code trustAnchor} or {@code subjectPublicKey} parameters + * are {@code null} */ public PKIXCertPathBuilderResult(CertPath certPath, TrustAnchor trustAnchor, PolicyNode policyTree, @@ -87,13 +87,13 @@ public class PKIXCertPathBuilderResult extends PKIXCertPathValidatorResult /** * Returns the built and validated certification path. The - * CertPath object does not include the trust anchor. + * {@code CertPath} object does not include the trust anchor. * Instead, use the {@link #getTrustAnchor() getTrustAnchor()} method to - * obtain the TrustAnchor that served as the trust anchor + * obtain the {@code TrustAnchor} that served as the trust anchor * for the certification path. * - * @return the built and validated CertPath (never - * null) + * @return the built and validated {@code CertPath} (never + * {@code null}) */ public CertPath getCertPath() { return certPath; @@ -101,10 +101,10 @@ public class PKIXCertPathBuilderResult extends PKIXCertPathValidatorResult /** * Return a printable representation of this - * PKIXCertPathBuilderResult. + * {@code PKIXCertPathBuilderResult}. * - * @return a String describing the contents of this - * PKIXCertPathBuilderResult + * @return a {@code String} describing the contents of this + * {@code PKIXCertPathBuilderResult} */ public String toString() { StringBuffer sb = new StringBuffer(); diff --git a/src/share/classes/java/security/cert/PKIXCertPathChecker.java b/src/share/classes/java/security/cert/PKIXCertPathChecker.java index 30b44c37f74d6603dbe52e4cad68b248b43bfdc1..21e01bf5166e5afb9fee9faa083a36965c81c9d9 100644 --- a/src/share/classes/java/security/cert/PKIXCertPathChecker.java +++ b/src/share/classes/java/security/cert/PKIXCertPathChecker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,38 +30,38 @@ import java.util.Set; /** * An abstract class that performs one or more checks on an - * X509Certificate. + * {@code X509Certificate}. * - *

    A concrete implementation of the PKIXCertPathChecker class + *

    A concrete implementation of the {@code PKIXCertPathChecker} class * can be created to extend the PKIX certification path validation algorithm. * For example, an implementation may check for and process a critical private * extension of each certificate in a certification path. * - *

    Instances of PKIXCertPathChecker are passed as parameters + *

    Instances of {@code PKIXCertPathChecker} are passed as parameters * using the {@link PKIXParameters#setCertPathCheckers setCertPathCheckers} * or {@link PKIXParameters#addCertPathChecker addCertPathChecker} methods - * of the PKIXParameters and PKIXBuilderParameters - * class. Each of the PKIXCertPathCheckers {@link #check check} + * of the {@code PKIXParameters} and {@code PKIXBuilderParameters} + * class. Each of the {@code PKIXCertPathChecker}s {@link #check check} * methods will be called, in turn, for each certificate processed by a PKIX - * CertPathValidator or CertPathBuilder + * {@code CertPathValidator} or {@code CertPathBuilder} * implementation. * - *

    A PKIXCertPathChecker may be called multiple times on + *

    A {@code PKIXCertPathChecker} may be called multiple times on * successive certificates in a certification path. Concrete subclasses * are expected to maintain any internal state that may be necessary to * check successive certificates. The {@link #init init} method is used * to initialize the internal state of the checker so that the certificates * of a new certification path may be checked. A stateful implementation * must override the {@link #clone clone} method if necessary in - * order to allow a PKIX CertPathBuilder to efficiently + * order to allow a PKIX {@code CertPathBuilder} to efficiently * backtrack and try other paths. In these situations, the - * CertPathBuilder is able to restore prior path validation - * states by restoring the cloned PKIXCertPathCheckers. + * {@code CertPathBuilder} is able to restore prior path validation + * states by restoring the cloned {@code PKIXCertPathChecker}s. * *

    The order in which the certificates are presented to the - * PKIXCertPathChecker may be either in the forward direction + * {@code PKIXCertPathChecker} may be either in the forward direction * (from target to most-trusted CA) or in the reverse direction (from - * most-trusted CA to target). A PKIXCertPathChecker implementation + * most-trusted CA to target). A {@code PKIXCertPathChecker} implementation * must support reverse checking (the ability to perform its checks when * it is presented with certificates in the reverse direction) and may * support forward checking (the ability to perform its checks when it is @@ -96,19 +96,19 @@ public abstract class PKIXCertPathChecker protected PKIXCertPathChecker() {} /** - * Initializes the internal state of this PKIXCertPathChecker. + * Initializes the internal state of this {@code PKIXCertPathChecker}. *

    - * The forward flag specifies the order that + * The {@code forward} flag specifies the order that * certificates will be passed to the {@link #check check} method - * (forward or reverse). A PKIXCertPathChecker must + * (forward or reverse). A {@code PKIXCertPathChecker} must * support reverse checking and may support forward checking. * * @param forward the order that certificates are presented to - * the check method. If true, certificates + * the {@code check} method. If {@code true}, certificates * are presented from target to most-trusted CA (forward); if - * false, from most-trusted CA to target (reverse). + * {@code false}, from most-trusted CA to target (reverse). * @throws CertPathValidatorException if this - * PKIXCertPathChecker is unable to check certificates in + * {@code PKIXCertPathChecker} is unable to check certificates in * the specified order; it should never be thrown if the forward flag * is false since reverse checking must be supported */ @@ -118,32 +118,32 @@ public abstract class PKIXCertPathChecker /** * Indicates if forward checking is supported. Forward checking refers - * to the ability of the PKIXCertPathChecker to perform - * its checks when certificates are presented to the check + * to the ability of the {@code PKIXCertPathChecker} to perform + * its checks when certificates are presented to the {@code check} * method in the forward direction (from target to most-trusted CA). * - * @return true if forward checking is supported, - * false otherwise + * @return {@code true} if forward checking is supported, + * {@code false} otherwise */ @Override public abstract boolean isForwardCheckingSupported(); /** - * Returns an immutable Set of X.509 certificate extensions - * that this PKIXCertPathChecker supports (i.e. recognizes, is - * able to process), or null if no extensions are supported. + * Returns an immutable {@code Set} of X.509 certificate extensions + * that this {@code PKIXCertPathChecker} supports (i.e. recognizes, is + * able to process), or {@code null} if no extensions are supported. *

    - * Each element of the set is a String representing the + * Each element of the set is a {@code String} representing the * Object Identifier (OID) of the X.509 extension that is supported. * The OID is represented by a set of nonnegative integers separated by * periods. *

    - * All X.509 certificate extensions that a PKIXCertPathChecker + * All X.509 certificate extensions that a {@code PKIXCertPathChecker} * might possibly be able to process should be included in the set. * - * @return an immutable Set of X.509 extension OIDs (in - * String format) supported by this - * PKIXCertPathChecker, or null if no + * @return an immutable {@code Set} of X.509 extension OIDs (in + * {@code String} format) supported by this + * {@code PKIXCertPathChecker}, or {@code null} if no * extensions are supported */ public abstract Set getSupportedExtensions(); @@ -153,10 +153,10 @@ public abstract class PKIXCertPathChecker * state and removes any critical extensions that it processes from the * specified collection of OID strings that represent the unresolved * critical extensions. The certificates are presented in the order - * specified by the init method. + * specified by the {@code init} method. * - * @param cert the Certificate to be checked - * @param unresolvedCritExts a Collection of OID strings + * @param cert the {@code Certificate} to be checked + * @param unresolvedCritExts a {@code Collection} of OID strings * representing the current set of unresolved critical extensions * @exception CertPathValidatorException if the specified certificate does * not pass the check @@ -177,12 +177,12 @@ public abstract class PKIXCertPathChecker } /** - * Returns a clone of this object. Calls the Object.clone() + * Returns a clone of this object. Calls the {@code Object.clone()} * method. * All subclasses which maintain state must support and * override this method, if necessary. * - * @return a copy of this PKIXCertPathChecker + * @return a copy of this {@code PKIXCertPathChecker} */ @Override public Object clone() { diff --git a/src/share/classes/java/security/cert/PKIXCertPathValidatorResult.java b/src/share/classes/java/security/cert/PKIXCertPathValidatorResult.java index 39f2272681857d92b2358ecaabd0424b150927bb..b40cd393c7dc691f4fc2e65282b635d164088750 100644 --- a/src/share/classes/java/security/cert/PKIXCertPathValidatorResult.java +++ b/src/share/classes/java/security/cert/PKIXCertPathValidatorResult.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,13 +31,13 @@ import java.security.PublicKey; * This class represents the successful result of the PKIX certification * path validation algorithm. * - *

    Instances of PKIXCertPathValidatorResult are returned by the + *

    Instances of {@code PKIXCertPathValidatorResult} are returned by the * {@link CertPathValidator#validate validate} method of - * CertPathValidator objects implementing the PKIX algorithm. + * {@code CertPathValidator} objects implementing the PKIX algorithm. * - *

    All PKIXCertPathValidatorResult objects contain the + *

    All {@code PKIXCertPathValidatorResult} objects contain the * valid policy tree and subject public key resulting from the - * validation algorithm, as well as a TrustAnchor describing + * validation algorithm, as well as a {@code TrustAnchor} describing * the certification authority (CA) that served as a trust anchor for the * certification path. *

    @@ -62,16 +62,16 @@ public class PKIXCertPathValidatorResult implements CertPathValidatorResult { private PublicKey subjectPublicKey; /** - * Creates an instance of PKIXCertPathValidatorResult + * Creates an instance of {@code PKIXCertPathValidatorResult} * containing the specified parameters. * - * @param trustAnchor a TrustAnchor describing the CA that + * @param trustAnchor a {@code TrustAnchor} describing the CA that * served as a trust anchor for the certification path - * @param policyTree the immutable valid policy tree, or null + * @param policyTree the immutable valid policy tree, or {@code null} * if there are no valid policies * @param subjectPublicKey the public key of the subject - * @throws NullPointerException if the subjectPublicKey or - * trustAnchor parameters are null + * @throws NullPointerException if the {@code subjectPublicKey} or + * {@code trustAnchor} parameters are {@code null} */ public PKIXCertPathValidatorResult(TrustAnchor trustAnchor, PolicyNode policyTree, PublicKey subjectPublicKey) @@ -86,10 +86,10 @@ public class PKIXCertPathValidatorResult implements CertPathValidatorResult { } /** - * Returns the TrustAnchor describing the CA that served + * Returns the {@code TrustAnchor} describing the CA that served * as a trust anchor for the certification path. * - * @return the TrustAnchor (never null) + * @return the {@code TrustAnchor} (never {@code null}) */ public TrustAnchor getTrustAnchor() { return trustAnchor; @@ -98,18 +98,18 @@ public class PKIXCertPathValidatorResult implements CertPathValidatorResult { /** * Returns the root node of the valid policy tree resulting from the * PKIX certification path validation algorithm. The - * PolicyNode object that is returned and any objects that + * {@code PolicyNode} object that is returned and any objects that * it returns through public methods are immutable. * *

    Most applications will not need to examine the valid policy tree. * They can achieve their policy processing goals by setting the - * policy-related parameters in PKIXParameters. However, more + * policy-related parameters in {@code PKIXParameters}. However, more * sophisticated applications, especially those that process policy * qualifiers, may need to traverse the valid policy tree using the * {@link PolicyNode#getParent PolicyNode.getParent} and * {@link PolicyNode#getChildren PolicyNode.getChildren} methods. * - * @return the root node of the valid policy tree, or null + * @return the root node of the valid policy tree, or {@code null} * if there are no valid policies */ public PolicyNode getPolicyTree() { @@ -120,7 +120,7 @@ public class PKIXCertPathValidatorResult implements CertPathValidatorResult { * Returns the public key of the subject (target) of the certification * path, including any inherited public key parameters if applicable. * - * @return the public key of the subject (never null) + * @return the public key of the subject (never {@code null}) */ public PublicKey getPublicKey() { return subjectPublicKey; @@ -142,10 +142,10 @@ public class PKIXCertPathValidatorResult implements CertPathValidatorResult { /** * Return a printable representation of this - * PKIXCertPathValidatorResult. + * {@code PKIXCertPathValidatorResult}. * - * @return a String describing the contents of this - * PKIXCertPathValidatorResult + * @return a {@code String} describing the contents of this + * {@code PKIXCertPathValidatorResult} */ public String toString() { StringBuffer sb = new StringBuffer(); diff --git a/src/share/classes/java/security/cert/PKIXParameters.java b/src/share/classes/java/security/cert/PKIXParameters.java index 8b0100511e0bca41386949effe2adbfbcdd353bc..4d8a344532e970526bffec8f65d3c7645ae98f09 100644 --- a/src/share/classes/java/security/cert/PKIXParameters.java +++ b/src/share/classes/java/security/cert/PKIXParameters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,34 +38,34 @@ import java.util.List; import java.util.Set; /** - * Parameters used as input for the PKIX CertPathValidator + * Parameters used as input for the PKIX {@code CertPathValidator} * algorithm. *

    - * A PKIX CertPathValidator uses these parameters to - * validate a CertPath according to the PKIX certification path + * A PKIX {@code CertPathValidator} uses these parameters to + * validate a {@code CertPath} according to the PKIX certification path * validation algorithm. * - *

    To instantiate a PKIXParameters object, an + *

    To instantiate a {@code PKIXParameters} object, an * application must specify one or more most-trusted CAs as defined by * the PKIX certification path validation algorithm. The most-trusted CAs * can be specified using one of two constructors. An application * can call {@link #PKIXParameters(Set) PKIXParameters(Set)}, - * specifying a Set of TrustAnchor objects, each + * specifying a {@code Set} of {@code TrustAnchor} objects, each * of which identify a most-trusted CA. Alternatively, an application can call * {@link #PKIXParameters(KeyStore) PKIXParameters(KeyStore)}, specifying a - * KeyStore instance containing trusted certificate entries, each + * {@code KeyStore} instance containing trusted certificate entries, each * of which will be considered as a most-trusted CA. *

    - * Once a PKIXParameters object has been created, other parameters + * Once a {@code PKIXParameters} object has been created, other parameters * can be specified (by calling {@link #setInitialPolicies setInitialPolicies} * or {@link #setDate setDate}, for instance) and then the - * PKIXParameters is passed along with the CertPath + * {@code PKIXParameters} is passed along with the {@code CertPath} * to be validated to {@link CertPathValidator#validate * CertPathValidator.validate}. *

    - * Any parameter that is not set (or is set to null) will + * Any parameter that is not set (or is set to {@code null}) will * be set to the default value for that parameter. The default value for the - * date parameter is null, which indicates + * {@code date} parameter is {@code null}, which indicates * the current time when the path is validated. The default for the * remaining parameters is the least constrained. *

    @@ -99,20 +99,20 @@ public class PKIXParameters implements CertPathParameters { private CertSelector certSelector; /** - * Creates an instance of PKIXParameters with the specified - * Set of most-trusted CAs. Each element of the + * Creates an instance of {@code PKIXParameters} with the specified + * {@code Set} of most-trusted CAs. Each element of the * set is a {@link TrustAnchor TrustAnchor}. *

    - * Note that the Set is copied to protect against + * Note that the {@code Set} is copied to protect against * subsequent modifications. * - * @param trustAnchors a Set of TrustAnchors + * @param trustAnchors a {@code Set} of {@code TrustAnchor}s * @throws InvalidAlgorithmParameterException if the specified - * Set is empty (trustAnchors.isEmpty() == true) - * @throws NullPointerException if the specified Set is - * null - * @throws ClassCastException if any of the elements in the Set - * are not of type java.security.cert.TrustAnchor + * {@code Set} is empty {@code (trustAnchors.isEmpty() == true)} + * @throws NullPointerException if the specified {@code Set} is + * {@code null} + * @throws ClassCastException if any of the elements in the {@code Set} + * are not of type {@code java.security.cert.TrustAnchor} */ public PKIXParameters(Set trustAnchors) throws InvalidAlgorithmParameterException @@ -125,18 +125,18 @@ public class PKIXParameters implements CertPathParameters { } /** - * Creates an instance of PKIXParameters that + * Creates an instance of {@code PKIXParameters} that * populates the set of most-trusted CAs from the trusted - * certificate entries contained in the specified KeyStore. - * Only keystore entries that contain trusted X509Certificates + * certificate entries contained in the specified {@code KeyStore}. + * Only keystore entries that contain trusted {@code X509Certificates} * are considered; all other certificate types are ignored. * - * @param keystore a KeyStore from which the set of + * @param keystore a {@code KeyStore} from which the set of * most-trusted CAs will be populated * @throws KeyStoreException if the keystore has not been initialized * @throws InvalidAlgorithmParameterException if the keystore does * not contain at least one trusted certificate entry - * @throws NullPointerException if the keystore is null + * @throws NullPointerException if the keystore is {@code null} */ public PKIXParameters(KeyStore keystore) throws KeyStoreException, InvalidAlgorithmParameterException @@ -161,11 +161,11 @@ public class PKIXParameters implements CertPathParameters { } /** - * Returns an immutable Set of the most-trusted + * Returns an immutable {@code Set} of the most-trusted * CAs. * - * @return an immutable Set of TrustAnchors - * (never null) + * @return an immutable {@code Set} of {@code TrustAnchor}s + * (never {@code null}) * * @see #setTrustAnchors */ @@ -174,18 +174,18 @@ public class PKIXParameters implements CertPathParameters { } /** - * Sets the Set of most-trusted CAs. + * Sets the {@code Set} of most-trusted CAs. *

    - * Note that the Set is copied to protect against + * Note that the {@code Set} is copied to protect against * subsequent modifications. * - * @param trustAnchors a Set of TrustAnchors + * @param trustAnchors a {@code Set} of {@code TrustAnchor}s * @throws InvalidAlgorithmParameterException if the specified - * Set is empty (trustAnchors.isEmpty() == true) - * @throws NullPointerException if the specified Set is - * null + * {@code Set} is empty {@code (trustAnchors.isEmpty() == true)} + * @throws NullPointerException if the specified {@code Set} is + * {@code null} * @throws ClassCastException if any of the elements in the set - * are not of type java.security.cert.TrustAnchor + * are not of type {@code java.security.cert.TrustAnchor} * * @see #getTrustAnchors */ @@ -211,16 +211,16 @@ public class PKIXParameters implements CertPathParameters { } /** - * Returns an immutable Set of initial + * Returns an immutable {@code Set} of initial * policy identifiers (OID strings), indicating that any one of these * policies would be acceptable to the certificate user for the purposes of * certification path processing. The default return value is an empty - * Set, which is interpreted as meaning that any policy would + * {@code Set}, which is interpreted as meaning that any policy would * be acceptable. * - * @return an immutable Set of initial policy OIDs in - * String format, or an empty Set (implying any - * policy is acceptable). Never returns null. + * @return an immutable {@code Set} of initial policy OIDs in + * {@code String} format, or an empty {@code Set} (implying any + * policy is acceptable). Never returns {@code null}. * * @see #setInitialPolicies */ @@ -229,21 +229,21 @@ public class PKIXParameters implements CertPathParameters { } /** - * Sets the Set of initial policy identifiers + * Sets the {@code Set} of initial policy identifiers * (OID strings), indicating that any one of these * policies would be acceptable to the certificate user for the purposes of * certification path processing. By default, any policy is acceptable * (i.e. all policies), so a user that wants to allow any policy as * acceptable does not need to call this method, or can call it - * with an empty Set (or null). + * with an empty {@code Set} (or {@code null}). *

    - * Note that the Set is copied to protect against + * Note that the {@code Set} is copied to protect against * subsequent modifications. * - * @param initialPolicies a Set of initial policy - * OIDs in String format (or null) + * @param initialPolicies a {@code Set} of initial policy + * OIDs in {@code String} format (or {@code null}) * @throws ClassCastException if any of the elements in the set are - * not of type String + * not of type {@code String} * * @see #getInitialPolicies */ @@ -262,19 +262,19 @@ public class PKIXParameters implements CertPathParameters { } /** - * Sets the list of CertStores to be used in finding - * certificates and CRLs. May be null, in which case - * no CertStores will be used. The first - * CertStores in the list may be preferred to those that + * Sets the list of {@code CertStore}s to be used in finding + * certificates and CRLs. May be {@code null}, in which case + * no {@code CertStore}s will be used. The first + * {@code CertStore}s in the list may be preferred to those that * appear later. *

    - * Note that the List is copied to protect against + * Note that the {@code List} is copied to protect against * subsequent modifications. * - * @param stores a List of CertStores (or - * null) + * @param stores a {@code List} of {@code CertStore}s (or + * {@code null}) * @throws ClassCastException if any of the elements in the list are - * not of type java.security.cert.CertStore + * not of type {@code java.security.cert.CertStore} * * @see #getCertStores */ @@ -293,10 +293,10 @@ public class PKIXParameters implements CertPathParameters { } /** - * Adds a CertStore to the end of the list of - * CertStores used in finding certificates and CRLs. + * Adds a {@code CertStore} to the end of the list of + * {@code CertStore}s used in finding certificates and CRLs. * - * @param store the CertStore to add. If null, + * @param store the {@code CertStore} to add. If {@code null}, * the store is ignored (not added to list). */ public void addCertStore(CertStore store) { @@ -306,11 +306,11 @@ public class PKIXParameters implements CertPathParameters { } /** - * Returns an immutable List of CertStores that + * Returns an immutable {@code List} of {@code CertStore}s that * are used to find certificates and CRLs. * - * @return an immutable List of CertStores - * (may be empty, but never null) + * @return an immutable {@code List} of {@code CertStore}s + * (may be empty, but never {@code null}) * * @see #setCertStores */ @@ -325,7 +325,7 @@ public class PKIXParameters implements CertPathParameters { * will be used. If this flag is false, the default revocation checking * mechanism will be disabled (not used). *

    - * When a PKIXParameters object is created, this flag is set + * When a {@code PKIXParameters} object is created, this flag is set * to true. This setting reflects the most common strategy for checking * revocation, since each service provider must support revocation * checking to be PKIX compliant. Sophisticated applications should set @@ -360,8 +360,8 @@ public class PKIXParameters implements CertPathParameters { * acceptable policy needs to be explicitly identified in every certificate. * By default, the ExplicitPolicyRequired flag is false. * - * @param val true if explicit policy is to be required, - * false otherwise + * @param val {@code true} if explicit policy is to be required, + * {@code false} otherwise */ public void setExplicitPolicyRequired(boolean val) { explicitPolicyRequired = val; @@ -372,8 +372,8 @@ public class PKIXParameters implements CertPathParameters { * acceptable policy needs to be explicitly identified in every certificate. * By default, the ExplicitPolicyRequired flag is false. * - * @return true if explicit policy is required, - * false otherwise + * @return {@code true} if explicit policy is required, + * {@code false} otherwise */ public boolean isExplicitPolicyRequired() { return explicitPolicyRequired; @@ -384,8 +384,8 @@ public class PKIXParameters implements CertPathParameters { * mapping is inhibited. By default, policy mapping is not inhibited (the * flag is false). * - * @param val true if policy mapping is to be inhibited, - * false otherwise + * @param val {@code true} if policy mapping is to be inhibited, + * {@code false} otherwise */ public void setPolicyMappingInhibited(boolean val) { policyMappingInhibited = val; @@ -406,10 +406,10 @@ public class PKIXParameters implements CertPathParameters { * Sets state to determine if the any policy OID should be processed * if it is included in a certificate. By default, the any policy OID * is not inhibited ({@link #isAnyPolicyInhibited isAnyPolicyInhibited()} - * returns false). + * returns {@code false}). * - * @param val true if the any policy OID is to be - * inhibited, false otherwise + * @param val {@code true} if the any policy OID is to be + * inhibited, {@code false} otherwise */ public void setAnyPolicyInhibited(boolean val) { anyPolicyInhibited = val; @@ -419,8 +419,8 @@ public class PKIXParameters implements CertPathParameters { * Checks whether the any policy OID should be processed if it * is included in a certificate. * - * @return true if the any policy OID is inhibited, - * false otherwise + * @return {@code true} if the any policy OID is inhibited, + * {@code false} otherwise */ public boolean isAnyPolicyInhibited() { return anyPolicyInhibited; @@ -432,7 +432,7 @@ public class PKIXParameters implements CertPathParameters { * policies extension that is marked critical are rejected. * If the flag is false, certificates are not rejected on this basis. * - *

    When a PKIXParameters object is created, this flag is + *

    When a {@code PKIXParameters} object is created, this flag is * set to true. This setting reflects the most common (and simplest) * strategy for processing policy qualifiers. Applications that want to use * a more sophisticated policy must set this flag to false. @@ -459,7 +459,7 @@ public class PKIXParameters implements CertPathParameters { * extension that is marked critical are rejected. * If the flag is false, certificates are not rejected on this basis. * - *

    When a PKIXParameters object is created, this flag is + *

    When a {@code PKIXParameters} object is created, this flag is * set to true. This setting reflects the most common (and simplest) * strategy for processing policy qualifiers. Applications that want to use * a more sophisticated policy must set this flag to false. @@ -473,12 +473,12 @@ public class PKIXParameters implements CertPathParameters { /** * Returns the time for which the validity of the certification path - * should be determined. If null, the current time is used. + * should be determined. If {@code null}, the current time is used. *

    - * Note that the Date returned is copied to protect against + * Note that the {@code Date} returned is copied to protect against * subsequent modifications. * - * @return the Date, or null if not set + * @return the {@code Date}, or {@code null} if not set * @see #setDate */ public Date getDate() { @@ -490,12 +490,12 @@ public class PKIXParameters implements CertPathParameters { /** * Sets the time for which the validity of the certification path - * should be determined. If null, the current time is used. + * should be determined. If {@code null}, the current time is used. *

    - * Note that the Date supplied here is copied to protect + * Note that the {@code Date} supplied here is copied to protect * against subsequent modifications. * - * @param date the Date, or null for the + * @param date the {@code Date}, or {@code null} for the * current time * @see #getDate */ @@ -507,39 +507,39 @@ public class PKIXParameters implements CertPathParameters { } /** - * Sets a List of additional certification path checkers. If - * the specified List contains an object that is not a - * PKIXCertPathChecker, it is ignored. + * Sets a {@code List} of additional certification path checkers. If + * the specified {@code List} contains an object that is not a + * {@code PKIXCertPathChecker}, it is ignored. *

    - * Each PKIXCertPathChecker specified implements + * Each {@code PKIXCertPathChecker} specified implements * additional checks on a certificate. Typically, these are checks to * process and verify private extensions contained in certificates. - * Each PKIXCertPathChecker should be instantiated with any + * Each {@code PKIXCertPathChecker} should be instantiated with any * initialization parameters needed to execute the check. *

    * This method allows sophisticated applications to extend a PKIX - * CertPathValidator or CertPathBuilder. - * Each of the specified PKIXCertPathCheckers will be called, - * in turn, by a PKIX CertPathValidator or - * CertPathBuilder for each certificate processed or + * {@code CertPathValidator} or {@code CertPathBuilder}. + * Each of the specified {@code PKIXCertPathChecker}s will be called, + * in turn, by a PKIX {@code CertPathValidator} or + * {@code CertPathBuilder} for each certificate processed or * validated. *

    - * Regardless of whether these additional PKIXCertPathCheckers - * are set, a PKIX CertPathValidator or - * CertPathBuilder must perform all of the required PKIX + * Regardless of whether these additional {@code PKIXCertPathChecker}s + * are set, a PKIX {@code CertPathValidator} or + * {@code CertPathBuilder} must perform all of the required PKIX * checks on each certificate. The one exception to this rule is if the * RevocationEnabled flag is set to false (see the {@link * #setRevocationEnabled setRevocationEnabled} method). *

    - * Note that the List supplied here is copied and each - * PKIXCertPathChecker in the list is cloned to protect + * Note that the {@code List} supplied here is copied and each + * {@code PKIXCertPathChecker} in the list is cloned to protect * against subsequent modifications. * - * @param checkers a List of PKIXCertPathCheckers. - * May be null, in which case no additional checkers will be + * @param checkers a {@code List} of {@code PKIXCertPathChecker}s. + * May be {@code null}, in which case no additional checkers will be * used. * @throws ClassCastException if any of the elements in the list - * are not of type java.security.cert.PKIXCertPathChecker + * are not of type {@code java.security.cert.PKIXCertPathChecker} * @see #getCertPathCheckers */ public void setCertPathCheckers(List checkers) { @@ -556,14 +556,14 @@ public class PKIXParameters implements CertPathParameters { } /** - * Returns the List of certification path checkers. - * The returned List is immutable, and each - * PKIXCertPathChecker in the List is cloned + * Returns the {@code List} of certification path checkers. + * The returned {@code List} is immutable, and each + * {@code PKIXCertPathChecker} in the {@code List} is cloned * to protect against subsequent modifications. * - * @return an immutable List of - * PKIXCertPathCheckers (may be empty, but not - * null) + * @return an immutable {@code List} of + * {@code PKIXCertPathChecker}s (may be empty, but not + * {@code null}) * @see #setCertPathCheckers */ public List getCertPathCheckers() { @@ -575,15 +575,15 @@ public class PKIXParameters implements CertPathParameters { } /** - * Adds a PKIXCertPathChecker to the list of certification + * Adds a {@code PKIXCertPathChecker} to the list of certification * path checkers. See the {@link #setCertPathCheckers setCertPathCheckers} * method for more details. *

    - * Note that the PKIXCertPathChecker is cloned to protect + * Note that the {@code PKIXCertPathChecker} is cloned to protect * against subsequent modifications. * - * @param checker a PKIXCertPathChecker to add to the list of - * checks. If null, the checker is ignored (not added to list). + * @param checker a {@code PKIXCertPathChecker} to add to the list of + * checks. If {@code null}, the checker is ignored (not added to list). */ public void addCertPathChecker(PKIXCertPathChecker checker) { if (checker != null) { @@ -592,10 +592,10 @@ public class PKIXParameters implements CertPathParameters { } /** - * Returns the signature provider's name, or null + * Returns the signature provider's name, or {@code null} * if not set. * - * @return the signature provider's name (or null) + * @return the signature provider's name (or {@code null}) * @see #setSigProvider */ public String getSigProvider() { @@ -605,10 +605,10 @@ public class PKIXParameters implements CertPathParameters { /** * Sets the signature provider's name. The specified provider will be * preferred when creating {@link java.security.Signature Signature} - * objects. If null or not set, the first provider found + * objects. If {@code null} or not set, the first provider found * supporting the algorithm will be used. * - * @param sigProvider the signature provider's name (or null) + * @param sigProvider the signature provider's name (or {@code null}) * @see #getSigProvider */ public void setSigProvider(String sigProvider) { @@ -617,14 +617,14 @@ public class PKIXParameters implements CertPathParameters { /** * Returns the required constraints on the target certificate. - * The constraints are returned as an instance of CertSelector. - * If null, no constraints are defined. + * The constraints are returned as an instance of {@code CertSelector}. + * If {@code null}, no constraints are defined. * - *

    Note that the CertSelector returned is cloned + *

    Note that the {@code CertSelector} returned is cloned * to protect against subsequent modifications. * - * @return a CertSelector specifying the constraints - * on the target certificate (or null) + * @return a {@code CertSelector} specifying the constraints + * on the target certificate (or {@code null}) * @see #setTargetCertConstraints */ public CertSelector getTargetCertConstraints() { @@ -638,14 +638,14 @@ public class PKIXParameters implements CertPathParameters { /** * Sets the required constraints on the target certificate. * The constraints are specified as an instance of - * CertSelector. If null, no constraints are + * {@code CertSelector}. If {@code null}, no constraints are * defined. * - *

    Note that the CertSelector specified is cloned + *

    Note that the {@code CertSelector} specified is cloned * to protect against subsequent modifications. * - * @param selector a CertSelector specifying the constraints - * on the target certificate (or null) + * @param selector a {@code CertSelector} specifying the constraints + * on the target certificate (or {@code null}) * @see #getTargetCertConstraints */ public void setTargetCertConstraints(CertSelector selector) { @@ -656,10 +656,10 @@ public class PKIXParameters implements CertPathParameters { } /** - * Makes a copy of this PKIXParameters object. Changes + * Makes a copy of this {@code PKIXParameters} object. Changes * to the copy will not affect the original and vice versa. * - * @return a copy of this PKIXParameters object + * @return a copy of this {@code PKIXParameters} object */ public Object clone() { try { diff --git a/src/share/classes/java/security/cert/PKIXReason.java b/src/share/classes/java/security/cert/PKIXReason.java index 9d81b1321048e5aed7341aa679def6b310c61130..d58ded97541b43c5689b733bcf3b3d7ce4389a4c 100644 --- a/src/share/classes/java/security/cert/PKIXReason.java +++ b/src/share/classes/java/security/cert/PKIXReason.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,10 +26,10 @@ package java.security.cert; /** - * The PKIXReason enumerates the potential PKIX-specific reasons + * The {@code PKIXReason} enumerates the potential PKIX-specific reasons * that an X.509 certification path may be invalid according to the PKIX * (RFC 3280) standard. These reasons are in addition to those of the - * CertPathValidatorException.BasicReason enumeration. + * {@code CertPathValidatorException.BasicReason} enumeration. * * @since 1.7 */ diff --git a/src/share/classes/java/security/cert/PolicyNode.java b/src/share/classes/java/security/cert/PolicyNode.java index 7b16dfe8fbf11bf5d98060e817f4383f647e230c..1633dcb83dafea80078ccbb04b5059bdbc1c71f2 100644 --- a/src/share/classes/java/security/cert/PolicyNode.java +++ b/src/share/classes/java/security/cert/PolicyNode.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,7 +41,7 @@ import java.util.Set; * *

    Most applications will not need to examine the valid policy tree. * They can achieve their policy processing goals by setting the - * policy-related parameters in PKIXParameters. However, + * policy-related parameters in {@code PKIXParameters}. However, * the valid policy tree is available for more sophisticated applications, * especially those that process policy qualifiers. * @@ -50,12 +50,12 @@ import java.util.Set; * valid policy tree. The tree can be traversed using the * {@link #getChildren getChildren} and {@link #getParent getParent} methods. * Data about a particular node can be retrieved using other methods of - * PolicyNode. + * {@code PolicyNode}. * *

    Concurrent Access - *

    All PolicyNode objects must be immutable and + *

    All {@code PolicyNode} objects must be immutable and * thread-safe. Multiple threads may concurrently invoke the methods defined - * in this class on a single PolicyNode object (or more than one) + * in this class on a single {@code PolicyNode} object (or more than one) * with no ill effects. This stipulation applies to all public fields and * methods of this class and any added or overridden by subclasses. * @@ -65,10 +65,10 @@ import java.util.Set; public interface PolicyNode { /** - * Returns the parent of this node, or null if this is the + * Returns the parent of this node, or {@code null} if this is the * root node. * - * @return the parent of this node, or null if this is the + * @return the parent of this node, or {@code null} if this is the * root node */ PolicyNode getParent(); @@ -76,8 +76,8 @@ public interface PolicyNode { /** * Returns an iterator over the children of this node. Any attempts to * modify the children of this node through the - * Iterator's remove method must throw an - * UnsupportedOperationException. + * {@code Iterator}'s remove method must throw an + * {@code UnsupportedOperationException}. * * @return an iterator over the children of this node */ @@ -94,7 +94,7 @@ public interface PolicyNode { /** * Returns the valid policy represented by this node. * - * @return the String OID of the valid policy + * @return the {@code String} OID of the valid policy * represented by this node. For the root node, this method always returns * the special anyPolicy OID: "2.5.29.32.0". */ @@ -104,9 +104,9 @@ public interface PolicyNode { * Returns the set of policy qualifiers associated with the * valid policy represented by this node. * - * @return an immutable Set of - * PolicyQualifierInfos. For the root node, this - * is always an empty Set. + * @return an immutable {@code Set} of + * {@code PolicyQualifierInfo}s. For the root node, this + * is always an empty {@code Set}. */ Set getPolicyQualifiers(); @@ -114,9 +114,9 @@ public interface PolicyNode { * Returns the set of expected policies that would satisfy this * node's valid policy in the next certificate to be processed. * - * @return an immutable Set of expected policy - * String OIDs. For the root node, this method - * always returns a Set with one element, the + * @return an immutable {@code Set} of expected policy + * {@code String} OIDs. For the root node, this method + * always returns a {@code Set} with one element, the * special anyPolicy OID: "2.5.29.32.0". */ Set getExpectedPolicies(); @@ -125,8 +125,8 @@ public interface PolicyNode { * Returns the criticality indicator of the certificate policy extension * in the most recently processed certificate. * - * @return true if extension marked critical, - * false otherwise. For the root node, false + * @return {@code true} if extension marked critical, + * {@code false} otherwise. For the root node, {@code false} * is always returned. */ boolean isCritical(); diff --git a/src/share/classes/java/security/cert/PolicyQualifierInfo.java b/src/share/classes/java/security/cert/PolicyQualifierInfo.java index 75a8702ac8438bd520156fd8f2729272c4535c47..bc083eb7a43c7377a1ee29faf2fb316c42190b5f 100644 --- a/src/share/classes/java/security/cert/PolicyQualifierInfo.java +++ b/src/share/classes/java/security/cert/PolicyQualifierInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -50,12 +50,12 @@ import sun.security.util.DerValue; * policy information terms limit the set of policies for certification paths * which include this certificate. *

    - * A Set of PolicyQualifierInfo objects are returned + * A {@code Set} of {@code PolicyQualifierInfo} objects are returned * by the {@link PolicyNode#getPolicyQualifiers PolicyNode.getPolicyQualifiers} * method. This allows applications with specific policy requirements to * process and validate each policy qualifier. Applications that need to * process policy qualifiers should explicitly set the - * policyQualifiersRejected flag to false (by calling the + * {@code policyQualifiersRejected} flag to false (by calling the * {@link PKIXParameters#setPolicyQualifiersRejected * PKIXParameters.setPolicyQualifiersRejected} method) before validating * a certification path. @@ -64,17 +64,17 @@ import sun.security.util.DerValue; * that any policy qualifier in a certificate policies extension that is * marked critical must be processed and validated. Otherwise the * certification path must be rejected. If the - * policyQualifiersRejected flag is set to false, it is up to + * {@code policyQualifiersRejected} flag is set to false, it is up to * the application to validate all policy qualifiers in this manner in order * to be PKIX compliant. * *

    Concurrent Access * - *

    All PolicyQualifierInfo objects must be immutable and + *

    All {@code PolicyQualifierInfo} objects must be immutable and * thread-safe. That is, multiple threads may concurrently invoke the - * methods defined in this class on a single PolicyQualifierInfo + * methods defined in this class on a single {@code PolicyQualifierInfo} * object (or more than one) with no ill effects. Requiring - * PolicyQualifierInfo objects to be immutable and thread-safe + * {@code PolicyQualifierInfo} objects to be immutable and thread-safe * allows them to be passed around to various pieces of code without * worrying about coordinating access. * @@ -90,7 +90,7 @@ public class PolicyQualifierInfo { private String pqiString; /** - * Creates an instance of PolicyQualifierInfo from the + * Creates an instance of {@code PolicyQualifierInfo} from the * encoded bytes. The encoded byte array is copied on construction. * * @param encoded a byte array containing the qualifier in DER encoding @@ -115,12 +115,12 @@ public class PolicyQualifierInfo { } /** - * Returns the policyQualifierId field of this - * PolicyQualifierInfo. The policyQualifierId + * Returns the {@code policyQualifierId} field of this + * {@code PolicyQualifierInfo}. The {@code policyQualifierId} * is an Object Identifier (OID) represented by a set of nonnegative * integers separated by periods. * - * @return the OID (never null) + * @return the OID (never {@code null}) */ public final String getPolicyQualifierId() { return mId; @@ -128,9 +128,9 @@ public class PolicyQualifierInfo { /** * Returns the ASN.1 DER encoded form of this - * PolicyQualifierInfo. + * {@code PolicyQualifierInfo}. * - * @return the ASN.1 DER encoded bytes (never null). + * @return the ASN.1 DER encoded bytes (never {@code null}). * Note that a copy is returned, so the data is cloned each time * this method is called. */ @@ -139,10 +139,10 @@ public class PolicyQualifierInfo { } /** - * Returns the ASN.1 DER encoded form of the qualifier - * field of this PolicyQualifierInfo. + * Returns the ASN.1 DER encoded form of the {@code qualifier} + * field of this {@code PolicyQualifierInfo}. * - * @return the ASN.1 DER encoded bytes of the qualifier + * @return the ASN.1 DER encoded bytes of the {@code qualifier} * field. Note that a copy is returned, so the data is cloned each * time this method is called. */ @@ -152,10 +152,10 @@ public class PolicyQualifierInfo { /** * Return a printable representation of this - * PolicyQualifierInfo. + * {@code PolicyQualifierInfo}. * - * @return a String describing the contents of this - * PolicyQualifierInfo + * @return a {@code String} describing the contents of this + * {@code PolicyQualifierInfo} */ public String toString() { if (pqiString != null) diff --git a/src/share/classes/java/security/cert/TrustAnchor.java b/src/share/classes/java/security/cert/TrustAnchor.java index d9c88f405dcf4f36bc5913b8320637754117409f..fe267a52f669bf33d9a81cb53ec410ea657e31b1 100644 --- a/src/share/classes/java/security/cert/TrustAnchor.java +++ b/src/share/classes/java/security/cert/TrustAnchor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,16 +40,16 @@ import sun.security.x509.X500Name; * for validating X.509 certification paths. A most-trusted CA includes the * public key of the CA, the CA's name, and any constraints upon the set of * paths which may be validated using this key. These parameters can be - * specified in the form of a trusted X509Certificate or as + * specified in the form of a trusted {@code X509Certificate} or as * individual parameters. *

    * Concurrent Access *

    - *

    All TrustAnchor objects must be immutable and + *

    All {@code TrustAnchor} objects must be immutable and * thread-safe. That is, multiple threads may concurrently invoke the - * methods defined in this class on a single TrustAnchor + * methods defined in this class on a single {@code TrustAnchor} * object (or more than one) with no ill effects. Requiring - * TrustAnchor objects to be immutable and thread-safe + * {@code TrustAnchor} objects to be immutable and thread-safe * allows them to be passed around to various pieces of code without * worrying about coordinating access. This stipulation applies to all * public fields and methods of this class and any added or overridden @@ -71,8 +71,8 @@ public class TrustAnchor { private NameConstraintsExtension nc; /** - * Creates an instance of TrustAnchor with the specified - * X509Certificate and optional name constraints, which + * Creates an instance of {@code TrustAnchor} with the specified + * {@code X509Certificate} and optional name constraints, which * are intended to be used as additional constraints when validating * an X.509 certification path. *

    @@ -82,7 +82,7 @@ public class TrustAnchor { * RFC 3280 * and X.509. The ASN.1 definition of this structure appears below. * - *

    
    +     * 
    {@code
          *  NameConstraints ::= SEQUENCE {
          *       permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
          *       excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
    @@ -106,20 +106,20 @@ public class TrustAnchor {
          *       uniformResourceIdentifier       [6]     IA5String,
          *       iPAddress                       [7]     OCTET STRING,
          *       registeredID                    [8]     OBJECT IDENTIFIER}
    -     * 
    + * }
    *

    * Note that the name constraints byte array supplied is cloned to protect * against subsequent modifications. * - * @param trustedCert a trusted X509Certificate + * @param trustedCert a trusted {@code X509Certificate} * @param nameConstraints a byte array containing the ASN.1 DER encoding of * a NameConstraints extension to be used for checking name constraints. * Only the value of the extension is included, not the OID or criticality - * flag. Specify null to omit the parameter. + * flag. Specify {@code null} to omit the parameter. * @throws IllegalArgumentException if the name constraints cannot be * decoded * @throws NullPointerException if the specified - * X509Certificate is null + * {@code X509Certificate} is {@code null} */ public TrustAnchor(X509Certificate trustedCert, byte[] nameConstraints) { @@ -134,7 +134,7 @@ public class TrustAnchor { } /** - * Creates an instance of TrustAnchor where the + * Creates an instance of {@code TrustAnchor} where the * most-trusted CA is specified as an X500Principal and public key. * Name constraints are an optional parameter, and are intended to be used * as additional constraints when validating an X.509 certification path. @@ -155,9 +155,9 @@ public class TrustAnchor { * @param nameConstraints a byte array containing the ASN.1 DER encoding of * a NameConstraints extension to be used for checking name constraints. * Only the value of the extension is included, not the OID or criticality - * flag. Specify null to omit the parameter. - * @throws NullPointerException if the specified caPrincipal or - * pubKey parameter is null + * flag. Specify {@code null} to omit the parameter. + * @throws NullPointerException if the specified {@code caPrincipal} or + * {@code pubKey} parameter is {@code null} * @since 1.5 */ public TrustAnchor(X500Principal caPrincipal, PublicKey pubKey, @@ -173,7 +173,7 @@ public class TrustAnchor { } /** - * Creates an instance of TrustAnchor where the + * Creates an instance of {@code TrustAnchor} where the * most-trusted CA is specified as a distinguished name and public key. * Name constraints are an optional parameter, and are intended to be used * as additional constraints when validating an X.509 certification path. @@ -191,17 +191,17 @@ public class TrustAnchor { * * @param caName the X.500 distinguished name of the most-trusted CA in * RFC 2253 - * String format + * {@code String} format * @param pubKey the public key of the most-trusted CA * @param nameConstraints a byte array containing the ASN.1 DER encoding of * a NameConstraints extension to be used for checking name constraints. * Only the value of the extension is included, not the OID or criticality - * flag. Specify null to omit the parameter. - * @throws IllegalArgumentException if the specified - * caName parameter is empty (caName.length() == 0) + * flag. Specify {@code null} to omit the parameter. + * @throws IllegalArgumentException if the specified + * {@code caName} parameter is empty {@code (caName.length() == 0)} * or incorrectly formatted or the name constraints cannot be decoded - * @throws NullPointerException if the specified caName or - * pubKey parameter is null + * @throws NullPointerException if the specified {@code caName} or + * {@code pubKey} parameter is {@code null} */ public TrustAnchor(String caName, PublicKey pubKey, byte[] nameConstraints) { @@ -225,7 +225,7 @@ public class TrustAnchor { /** * Returns the most-trusted CA certificate. * - * @return a trusted X509Certificate or null + * @return a trusted {@code X509Certificate} or {@code null} * if the trust anchor was not specified as a trusted certificate */ public final X509Certificate getTrustedCert() { @@ -236,7 +236,7 @@ public class TrustAnchor { * Returns the name of the most-trusted CA as an X500Principal. * * @return the X.500 distinguished name of the most-trusted CA, or - * null if the trust anchor was not specified as a trusted + * {@code null} if the trust anchor was not specified as a trusted * public key and name or X500Principal pair * @since 1.5 */ @@ -245,11 +245,11 @@ public class TrustAnchor { } /** - * Returns the name of the most-trusted CA in RFC 2253 String + * Returns the name of the most-trusted CA in RFC 2253 {@code String} * format. * * @return the X.500 distinguished name of the most-trusted CA, or - * null if the trust anchor was not specified as a trusted + * {@code null} if the trust anchor was not specified as a trusted * public key and name or X500Principal pair */ public final String getCAName() { @@ -259,7 +259,7 @@ public class TrustAnchor { /** * Returns the public key of the most-trusted CA. * - * @return the public key of the most-trusted CA, or null + * @return the public key of the most-trusted CA, or {@code null} * if the trust anchor was not specified as a trusted public key and name * or X500Principal pair */ @@ -306,16 +306,16 @@ public class TrustAnchor { * * @return a byte array containing the ASN.1 DER encoding of * a NameConstraints extension used for checking name constraints, - * or null if not set. + * or {@code null} if not set. */ public final byte [] getNameConstraints() { return ncBytes == null ? null : ncBytes.clone(); } /** - * Returns a formatted string describing the TrustAnchor. + * Returns a formatted string describing the {@code TrustAnchor}. * - * @return a formatted string describing the TrustAnchor + * @return a formatted string describing the {@code TrustAnchor} */ public String toString() { StringBuffer sb = new StringBuffer(); diff --git a/src/share/classes/java/security/cert/X509CRL.java b/src/share/classes/java/security/cert/X509CRL.java index cd1769f07249c7802bff5a18bbd70004e9728dbf..5ce84847fa56d57fd83cf5da015058d8cbfbb7f2 100644 --- a/src/share/classes/java/security/cert/X509CRL.java +++ b/src/share/classes/java/security/cert/X509CRL.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -72,7 +72,7 @@ import sun.security.x509.X509CRLImpl; * RFC 3280: Internet X.509 * Public Key Infrastructure Certificate and CRL Profile. *

    - * The ASN.1 definition of tbsCertList is: + * The ASN.1 definition of {@code tbsCertList} is: *

      * TBSCertList  ::=  SEQUENCE  {
      *     version                 Version OPTIONAL,
    @@ -94,12 +94,12 @@ import sun.security.x509.X509CRLImpl;
      * 

    * CRLs are instantiated using a certificate factory. The following is an * example of how to instantiate an X.509 CRL: - *

    
    + * 
    {@code
      * try (InputStream inStream = new FileInputStream("fileName-of-crl")) {
      *     CertificateFactory cf = CertificateFactory.getInstance("X.509");
      *     X509CRL crl = (X509CRL)cf.generateCRL(inStream);
      * }
    - * 
    + * }
    * * @author Hemma Prafullchandra * @@ -122,8 +122,8 @@ public abstract class X509CRL extends CRL implements X509Extension { /** * Compares this CRL for equality with the given - * object. If the other object is an - * instanceof X509CRL, then + * object. If the {@code other} object is an + * {@code instanceof} {@code X509CRL}, then * its encoded form is retrieved and compared with the * encoded form of this CRL. * @@ -225,7 +225,7 @@ public abstract class X509CRL extends CRL implements X509Extension { * * This method was added to version 1.8 of the Java Platform Standard * Edition. In order to maintain backwards compatibility with existing - * service providers, this method is not abstract + * service providers, this method is not {@code abstract} * and it provides a default implementation. * * @param key the PublicKey used to carry out the verification. @@ -245,11 +245,12 @@ public abstract class X509CRL extends CRL implements X509Extension { } /** - * Gets the version (version number) value from the CRL. + * Gets the {@code version} (version number) value from the CRL. * The ASN.1 definition for this is: *
          * version    Version OPTIONAL,
    -     *             -- if present, must be v2

    + * -- if present, must be v2 + * * Version ::= INTEGER { v1(0), v2(1), v3(2) } * -- v3 does not apply to CRLs but appears for consistency * -- with definition of Version for certs @@ -261,12 +262,12 @@ public abstract class X509CRL extends CRL implements X509Extension { /** * Denigrated, replaced by {@linkplain - * #getIssuerX500Principal()}. This method returns the issuer + * #getIssuerX500Principal()}. This method returns the {@code issuer} * as an implementation specific Principal object, which should not be * relied upon by portable code. * *

    - * Gets the issuer (issuer distinguished name) value from + * Gets the {@code issuer} (issuer distinguished name) value from * the CRL. The issuer name identifies the entity that signed (and * issued) the CRL. * @@ -287,14 +288,14 @@ public abstract class X509CRL extends CRL implements X509Extension { * AttributeType ::= OBJECT IDENTIFIER * AttributeValue ::= ANY *

    - * The Name describes a hierarchical name composed of + * The {@code Name} describes a hierarchical name composed of * attributes, * such as country name, and corresponding values, such as US. - * The type of the AttributeValue component is determined by - * the AttributeType; in general it will be a - * directoryString. A directoryString is usually - * one of PrintableString, - * TeletexString or UniversalString. + * The type of the {@code AttributeValue} component is determined by + * the {@code AttributeType}; in general it will be a + * {@code directoryString}. A {@code directoryString} is usually + * one of {@code PrintableString}, + * {@code TeletexString} or {@code UniversalString}. * * @return a Principal whose name is the issuer distinguished name. */ @@ -302,11 +303,11 @@ public abstract class X509CRL extends CRL implements X509Extension { /** * Returns the issuer (issuer distinguished name) value from the - * CRL as an X500Principal. + * CRL as an {@code X500Principal}. *

    * It is recommended that subclasses override this method. * - * @return an X500Principal representing the issuer + * @return an {@code X500Principal} representing the issuer * distinguished name * @since 1.4 */ @@ -318,7 +319,7 @@ public abstract class X509CRL extends CRL implements X509Extension { } /** - * Gets the thisUpdate date from the CRL. + * Gets the {@code thisUpdate} date from the CRL. * The ASN.1 definition for this is: *

          * thisUpdate   ChoiceOfTime
    @@ -327,14 +328,14 @@ public abstract class X509CRL extends CRL implements X509Extension {
          *     generalTime    GeneralizedTime }
          * 
    * - * @return the thisUpdate date from the CRL. + * @return the {@code thisUpdate} date from the CRL. */ public abstract Date getThisUpdate(); /** - * Gets the nextUpdate date from the CRL. + * Gets the {@code nextUpdate} date from the CRL. * - * @return the nextUpdate date from the CRL, or null if + * @return the {@code nextUpdate} date from the CRL, or null if * not present. */ public abstract Date getNextUpdate(); @@ -388,7 +389,7 @@ public abstract class X509CRL extends CRL implements X509Extension { /** * Gets the DER-encoded CRL information, the - * tbsCertList from this CRL. + * {@code tbsCertList} from this CRL. * This can be used to verify the signature independently. * * @return the DER-encoded CRL information. @@ -397,7 +398,7 @@ public abstract class X509CRL extends CRL implements X509Extension { public abstract byte[] getTBSCertList() throws CRLException; /** - * Gets the signature value (the raw signature bits) from + * Gets the {@code signature} value (the raw signature bits) from * the CRL. * The ASN.1 definition for this is: *
    @@ -413,7 +414,8 @@ public abstract class X509CRL extends CRL implements X509Extension {
          * signature algorithm. An example is the string "SHA256withRSA".
          * The ASN.1 definition for this is:
          * 
    -     * signatureAlgorithm   AlgorithmIdentifier

    + * signatureAlgorithm AlgorithmIdentifier + * * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL } @@ -422,7 +424,7 @@ public abstract class X509CRL extends CRL implements X509Extension { * -- algorithm object identifier value *

    * - *

    The algorithm name is determined from the algorithm + *

    The algorithm name is determined from the {@code algorithm} * OID string. * * @return the signature algorithm name. diff --git a/src/share/classes/java/security/cert/X509CRLEntry.java b/src/share/classes/java/security/cert/X509CRLEntry.java index 517bbd2c03d2abe99f1d0a17216461f7bd865270..268fa81958701309c17d2c33b1a95dfe83fcce25 100644 --- a/src/share/classes/java/security/cert/X509CRLEntry.java +++ b/src/share/classes/java/security/cert/X509CRLEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,11 +43,11 @@ import sun.security.x509.X509CRLEntryImpl; * crlEntryExtensions Extensions OPTIONAL * -- if present, must be v2 * } OPTIONAL - *

    + * * CertificateSerialNumber ::= INTEGER - *

    + * * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension - *

    + * * Extension ::= SEQUENCE { * extnId OBJECT IDENTIFIER, * critical BOOLEAN DEFAULT FALSE, @@ -68,8 +68,8 @@ public abstract class X509CRLEntry implements X509Extension { /** * Compares this CRL entry for equality with the given - * object. If the other object is an - * instanceof X509CRLEntry, then + * object. If the {@code other} object is an + * {@code instanceof} {@code X509CRLEntry}, then * its encoded form (the inner SEQUENCE) is retrieved and compared * with the encoded form of this CRL entry. * @@ -178,7 +178,7 @@ public abstract class X509CRLEntry implements X509Extension { * in the Reason Code extension of this CRL entry. * * @return the reason the certificate has been revoked, or - * null if this CRL entry does not have + * {@code null} if this CRL entry does not have * a Reason Code extension * @since 1.7 */ diff --git a/src/share/classes/java/security/cert/X509CRLSelector.java b/src/share/classes/java/security/cert/X509CRLSelector.java index 4258da396391629908e49b265b1e4e7aede39176..0580ee36bf280ffa5b936900b1c6d44e3a5847f5 100644 --- a/src/share/classes/java/security/cert/X509CRLSelector.java +++ b/src/share/classes/java/security/cert/X509CRLSelector.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,18 +37,18 @@ import sun.security.x509.CRLNumberExtension; import sun.security.x509.X500Name; /** - * A CRLSelector that selects X509CRLs that + * A {@code CRLSelector} that selects {@code X509CRLs} that * match all specified criteria. This class is particularly useful when - * selecting CRLs from a CertStore to check revocation status + * selecting CRLs from a {@code CertStore} to check revocation status * of a particular certificate. *

    - * When first constructed, an X509CRLSelector has no criteria - * enabled and each of the get methods return a default - * value (null). Therefore, the {@link #match match} method - * would return true for any X509CRL. Typically, + * When first constructed, an {@code X509CRLSelector} has no criteria + * enabled and each of the {@code get} methods return a default + * value ({@code null}). Therefore, the {@link #match match} method + * would return {@code true} for any {@code X509CRL}. Typically, * several criteria are enabled (by calling {@link #setIssuers setIssuers} * or {@link #setDateAndTime setDateAndTime}, for instance) and then the - * X509CRLSelector is passed to + * {@code X509CRLSelector} is passed to * {@link CertStore#getCRLs CertStore.getCRLs} or some similar * method. *

    @@ -86,35 +86,35 @@ public class X509CRLSelector implements CRLSelector { private long skew = 0; /** - * Creates an X509CRLSelector. Initially, no criteria are set - * so any X509CRL will match. + * Creates an {@code X509CRLSelector}. Initially, no criteria are set + * so any {@code X509CRL} will match. */ public X509CRLSelector() {} /** * Sets the issuerNames criterion. The issuer distinguished name in the - * X509CRL must match at least one of the specified - * distinguished names. If null, any issuer distinguished name + * {@code X509CRL} must match at least one of the specified + * distinguished names. If {@code null}, any issuer distinguished name * will do. *

    * This method allows the caller to specify, with a single method call, - * the complete set of issuer names which X509CRLs may contain. + * the complete set of issuer names which {@code X509CRLs} may contain. * The specified value replaces the previous value for the issuerNames * criterion. *

    - * The names parameter (if not null) is a - * Collection of X500Principals. + * The {@code names} parameter (if not {@code null}) is a + * {@code Collection} of {@code X500Principal}s. *

    - * Note that the names parameter can contain duplicate + * Note that the {@code names} parameter can contain duplicate * distinguished names, but they may be removed from the - * Collection of names returned by the + * {@code Collection} of names returned by the * {@link #getIssuers getIssuers} method. *

    - * Note that a copy is performed on the Collection to + * Note that a copy is performed on the {@code Collection} to * protect against subsequent modifications. * - * @param issuers a Collection of X500Principals - * (or null) + * @param issuers a {@code Collection} of X500Principals + * (or {@code null}) * @see #getIssuers * @since 1.5 */ @@ -138,31 +138,31 @@ public class X509CRLSelector implements CRLSelector { * this method. See {@link #addIssuerName(String)} for more information. *

    * Sets the issuerNames criterion. The issuer distinguished name in the - * X509CRL must match at least one of the specified - * distinguished names. If null, any issuer distinguished name + * {@code X509CRL} must match at least one of the specified + * distinguished names. If {@code null}, any issuer distinguished name * will do. *

    * This method allows the caller to specify, with a single method call, - * the complete set of issuer names which X509CRLs may contain. + * the complete set of issuer names which {@code X509CRLs} may contain. * The specified value replaces the previous value for the issuerNames * criterion. *

    - * The names parameter (if not null) is a - * Collection of names. Each name is a String + * The {@code names} parameter (if not {@code null}) is a + * {@code Collection} of names. Each name is a {@code String} * or a byte array representing a distinguished name (in * RFC 2253 or - * ASN.1 DER encoded form, respectively). If null is supplied + * ASN.1 DER encoded form, respectively). If {@code null} is supplied * as the value for this argument, no issuerNames check will be performed. *

    - * Note that the names parameter can contain duplicate + * Note that the {@code names} parameter can contain duplicate * distinguished names, but they may be removed from the - * Collection of names returned by the + * {@code Collection} of names returned by the * {@link #getIssuerNames getIssuerNames} method. *

    * If a name is specified as a byte array, it should contain a single DER * encoded distinguished name, as defined in X.501. The ASN.1 notation for * this structure is as follows. - *

    
    +     * 
    {@code
          * Name ::= CHOICE {
          *   RDNSequence }
          *
    @@ -185,12 +185,12 @@ public class X509CRLSelector implements CRLSelector {
          *       universalString         UniversalString (SIZE (1..MAX)),
          *       utf8String              UTF8String (SIZE (1.. MAX)),
          *       bmpString               BMPString (SIZE (1..MAX)) }
    -     * 
    + * }
    *

    - * Note that a deep copy is performed on the Collection to + * Note that a deep copy is performed on the {@code Collection} to * protect against subsequent modifications. * - * @param names a Collection of names (or null) + * @param names a {@code Collection} of names (or {@code null}) * @throws IOException if a parsing error occurs * @see #getIssuerNames */ @@ -208,11 +208,11 @@ public class X509CRLSelector implements CRLSelector { /** * Adds a name to the issuerNames criterion. The issuer distinguished - * name in the X509CRL must match at least one of the specified + * name in the {@code X509CRL} must match at least one of the specified * distinguished names. *

    * This method allows the caller to add a name to the set of issuer names - * which X509CRLs may contain. The specified name is added to + * which {@code X509CRLs} may contain. The specified name is added to * any previous value for the issuerNames criterion. * If the specified name is a duplicate, it may be ignored. * @@ -232,11 +232,11 @@ public class X509CRLSelector implements CRLSelector { * names. *

    * Adds a name to the issuerNames criterion. The issuer distinguished - * name in the X509CRL must match at least one of the specified + * name in the {@code X509CRL} must match at least one of the specified * distinguished names. *

    * This method allows the caller to add a name to the set of issuer names - * which X509CRLs may contain. The specified name is added to + * which {@code X509CRLs} may contain. The specified name is added to * any previous value for the issuerNames criterion. * If the specified name is a duplicate, it may be ignored. * @@ -249,11 +249,11 @@ public class X509CRLSelector implements CRLSelector { /** * Adds a name to the issuerNames criterion. The issuer distinguished - * name in the X509CRL must match at least one of the specified + * name in the {@code X509CRL} must match at least one of the specified * distinguished names. *

    * This method allows the caller to add a name to the set of issuer names - * which X509CRLs may contain. The specified name is added to + * which {@code X509CRLs} may contain. The specified name is added to * any previous value for the issuerNames criterion. If the specified name * is a duplicate, it may be ignored. * If a name is specified as a byte array, it should contain a single DER @@ -279,7 +279,7 @@ public class X509CRLSelector implements CRLSelector { /** * A private method that adds a name (String or byte array) to the * issuerNames criterion. The issuer distinguished - * name in the X509CRL must match at least one of the specified + * name in the {@code X509CRL} must match at least one of the specified * distinguished names. * * @param name the name in string or byte array form @@ -301,11 +301,11 @@ public class X509CRLSelector implements CRLSelector { * Clone and check an argument of the form passed to * setIssuerNames. Throw an IOException if the argument is malformed. * - * @param names a Collection of names. Each entry is a + * @param names a {@code Collection} of names. Each entry is a * String or a byte array (the name, in string or ASN.1 - * DER encoded form, respectively). null is + * DER encoded form, respectively). {@code null} is * not an acceptable value. - * @return a deep copy of the specified Collection + * @return a deep copy of the specified {@code Collection} * @throws IOException if a parsing error occurs */ private static HashSet cloneAndCheckIssuerNames(Collection names) @@ -334,11 +334,11 @@ public class X509CRLSelector implements CRLSelector { * into a RuntimeException. This method should be used when the object being * cloned has already been checked, so there should never be any exceptions. * - * @param names a Collection of names. Each entry is a + * @param names a {@code Collection} of names. Each entry is a * String or a byte array (the name, in string or ASN.1 - * DER encoded form, respectively). null is + * DER encoded form, respectively). {@code null} is * not an acceptable value. - * @return a deep copy of the specified Collection + * @return a deep copy of the specified {@code Collection} * @throws RuntimeException if a parsing error occurs */ private static HashSet cloneIssuerNames(Collection names) { @@ -354,7 +354,7 @@ public class X509CRLSelector implements CRLSelector { * returning a Collection of issuerX500Principals. * Throw an IOException if the argument is malformed. * - * @param names a Collection of names. Each entry is a + * @param names a {@code Collection} of names. Each entry is a * String or a byte array (the name, in string or ASN.1 * DER encoded form, respectively). Null is * not an acceptable value. @@ -380,24 +380,24 @@ public class X509CRLSelector implements CRLSelector { } /** - * Sets the minCRLNumber criterion. The X509CRL must have a + * Sets the minCRLNumber criterion. The {@code X509CRL} must have a * CRL number extension whose value is greater than or equal to the - * specified value. If null, no minCRLNumber check will be + * specified value. If {@code null}, no minCRLNumber check will be * done. * - * @param minCRL the minimum CRL number accepted (or null) + * @param minCRL the minimum CRL number accepted (or {@code null}) */ public void setMinCRLNumber(BigInteger minCRL) { this.minCRL = minCRL; } /** - * Sets the maxCRLNumber criterion. The X509CRL must have a + * Sets the maxCRLNumber criterion. The {@code X509CRL} must have a * CRL number extension whose value is less than or equal to the - * specified value. If null, no maxCRLNumber check will be + * specified value. If {@code null}, no maxCRLNumber check will be * done. * - * @param maxCRL the maximum CRL number accepted (or null) + * @param maxCRL the maximum CRL number accepted (or {@code null}) */ public void setMaxCRLNumber(BigInteger maxCRL) { this.maxCRL = maxCRL; @@ -406,16 +406,16 @@ public class X509CRLSelector implements CRLSelector { /** * Sets the dateAndTime criterion. The specified date must be * equal to or later than the value of the thisUpdate component - * of the X509CRL and earlier than the value of the - * nextUpdate component. There is no match if the X509CRL + * of the {@code X509CRL} and earlier than the value of the + * nextUpdate component. There is no match if the {@code X509CRL} * does not contain a nextUpdate component. - * If null, no dateAndTime check will be done. + * If {@code null}, no dateAndTime check will be done. *

    - * Note that the Date supplied here is cloned to protect + * Note that the {@code Date} supplied here is cloned to protect * against subsequent modifications. * - * @param dateAndTime the Date to match against - * (or null) + * @param dateAndTime the {@code Date} to match against + * (or {@code null}) * @see #getDateAndTime */ public void setDateAndTime(Date dateAndTime) { @@ -438,13 +438,13 @@ public class X509CRLSelector implements CRLSelector { /** * Sets the certificate being checked. This is not a criterion. Rather, - * it is optional information that may help a CertStore + * it is optional information that may help a {@code CertStore} * find CRLs that would be relevant when checking revocation for the - * specified certificate. If null is specified, then no + * specified certificate. If {@code null} is specified, then no * such optional information is provided. * - * @param cert the X509Certificate being checked - * (or null) + * @param cert the {@code X509Certificate} being checked + * (or {@code null}) * @see #getCertificateChecking */ public void setCertificateChecking(X509Certificate cert) { @@ -453,15 +453,15 @@ public class X509CRLSelector implements CRLSelector { /** * Returns the issuerNames criterion. The issuer distinguished - * name in the X509CRL must match at least one of the specified - * distinguished names. If the value returned is null, any + * name in the {@code X509CRL} must match at least one of the specified + * distinguished names. If the value returned is {@code null}, any * issuer distinguished name will do. *

    - * If the value returned is not null, it is a - * unmodifiable Collection of X500Principals. + * If the value returned is not {@code null}, it is a + * unmodifiable {@code Collection} of {@code X500Principal}s. * - * @return an unmodifiable Collection of names - * (or null) + * @return an unmodifiable {@code Collection} of names + * (or {@code null}) * @see #setIssuers * @since 1.5 */ @@ -474,25 +474,25 @@ public class X509CRLSelector implements CRLSelector { /** * Returns a copy of the issuerNames criterion. The issuer distinguished - * name in the X509CRL must match at least one of the specified - * distinguished names. If the value returned is null, any + * name in the {@code X509CRL} must match at least one of the specified + * distinguished names. If the value returned is {@code null}, any * issuer distinguished name will do. *

    - * If the value returned is not null, it is a - * Collection of names. Each name is a String + * If the value returned is not {@code null}, it is a + * {@code Collection} of names. Each name is a {@code String} * or a byte array representing a distinguished name (in RFC 2253 or * ASN.1 DER encoded form, respectively). Note that the - * Collection returned may contain duplicate names. + * {@code Collection} returned may contain duplicate names. *

    * If a name is specified as a byte array, it should contain a single DER * encoded distinguished name, as defined in X.501. The ASN.1 notation for * this structure is given in the documentation for * {@link #setIssuerNames setIssuerNames(Collection names)}. *

    - * Note that a deep copy is performed on the Collection to + * Note that a deep copy is performed on the {@code Collection} to * protect against subsequent modifications. * - * @return a Collection of names (or null) + * @return a {@code Collection} of names (or {@code null}) * @see #setIssuerNames */ public Collection getIssuerNames() { @@ -503,23 +503,23 @@ public class X509CRLSelector implements CRLSelector { } /** - * Returns the minCRLNumber criterion. The X509CRL must have a + * Returns the minCRLNumber criterion. The {@code X509CRL} must have a * CRL number extension whose value is greater than or equal to the - * specified value. If null, no minCRLNumber check will be done. + * specified value. If {@code null}, no minCRLNumber check will be done. * - * @return the minimum CRL number accepted (or null) + * @return the minimum CRL number accepted (or {@code null}) */ public BigInteger getMinCRL() { return minCRL; } /** - * Returns the maxCRLNumber criterion. The X509CRL must have a + * Returns the maxCRLNumber criterion. The {@code X509CRL} must have a * CRL number extension whose value is less than or equal to the - * specified value. If null, no maxCRLNumber check will be + * specified value. If {@code null}, no maxCRLNumber check will be * done. * - * @return the maximum CRL number accepted (or null) + * @return the maximum CRL number accepted (or {@code null}) */ public BigInteger getMaxCRL() { return maxCRL; @@ -528,15 +528,15 @@ public class X509CRLSelector implements CRLSelector { /** * Returns the dateAndTime criterion. The specified date must be * equal to or later than the value of the thisUpdate component - * of the X509CRL and earlier than the value of the + * of the {@code X509CRL} and earlier than the value of the * nextUpdate component. There is no match if the - * X509CRL does not contain a nextUpdate component. - * If null, no dateAndTime check will be done. + * {@code X509CRL} does not contain a nextUpdate component. + * If {@code null}, no dateAndTime check will be done. *

    - * Note that the Date returned is cloned to protect against + * Note that the {@code Date} returned is cloned to protect against * subsequent modifications. * - * @return the Date to match against (or null) + * @return the {@code Date} to match against (or {@code null}) * @see #setDateAndTime */ public Date getDateAndTime() { @@ -547,12 +547,12 @@ public class X509CRLSelector implements CRLSelector { /** * Returns the certificate being checked. This is not a criterion. Rather, - * it is optional information that may help a CertStore + * it is optional information that may help a {@code CertStore} * find CRLs that would be relevant when checking revocation for the - * specified certificate. If the value returned is null, then + * specified certificate. If the value returned is {@code null}, then * no such optional information is provided. * - * @return the certificate being checked (or null) + * @return the certificate being checked (or {@code null}) * @see #setCertificateChecking */ public X509Certificate getCertificateChecking() { @@ -560,10 +560,10 @@ public class X509CRLSelector implements CRLSelector { } /** - * Returns a printable representation of the X509CRLSelector. + * Returns a printable representation of the {@code X509CRLSelector}. * - * @return a String describing the contents of the - * X509CRLSelector. + * @return a {@code String} describing the contents of the + * {@code X509CRLSelector}. */ public String toString() { StringBuffer sb = new StringBuffer(); @@ -587,11 +587,11 @@ public class X509CRLSelector implements CRLSelector { } /** - * Decides whether a CRL should be selected. + * Decides whether a {@code CRL} should be selected. * - * @param crl the CRL to be checked - * @return true if the CRL should be selected, - * false otherwise + * @param crl the {@code CRL} to be checked + * @return {@code true} if the {@code CRL} should be selected, + * {@code false} otherwise */ public boolean match(CRL crl) { if (!(crl instanceof X509CRL)) { diff --git a/src/share/classes/java/security/cert/X509CertSelector.java b/src/share/classes/java/security/cert/X509CertSelector.java index 19ca2cb515d0e0e9158c728c4dc7b5b5efd901c7..e44dba125e450fcdc6c1a6525b4bb01bdde1b81a 100644 --- a/src/share/classes/java/security/cert/X509CertSelector.java +++ b/src/share/classes/java/security/cert/X509CertSelector.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,27 +39,27 @@ import sun.security.util.ObjectIdentifier; import sun.security.x509.*; /** - * A CertSelector that selects X509Certificates that + * A {@code CertSelector} that selects {@code X509Certificates} that * match all specified criteria. This class is particularly useful when - * selecting certificates from a CertStore to build a + * selecting certificates from a {@code CertStore} to build a * PKIX-compliant certification path. *

    - * When first constructed, an X509CertSelector has no criteria - * enabled and each of the get methods return a default value - * (null, or -1 for the {@link #getBasicConstraints + * When first constructed, an {@code X509CertSelector} has no criteria + * enabled and each of the {@code get} methods return a default value + * ({@code null}, or {@code -1} for the {@link #getBasicConstraints * getBasicConstraints} method). Therefore, the {@link #match match} - * method would return true for any X509Certificate. + * method would return {@code true} for any {@code X509Certificate}. * Typically, several criteria are enabled (by calling * {@link #setIssuer setIssuer} or * {@link #setKeyUsage setKeyUsage}, for instance) and then the - * X509CertSelector is passed to + * {@code X509CertSelector} is passed to * {@link CertStore#getCertificates CertStore.getCertificates} or some similar * method. *

    * Several criteria can be enabled (by calling {@link #setIssuer setIssuer} * and {@link #setSerialNumber setSerialNumber}, - * for example) such that the match method - * usually uniquely matches a single X509Certificate. We say + * for example) such that the {@code match} method + * usually uniquely matches a single {@code X509Certificate}. We say * usually, since it is possible for two issuing CAs to have the same * distinguished name and each issue a certificate with the same serial * number. Other unique combinations include the issuer, subject, @@ -149,8 +149,8 @@ public class X509CertSelector implements CertSelector { static final int NAME_OID = 8; /** - * Creates an X509CertSelector. Initially, no criteria are set - * so any X509Certificate will match. + * Creates an {@code X509CertSelector}. Initially, no criteria are set + * so any {@code X509Certificate} will match. */ public X509CertSelector() { // empty @@ -158,17 +158,17 @@ public class X509CertSelector implements CertSelector { /** * Sets the certificateEquals criterion. The specified - * X509Certificate must be equal to the - * X509Certificate passed to the match method. - * If null, then this check is not applied. + * {@code X509Certificate} must be equal to the + * {@code X509Certificate} passed to the {@code match} method. + * If {@code null}, then this check is not applied. * *

    This method is particularly useful when it is necessary to * match a single certificate. Although other criteria can be specified * in conjunction with the certificateEquals criterion, it is usually not * practical or necessary. * - * @param cert the X509Certificate to match (or - * null) + * @param cert the {@code X509Certificate} to match (or + * {@code null}) * @see #getCertificate */ public void setCertificate(X509Certificate cert) { @@ -178,11 +178,11 @@ public class X509CertSelector implements CertSelector { /** * Sets the serialNumber criterion. The specified serial number * must match the certificate serial number in the - * X509Certificate. If null, any certificate + * {@code X509Certificate}. If {@code null}, any certificate * serial number will do. * * @param serial the certificate serial number to match - * (or null) + * (or {@code null}) * @see #getSerialNumber */ public void setSerialNumber(BigInteger serial) { @@ -192,11 +192,11 @@ public class X509CertSelector implements CertSelector { /** * Sets the issuer criterion. The specified distinguished name * must match the issuer distinguished name in the - * X509Certificate. If null, any issuer + * {@code X509Certificate}. If {@code null}, any issuer * distinguished name will do. * * @param issuer a distinguished name as X500Principal - * (or null) + * (or {@code null}) * @since 1.5 */ public void setIssuer(X500Principal issuer) { @@ -213,14 +213,14 @@ public class X509CertSelector implements CertSelector { *

    * Sets the issuer criterion. The specified distinguished name * must match the issuer distinguished name in the - * X509Certificate. If null, any issuer + * {@code X509Certificate}. If {@code null}, any issuer * distinguished name will do. *

    - * If issuerDN is not null, it should contain a + * If {@code issuerDN} is not {@code null}, it should contain a * distinguished name, in RFC 2253 format. * * @param issuerDN a distinguished name in RFC 2253 format - * (or null) + * (or {@code null}) * @throws IOException if a parsing error occurs (incorrect form for DN) */ public void setIssuer(String issuerDN) throws IOException { @@ -234,14 +234,14 @@ public class X509CertSelector implements CertSelector { /** * Sets the issuer criterion. The specified distinguished name * must match the issuer distinguished name in the - * X509Certificate. If null is specified, + * {@code X509Certificate}. If {@code null} is specified, * the issuer criterion is disabled and any issuer distinguished name will * do. *

    - * If issuerDN is not null, it should contain a + * If {@code issuerDN} is not {@code null}, it should contain a * single DER encoded distinguished name, as defined in X.501. The ASN.1 * notation for this structure is as follows. - *

    
    +     * 
    {@code
          * Name ::= CHOICE {
          *   RDNSequence }
          *
    @@ -264,13 +264,13 @@ public class X509CertSelector implements CertSelector {
          *       universalString         UniversalString (SIZE (1..MAX)),
          *       utf8String              UTF8String (SIZE (1.. MAX)),
          *       bmpString               BMPString (SIZE (1..MAX)) }
    -     * 
    + * }
    *

    * Note that the byte array specified here is cloned to protect against * subsequent modifications. * * @param issuerDN a byte array containing the distinguished name - * in ASN.1 DER encoded form (or null) + * in ASN.1 DER encoded form (or {@code null}) * @throws IOException if an encoding error occurs (incorrect form for DN) */ public void setIssuer(byte[] issuerDN) throws IOException { @@ -284,11 +284,11 @@ public class X509CertSelector implements CertSelector { /** * Sets the subject criterion. The specified distinguished name * must match the subject distinguished name in the - * X509Certificate. If null, any subject + * {@code X509Certificate}. If {@code null}, any subject * distinguished name will do. * * @param subject a distinguished name as X500Principal - * (or null) + * (or {@code null}) * @since 1.5 */ public void setSubject(X500Principal subject) { @@ -304,14 +304,14 @@ public class X509CertSelector implements CertSelector { *

    * Sets the subject criterion. The specified distinguished name * must match the subject distinguished name in the - * X509Certificate. If null, any subject + * {@code X509Certificate}. If {@code null}, any subject * distinguished name will do. *

    - * If subjectDN is not null, it should contain a + * If {@code subjectDN} is not {@code null}, it should contain a * distinguished name, in RFC 2253 format. * * @param subjectDN a distinguished name in RFC 2253 format - * (or null) + * (or {@code null}) * @throws IOException if a parsing error occurs (incorrect form for DN) */ public void setSubject(String subjectDN) throws IOException { @@ -325,16 +325,16 @@ public class X509CertSelector implements CertSelector { /** * Sets the subject criterion. The specified distinguished name * must match the subject distinguished name in the - * X509Certificate. If null, any subject + * {@code X509Certificate}. If {@code null}, any subject * distinguished name will do. *

    - * If subjectDN is not null, it should contain a + * If {@code subjectDN} is not {@code null}, it should contain a * single DER encoded distinguished name, as defined in X.501. For the ASN.1 * notation for this structure, see * {@link #setIssuer(byte [] issuerDN) setIssuer(byte [] issuerDN)}. * * @param subjectDN a byte array containing the distinguished name in - * ASN.1 DER format (or null) + * ASN.1 DER format (or {@code null}) * @throws IOException if an encoding error occurs (incorrect form for DN) */ public void setSubject(byte[] subjectDN) throws IOException { @@ -347,34 +347,34 @@ public class X509CertSelector implements CertSelector { /** * Sets the subjectKeyIdentifier criterion. The - * X509Certificate must contain a SubjectKeyIdentifier + * {@code X509Certificate} must contain a SubjectKeyIdentifier * extension for which the contents of the extension * matches the specified criterion value. - * If the criterion value is null, no + * If the criterion value is {@code null}, no * subjectKeyIdentifier check will be done. *

    - * If subjectKeyID is not null, it + * If {@code subjectKeyID} is not {@code null}, it * should contain a single DER encoded value corresponding to the contents * of the extension value (not including the object identifier, * criticality setting, and encapsulating OCTET STRING) * for a SubjectKeyIdentifier extension. * The ASN.1 notation for this structure follows. *

    - *

    
    +     * 
    {@code
          * SubjectKeyIdentifier ::= KeyIdentifier
          *
          * KeyIdentifier ::= OCTET STRING
    -     * 
    + * }
    *

    * Since the format of subject key identifiers is not mandated by * any standard, subject key identifiers are not parsed by the - * X509CertSelector. Instead, the values are compared using + * {@code X509CertSelector}. Instead, the values are compared using * a byte-by-byte comparison. *

    * Note that the byte array supplied here is cloned to protect against * subsequent modifications. * - * @param subjectKeyID the subject key identifier (or null) + * @param subjectKeyID the subject key identifier (or {@code null}) * @see #getSubjectKeyIdentifier */ public void setSubjectKeyIdentifier(byte[] subjectKeyID) { @@ -387,46 +387,46 @@ public class X509CertSelector implements CertSelector { /** * Sets the authorityKeyIdentifier criterion. The - * X509Certificate must contain an + * {@code X509Certificate} must contain an * AuthorityKeyIdentifier extension for which the contents of the * extension value matches the specified criterion value. - * If the criterion value is null, no + * If the criterion value is {@code null}, no * authorityKeyIdentifier check will be done. *

    - * If authorityKeyID is not null, it + * If {@code authorityKeyID} is not {@code null}, it * should contain a single DER encoded value corresponding to the contents * of the extension value (not including the object identifier, * criticality setting, and encapsulating OCTET STRING) * for an AuthorityKeyIdentifier extension. * The ASN.1 notation for this structure follows. *

    - *

    
    +     * 
    {@code
          * AuthorityKeyIdentifier ::= SEQUENCE {
          *    keyIdentifier             [0] KeyIdentifier           OPTIONAL,
          *    authorityCertIssuer       [1] GeneralNames            OPTIONAL,
          *    authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL  }
          *
          * KeyIdentifier ::= OCTET STRING
    -     * 
    + * }
    *

    * Authority key identifiers are not parsed by the - * X509CertSelector. Instead, the values are + * {@code X509CertSelector}. Instead, the values are * compared using a byte-by-byte comparison. *

    - * When the keyIdentifier field of - * AuthorityKeyIdentifier is populated, the value is - * usually taken from the SubjectKeyIdentifier extension + * When the {@code keyIdentifier} field of + * {@code AuthorityKeyIdentifier} is populated, the value is + * usually taken from the {@code SubjectKeyIdentifier} extension * in the issuer's certificate. Note, however, that the result of - * X509Certificate.getExtensionValue(<SubjectKeyIdentifier Object - * Identifier>) on the issuer's certificate may NOT be used - * directly as the input to setAuthorityKeyIdentifier. + * {@code X509Certificate.getExtensionValue()} on the issuer's certificate may NOT be used + * directly as the input to {@code setAuthorityKeyIdentifier}. * This is because the SubjectKeyIdentifier contains * only a KeyIdentifier OCTET STRING, and not a SEQUENCE of * KeyIdentifier, GeneralNames, and CertificateSerialNumber. * In order to use the extension value of the issuer certificate's - * SubjectKeyIdentifier + * {@code SubjectKeyIdentifier} * extension, it will be necessary to extract the value of the embedded - * KeyIdentifier OCTET STRING, then DER encode this OCTET + * {@code KeyIdentifier} OCTET STRING, then DER encode this OCTET * STRING inside a SEQUENCE. * For more details on SubjectKeyIdentifier, see * {@link #setSubjectKeyIdentifier(byte[] subjectKeyID)}. @@ -435,7 +435,7 @@ public class X509CertSelector implements CertSelector { * subsequent modifications. * * @param authorityKeyID the authority key identifier - * (or null) + * (or {@code null}) * @see #getAuthorityKeyIdentifier */ public void setAuthorityKeyIdentifier(byte[] authorityKeyID) { @@ -449,13 +449,13 @@ public class X509CertSelector implements CertSelector { /** * Sets the certificateValid criterion. The specified date must fall * within the certificate validity period for the - * X509Certificate. If null, no certificateValid + * {@code X509Certificate}. If {@code null}, no certificateValid * check will be done. *

    - * Note that the Date supplied here is cloned to protect + * Note that the {@code Date} supplied here is cloned to protect * against subsequent modifications. * - * @param certValid the Date to check (or null) + * @param certValid the {@code Date} to check (or {@code null}) * @see #getCertificateValid */ public void setCertificateValid(Date certValid) { @@ -469,14 +469,14 @@ public class X509CertSelector implements CertSelector { /** * Sets the privateKeyValid criterion. The specified date must fall * within the private key validity period for the - * X509Certificate. If null, no privateKeyValid + * {@code X509Certificate}. If {@code null}, no privateKeyValid * check will be done. *

    - * Note that the Date supplied here is cloned to protect + * Note that the {@code Date} supplied here is cloned to protect * against subsequent modifications. * - * @param privateKeyValid the Date to check (or - * null) + * @param privateKeyValid the {@code Date} to check (or + * {@code null}) * @see #getPrivateKeyValid */ public void setPrivateKeyValid(Date privateKeyValid) { @@ -489,12 +489,12 @@ public class X509CertSelector implements CertSelector { /** * Sets the subjectPublicKeyAlgID criterion. The - * X509Certificate must contain a subject public key - * with the specified algorithm. If null, no + * {@code X509Certificate} must contain a subject public key + * with the specified algorithm. If {@code null}, no * subjectPublicKeyAlgID check will be done. * * @param oid The object identifier (OID) of the algorithm to check - * for (or null). An OID is represented by a + * for (or {@code null}). An OID is represented by a * set of nonnegative integers separated by periods. * @throws IOException if the OID is invalid, such as * the first component being not 0, 1 or 2 or the second component @@ -512,10 +512,10 @@ public class X509CertSelector implements CertSelector { /** * Sets the subjectPublicKey criterion. The - * X509Certificate must contain the specified subject public - * key. If null, no subjectPublicKey check will be done. + * {@code X509Certificate} must contain the specified subject public + * key. If {@code null}, no subjectPublicKey check will be done. * - * @param key the subject public key to check for (or null) + * @param key the subject public key to check for (or {@code null}) * @see #getSubjectPublicKey */ public void setSubjectPublicKey(PublicKey key) { @@ -529,17 +529,17 @@ public class X509CertSelector implements CertSelector { } /** - * Sets the subjectPublicKey criterion. The X509Certificate - * must contain the specified subject public key. If null, + * Sets the subjectPublicKey criterion. The {@code X509Certificate} + * must contain the specified subject public key. If {@code null}, * no subjectPublicKey check will be done. *

    * Because this method allows the public key to be specified as a byte * array, it may be used for unknown key types. *

    - * If key is not null, it should contain a + * If {@code key} is not {@code null}, it should contain a * single DER encoded SubjectPublicKeyInfo structure, as defined in X.509. * The ASN.1 notation for this structure is as follows. - *

    
    +     * 
    {@code
          * SubjectPublicKeyInfo  ::=  SEQUENCE  {
          *   algorithm            AlgorithmIdentifier,
          *   subjectPublicKey     BIT STRING  }
    @@ -550,13 +550,13 @@ public class X509CertSelector implements CertSelector {
          *                              -- contains a value of the type
          *                              -- registered for use with the
          *                              -- algorithm object identifier value
    -     * 
    + * }
    *

    * Note that the byte array supplied here is cloned to protect against * subsequent modifications. * * @param key a byte array containing the subject public key in ASN.1 DER - * form (or null) + * form (or {@code null}) * @throws IOException if an encoding error occurs (incorrect form for * subject public key) * @see #getSubjectPublicKey @@ -572,9 +572,9 @@ public class X509CertSelector implements CertSelector { } /** - * Sets the keyUsage criterion. The X509Certificate - * must allow the specified keyUsage values. If null, no - * keyUsage check will be done. Note that an X509Certificate + * Sets the keyUsage criterion. The {@code X509Certificate} + * must allow the specified keyUsage values. If {@code null}, no + * keyUsage check will be done. Note that an {@code X509Certificate} * that has no keyUsage extension implicitly allows all keyUsage values. *

    * Note that the boolean array supplied here is cloned to protect against @@ -583,7 +583,7 @@ public class X509CertSelector implements CertSelector { * @param keyUsage a boolean array in the same format as the boolean * array returned by * {@link X509Certificate#getKeyUsage() X509Certificate.getKeyUsage()}. - * Or null. + * Or {@code null}. * @see #getKeyUsage */ public void setKeyUsage(boolean[] keyUsage) { @@ -595,18 +595,18 @@ public class X509CertSelector implements CertSelector { } /** - * Sets the extendedKeyUsage criterion. The X509Certificate + * Sets the extendedKeyUsage criterion. The {@code X509Certificate} * must allow the specified key purposes in its extended key usage - * extension. If keyPurposeSet is empty or null, + * extension. If {@code keyPurposeSet} is empty or {@code null}, * no extendedKeyUsage check will be done. Note that an - * X509Certificate that has no extendedKeyUsage extension + * {@code X509Certificate} that has no extendedKeyUsage extension * implicitly allows all key purposes. *

    - * Note that the Set is cloned to protect against + * Note that the {@code Set} is cloned to protect against * subsequent modifications. * - * @param keyPurposeSet a Set of key purpose OIDs in string - * format (or null). Each OID is represented by a set of + * @param keyPurposeSet a {@code Set} of key purpose OIDs in string + * format (or {@code null}). Each OID is represented by a set of * nonnegative integers separated by periods. * @throws IOException if the OID is invalid, such as * the first component being not 0, 1 or 2 or the second component @@ -632,15 +632,15 @@ public class X509CertSelector implements CertSelector { * specified in the {@link #setSubjectAlternativeNames * setSubjectAlternativeNames} or {@link #addSubjectAlternativeName * addSubjectAlternativeName} methods. If enabled, - * the X509Certificate must contain all of the + * the {@code X509Certificate} must contain all of the * specified subject alternative names. If disabled, the - * X509Certificate must contain at least one of the + * {@code X509Certificate} must contain at least one of the * specified subject alternative names. * - *

    The matchAllNames flag is true by default. + *

    The matchAllNames flag is {@code true} by default. * - * @param matchAllNames if true, the flag is enabled; - * if false, the flag is disabled. + * @param matchAllNames if {@code true}, the flag is enabled; + * if {@code false}, the flag is disabled. * @see #getMatchAllSubjectAltNames */ public void setMatchAllSubjectAltNames(boolean matchAllNames) { @@ -649,7 +649,7 @@ public class X509CertSelector implements CertSelector { /** * Sets the subjectAlternativeNames criterion. The - * X509Certificate must contain all or at least one of the + * {@code X509Certificate} must contain all or at least one of the * specified subjectAlternativeNames, depending on the value of * the matchAllNames flag (see {@link #setMatchAllSubjectAltNames * setMatchAllSubjectAltNames}). @@ -659,19 +659,19 @@ public class X509CertSelector implements CertSelector { * subjectAlternativeNames criterion. The specified value replaces * the previous value for the subjectAlternativeNames criterion. *

    - * The names parameter (if not null) is a - * Collection with one + * The {@code names} parameter (if not {@code null}) is a + * {@code Collection} with one * entry for each name to be included in the subject alternative name - * criterion. Each entry is a List whose first entry is an - * Integer (the name type, 0-8) and whose second - * entry is a String or a byte array (the name, in + * criterion. Each entry is a {@code List} whose first entry is an + * {@code Integer} (the name type, 0-8) and whose second + * entry is a {@code String} or a byte array (the name, in * string or ASN.1 DER encoded form, respectively). - * There can be multiple names of the same type. If null + * There can be multiple names of the same type. If {@code null} * is supplied as the value for this argument, no * subjectAlternativeNames check will be performed. *

    - * Each subject alternative name in the Collection - * may be specified either as a String or as an ASN.1 encoded + * Each subject alternative name in the {@code Collection} + * may be specified either as a {@code String} or as an ASN.1 encoded * byte array. For more details about the formats used, see * {@link #addSubjectAlternativeName(int type, String name) * addSubjectAlternativeName(int type, String name)} and @@ -682,15 +682,15 @@ public class X509CertSelector implements CertSelector { * array form instead of the String form. See the note in * {@link #addSubjectAlternativeName(int, String)} for more information. *

    - * Note that the names parameter can contain duplicate + * Note that the {@code names} parameter can contain duplicate * names (same name and name type), but they may be removed from the - * Collection of names returned by the + * {@code Collection} of names returned by the * {@link #getSubjectAlternativeNames getSubjectAlternativeNames} method. *

    - * Note that a deep copy is performed on the Collection to + * Note that a deep copy is performed on the {@code Collection} to * protect against subsequent modifications. * - * @param names a Collection of names (or null) + * @param names a {@code Collection} of names (or {@code null}) * @throws IOException if a parsing error occurs * @see #getSubjectAlternativeNames */ @@ -714,7 +714,7 @@ public class X509CertSelector implements CertSelector { /** * Adds a name to the subjectAlternativeNames criterion. The - * X509Certificate must contain all or at least one + * {@code X509Certificate} must contain all or at least one * of the specified subjectAlternativeNames, depending on the value of * the matchAllNames flag (see {@link #setMatchAllSubjectAltNames * setMatchAllSubjectAltNames}). @@ -747,7 +747,7 @@ public class X509CertSelector implements CertSelector { * * @param type the name type (0-8, as specified in * RFC 3280, section 4.2.1.7) - * @param name the name in string form (not null) + * @param name the name in string form (not {@code null}) * @throws IOException if a parsing error occurs */ public void addSubjectAlternativeName(int type, String name) @@ -757,7 +757,7 @@ public class X509CertSelector implements CertSelector { /** * Adds a name to the subjectAlternativeNames criterion. The - * X509Certificate must contain all or at least one + * {@code X509Certificate} must contain all or at least one * of the specified subjectAlternativeNames, depending on the value of * the matchAllNames flag (see {@link #setMatchAllSubjectAltNames * setMatchAllSubjectAltNames}). @@ -774,7 +774,7 @@ public class X509CertSelector implements CertSelector { * the encoded value of the name, and should not include the tag associated * with the name in the GeneralName structure. The ASN.1 definition of this * structure appears below. - *

    
    +     * 
    {@code
          *  GeneralName ::= CHOICE {
          *       otherName                       [0]     OtherName,
          *       rfc822Name                      [1]     IA5String,
    @@ -785,7 +785,7 @@ public class X509CertSelector implements CertSelector {
          *       uniformResourceIdentifier       [6]     IA5String,
          *       iPAddress                       [7]     OCTET STRING,
          *       registeredID                    [8]     OBJECT IDENTIFIER}
    -     * 
    + * }
    *

    * Note that the byte array supplied here is cloned to protect against * subsequent modifications. @@ -802,7 +802,7 @@ public class X509CertSelector implements CertSelector { /** * A private method that adds a name (String or byte array) to the - * subjectAlternativeNames criterion. The X509Certificate + * subjectAlternativeNames criterion. The {@code X509Certificate} * must contain the specified subjectAlternativeName. * * @param type the name type (0-8, as specified in @@ -829,19 +829,19 @@ public class X509CertSelector implements CertSelector { /** * Parse an argument of the form passed to setSubjectAlternativeNames, - * returning a Collection of - * GeneralNameInterfaces. + * returning a {@code Collection} of + * {@code GeneralNameInterface}s. * Throw an IllegalArgumentException or a ClassCastException * if the argument is malformed. * * @param names a Collection with one entry per name. - * Each entry is a List whose first entry + * Each entry is a {@code List} whose first entry * is an Integer (the name type, 0-8) and whose second * entry is a String or a byte array (the name, in * string or ASN.1 DER encoded form, respectively). * There can be multiple names of the same type. Null is * not an acceptable value. - * @return a Set of GeneralNameInterfaces + * @return a Set of {@code GeneralNameInterface}s * @throws IOException if a parsing error occurs */ private static Set parseNames(Collection> names) throws IOException { @@ -865,8 +865,8 @@ public class X509CertSelector implements CertSelector { /** * Compare for equality two objects of the form passed to * setSubjectAlternativeNames (or X509CRLSelector.setIssuerNames). - * Throw an IllegalArgumentException or a - * ClassCastException if one of the objects is malformed. + * Throw an {@code IllegalArgumentException} or a + * {@code ClassCastException} if one of the objects is malformed. * * @param object1 a Collection containing the first object to compare * @param object2 a Collection containing the second object to compare @@ -880,7 +880,7 @@ public class X509CertSelector implements CertSelector { } /** - * Make a GeneralNameInterface out of a name type (0-8) and an + * Make a {@code GeneralNameInterface} out of a name type (0-8) and an * Object that may be a byte array holding the ASN.1 DER encoded * name or a String form of the name. Except for X.509 * Distinguished Names, the String form of the name must not be the @@ -989,7 +989,7 @@ public class X509CertSelector implements CertSelector { /** - * Sets the name constraints criterion. The X509Certificate + * Sets the name constraints criterion. The {@code X509Certificate} * must have subject and subject alternative names that * meet the specified name constraints. *

    @@ -998,7 +998,7 @@ public class X509CertSelector implements CertSelector { * would appear in the NameConstraints structure defined in RFC 3280 * and X.509. The ASN.1 definition of this structure appears below. * - *

    
    +     * 
    {@code
          *  NameConstraints ::= SEQUENCE {
          *       permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
          *       excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
    @@ -1022,7 +1022,7 @@ public class X509CertSelector implements CertSelector {
          *       uniformResourceIdentifier       [6]     IA5String,
          *       iPAddress                       [7]     OCTET STRING,
          *       registeredID                    [8]     OBJECT IDENTIFIER}
    -     * 
    + * }
    *

    * Note that the byte array supplied here is cloned to protect against * subsequent modifications. @@ -1031,7 +1031,7 @@ public class X509CertSelector implements CertSelector { * a NameConstraints extension to be used for checking * name constraints. Only the value of the extension is * included, not the OID or criticality flag. Can be - * null, + * {@code null}, * in which case no name constraints check will be performed. * @throws IOException if a parsing error occurs * @see #getNameConstraints @@ -1048,7 +1048,7 @@ public class X509CertSelector implements CertSelector { /** * Sets the basic constraints constraint. If the value is greater than or - * equal to zero, X509Certificates must include a + * equal to zero, {@code X509Certificates} must include a * basicConstraints extension with * a pathLen of at least this value. If the value is -2, only end-entity * certificates are accepted. If the value is -1, no check is done. @@ -1070,18 +1070,18 @@ public class X509CertSelector implements CertSelector { } /** - * Sets the policy constraint. The X509Certificate must + * Sets the policy constraint. The {@code X509Certificate} must * include at least one of the specified policies in its certificate - * policies extension. If certPolicySet is empty, then the - * X509Certificate must include at least some specified policy - * in its certificate policies extension. If certPolicySet is - * null, no policy check will be performed. + * policies extension. If {@code certPolicySet} is empty, then the + * {@code X509Certificate} must include at least some specified policy + * in its certificate policies extension. If {@code certPolicySet} is + * {@code null}, no policy check will be performed. *

    - * Note that the Set is cloned to protect against + * Note that the {@code Set} is cloned to protect against * subsequent modifications. * - * @param certPolicySet a Set of certificate policy OIDs in - * string format (or null). Each OID is + * @param certPolicySet a {@code Set} of certificate policy OIDs in + * string format (or {@code null}). Each OID is * represented by a set of nonnegative integers * separated by periods. * @throws IOException if a parsing error occurs on the OID such as @@ -1115,12 +1115,12 @@ public class X509CertSelector implements CertSelector { } /** - * Sets the pathToNames criterion. The X509Certificate must + * Sets the pathToNames criterion. The {@code X509Certificate} must * not include name constraints that would prohibit building a * path to the specified names. *

    * This method allows the caller to specify, with a single method call, - * the complete set of names which the X509Certificates's + * the complete set of names which the {@code X509Certificates}'s * name constraints must permit. The specified value replaces * the previous value for the pathToNames criterion. *

    @@ -1129,19 +1129,19 @@ public class X509CertSelector implements CertSelector { * built, any candidate certificate must not include name constraints that * would prohibit building a path to any of the names in the partial path. *

    - * The names parameter (if not null) is a - * Collection with one + * The {@code names} parameter (if not {@code null}) is a + * {@code Collection} with one * entry for each name to be included in the pathToNames - * criterion. Each entry is a List whose first entry is an - * Integer (the name type, 0-8) and whose second - * entry is a String or a byte array (the name, in + * criterion. Each entry is a {@code List} whose first entry is an + * {@code Integer} (the name type, 0-8) and whose second + * entry is a {@code String} or a byte array (the name, in * string or ASN.1 DER encoded form, respectively). - * There can be multiple names of the same type. If null + * There can be multiple names of the same type. If {@code null} * is supplied as the value for this argument, no * pathToNames check will be performed. *

    - * Each name in the Collection - * may be specified either as a String or as an ASN.1 encoded + * Each name in the {@code Collection} + * may be specified either as a {@code String} or as an ASN.1 encoded * byte array. For more details about the formats used, see * {@link #addPathToName(int type, String name) * addPathToName(int type, String name)} and @@ -1152,16 +1152,16 @@ public class X509CertSelector implements CertSelector { * array form instead of the String form. See the note in * {@link #addPathToName(int, String)} for more information. *

    - * Note that the names parameter can contain duplicate + * Note that the {@code names} parameter can contain duplicate * names (same name and name type), but they may be removed from the - * Collection of names returned by the + * {@code Collection} of names returned by the * {@link #getPathToNames getPathToNames} method. *

    - * Note that a deep copy is performed on the Collection to + * Note that a deep copy is performed on the {@code Collection} to * protect against subsequent modifications. * - * @param names a Collection with one entry per name - * (or null) + * @param names a {@code Collection} with one entry per name + * (or {@code null}) * @throws IOException if a parsing error occurs * @see #getPathToNames */ @@ -1186,12 +1186,12 @@ public class X509CertSelector implements CertSelector { } /** - * Adds a name to the pathToNames criterion. The X509Certificate + * Adds a name to the pathToNames criterion. The {@code X509Certificate} * must not include name constraints that would prohibit building a * path to the specified name. *

    * This method allows the caller to add a name to the set of names which - * the X509Certificates's name constraints must permit. + * the {@code X509Certificates}'s name constraints must permit. * The specified name is added to any previous value for the * pathToNames criterion. If the name is a duplicate, it may be ignored. *

    @@ -1223,12 +1223,12 @@ public class X509CertSelector implements CertSelector { } /** - * Adds a name to the pathToNames criterion. The X509Certificate + * Adds a name to the pathToNames criterion. The {@code X509Certificate} * must not include name constraints that would prohibit building a * path to the specified name. *

    * This method allows the caller to add a name to the set of names which - * the X509Certificates's name constraints must permit. + * the {@code X509Certificates}'s name constraints must permit. * The specified name is added to any previous value for the * pathToNames criterion. If the name is a duplicate, it may be ignored. *

    @@ -1254,7 +1254,7 @@ public class X509CertSelector implements CertSelector { /** * A private method that adds a name (String or byte array) to the - * pathToNames criterion. The X509Certificate must contain + * pathToNames criterion. The {@code X509Certificate} must contain * the specified pathToName. * * @param type the name type (0-8, as specified in @@ -1279,11 +1279,11 @@ public class X509CertSelector implements CertSelector { /** * Returns the certificateEquals criterion. The specified - * X509Certificate must be equal to the - * X509Certificate passed to the match method. - * If null, this check is not applied. + * {@code X509Certificate} must be equal to the + * {@code X509Certificate} passed to the {@code match} method. + * If {@code null}, this check is not applied. * - * @return the X509Certificate to match (or null) + * @return the {@code X509Certificate} to match (or {@code null}) * @see #setCertificate */ public X509Certificate getCertificate() { @@ -1293,11 +1293,11 @@ public class X509CertSelector implements CertSelector { /** * Returns the serialNumber criterion. The specified serial number * must match the certificate serial number in the - * X509Certificate. If null, any certificate + * {@code X509Certificate}. If {@code null}, any certificate * serial number will do. * * @return the certificate serial number to match - * (or null) + * (or {@code null}) * @see #setSerialNumber */ public BigInteger getSerialNumber() { @@ -1305,13 +1305,13 @@ public class X509CertSelector implements CertSelector { } /** - * Returns the issuer criterion as an X500Principal. This + * Returns the issuer criterion as an {@code X500Principal}. This * distinguished name must match the issuer distinguished name in the - * X509Certificate. If null, the issuer criterion + * {@code X509Certificate}. If {@code null}, the issuer criterion * is disabled and any issuer distinguished name will do. * * @return the required issuer distinguished name as X500Principal - * (or null) + * (or {@code null}) * @since 1.5 */ public X500Principal getIssuer() { @@ -1325,16 +1325,16 @@ public class X509CertSelector implements CertSelector { * encoding information in the RFC 2253 String form of some distinguished * names. *

    - * Returns the issuer criterion as a String. This + * Returns the issuer criterion as a {@code String}. This * distinguished name must match the issuer distinguished name in the - * X509Certificate. If null, the issuer criterion + * {@code X509Certificate}. If {@code null}, the issuer criterion * is disabled and any issuer distinguished name will do. *

    - * If the value returned is not null, it is a + * If the value returned is not {@code null}, it is a * distinguished name, in RFC 2253 format. * * @return the required issuer distinguished name in RFC 2253 format - * (or null) + * (or {@code null}) */ public String getIssuerAsString() { return (issuer == null ? null : issuer.getName()); @@ -1343,10 +1343,10 @@ public class X509CertSelector implements CertSelector { /** * Returns the issuer criterion as a byte array. This distinguished name * must match the issuer distinguished name in the - * X509Certificate. If null, the issuer criterion + * {@code X509Certificate}. If {@code null}, the issuer criterion * is disabled and any issuer distinguished name will do. *

    - * If the value returned is not null, it is a byte + * If the value returned is not {@code null}, it is a byte * array containing a single DER encoded distinguished name, as defined in * X.501. The ASN.1 notation for this structure is supplied in the * documentation for @@ -1356,7 +1356,7 @@ public class X509CertSelector implements CertSelector { * subsequent modifications. * * @return a byte array containing the required issuer distinguished name - * in ASN.1 DER format (or null) + * in ASN.1 DER format (or {@code null}) * @throws IOException if an encoding error occurs */ public byte[] getIssuerAsBytes() throws IOException { @@ -1364,13 +1364,13 @@ public class X509CertSelector implements CertSelector { } /** - * Returns the subject criterion as an X500Principal. This + * Returns the subject criterion as an {@code X500Principal}. This * distinguished name must match the subject distinguished name in the - * X509Certificate. If null, the subject criterion + * {@code X509Certificate}. If {@code null}, the subject criterion * is disabled and any subject distinguished name will do. * * @return the required subject distinguished name as X500Principal - * (or null) + * (or {@code null}) * @since 1.5 */ public X500Principal getSubject() { @@ -1384,16 +1384,16 @@ public class X509CertSelector implements CertSelector { * encoding information in the RFC 2253 String form of some distinguished * names. *

    - * Returns the subject criterion as a String. This + * Returns the subject criterion as a {@code String}. This * distinguished name must match the subject distinguished name in the - * X509Certificate. If null, the subject criterion + * {@code X509Certificate}. If {@code null}, the subject criterion * is disabled and any subject distinguished name will do. *

    - * If the value returned is not null, it is a + * If the value returned is not {@code null}, it is a * distinguished name, in RFC 2253 format. * * @return the required subject distinguished name in RFC 2253 format - * (or null) + * (or {@code null}) */ public String getSubjectAsString() { return (subject == null ? null : subject.getName()); @@ -1402,10 +1402,10 @@ public class X509CertSelector implements CertSelector { /** * Returns the subject criterion as a byte array. This distinguished name * must match the subject distinguished name in the - * X509Certificate. If null, the subject criterion + * {@code X509Certificate}. If {@code null}, the subject criterion * is disabled and any subject distinguished name will do. *

    - * If the value returned is not null, it is a byte + * If the value returned is not {@code null}, it is a byte * array containing a single DER encoded distinguished name, as defined in * X.501. The ASN.1 notation for this structure is supplied in the * documentation for @@ -1415,7 +1415,7 @@ public class X509CertSelector implements CertSelector { * subsequent modifications. * * @return a byte array containing the required subject distinguished name - * in ASN.1 DER format (or null) + * in ASN.1 DER format (or {@code null}) * @throws IOException if an encoding error occurs */ public byte[] getSubjectAsBytes() throws IOException { @@ -1424,14 +1424,14 @@ public class X509CertSelector implements CertSelector { /** * Returns the subjectKeyIdentifier criterion. The - * X509Certificate must contain a SubjectKeyIdentifier - * extension with the specified value. If null, no + * {@code X509Certificate} must contain a SubjectKeyIdentifier + * extension with the specified value. If {@code null}, no * subjectKeyIdentifier check will be done. *

    * Note that the byte array returned is cloned to protect against * subsequent modifications. * - * @return the key identifier (or null) + * @return the key identifier (or {@code null}) * @see #setSubjectKeyIdentifier */ public byte[] getSubjectKeyIdentifier() { @@ -1443,14 +1443,14 @@ public class X509CertSelector implements CertSelector { /** * Returns the authorityKeyIdentifier criterion. The - * X509Certificate must contain a AuthorityKeyIdentifier - * extension with the specified value. If null, no + * {@code X509Certificate} must contain a AuthorityKeyIdentifier + * extension with the specified value. If {@code null}, no * authorityKeyIdentifier check will be done. *

    * Note that the byte array returned is cloned to protect against * subsequent modifications. * - * @return the key identifier (or null) + * @return the key identifier (or {@code null}) * @see #setAuthorityKeyIdentifier */ public byte[] getAuthorityKeyIdentifier() { @@ -1463,13 +1463,13 @@ public class X509CertSelector implements CertSelector { /** * Returns the certificateValid criterion. The specified date must fall * within the certificate validity period for the - * X509Certificate. If null, no certificateValid + * {@code X509Certificate}. If {@code null}, no certificateValid * check will be done. *

    - * Note that the Date returned is cloned to protect against + * Note that the {@code Date} returned is cloned to protect against * subsequent modifications. * - * @return the Date to check (or null) + * @return the {@code Date} to check (or {@code null}) * @see #setCertificateValid */ public Date getCertificateValid() { @@ -1482,13 +1482,13 @@ public class X509CertSelector implements CertSelector { /** * Returns the privateKeyValid criterion. The specified date must fall * within the private key validity period for the - * X509Certificate. If null, no privateKeyValid + * {@code X509Certificate}. If {@code null}, no privateKeyValid * check will be done. *

    - * Note that the Date returned is cloned to protect against + * Note that the {@code Date} returned is cloned to protect against * subsequent modifications. * - * @return the Date to check (or null) + * @return the {@code Date} to check (or {@code null}) * @see #setPrivateKeyValid */ public Date getPrivateKeyValid() { @@ -1500,12 +1500,12 @@ public class X509CertSelector implements CertSelector { /** * Returns the subjectPublicKeyAlgID criterion. The - * X509Certificate must contain a subject public key - * with the specified algorithm. If null, no + * {@code X509Certificate} must contain a subject public key + * with the specified algorithm. If {@code null}, no * subjectPublicKeyAlgID check will be done. * * @return the object identifier (OID) of the signature algorithm to check - * for (or null). An OID is represented by a set of + * for (or {@code null}). An OID is represented by a set of * nonnegative integers separated by periods. * @see #setSubjectPublicKeyAlgID */ @@ -1518,10 +1518,10 @@ public class X509CertSelector implements CertSelector { /** * Returns the subjectPublicKey criterion. The - * X509Certificate must contain the specified subject - * public key. If null, no subjectPublicKey check will be done. + * {@code X509Certificate} must contain the specified subject + * public key. If {@code null}, no subjectPublicKey check will be done. * - * @return the subject public key to check for (or null) + * @return the subject public key to check for (or {@code null}) * @see #setSubjectPublicKey */ public PublicKey getSubjectPublicKey() { @@ -1529,7 +1529,7 @@ public class X509CertSelector implements CertSelector { } /** - * Returns the keyUsage criterion. The X509Certificate + * Returns the keyUsage criterion. The {@code X509Certificate} * must allow the specified keyUsage values. If null, no keyUsage * check will be done. *

    @@ -1539,7 +1539,7 @@ public class X509CertSelector implements CertSelector { * @return a boolean array in the same format as the boolean * array returned by * {@link X509Certificate#getKeyUsage() X509Certificate.getKeyUsage()}. - * Or null. + * Or {@code null}. * @see #setKeyUsage */ public boolean[] getKeyUsage() { @@ -1550,15 +1550,15 @@ public class X509CertSelector implements CertSelector { } /** - * Returns the extendedKeyUsage criterion. The X509Certificate + * Returns the extendedKeyUsage criterion. The {@code X509Certificate} * must allow the specified key purposes in its extended key usage - * extension. If the keyPurposeSet returned is empty or - * null, no extendedKeyUsage check will be done. Note that an - * X509Certificate that has no extendedKeyUsage extension + * extension. If the {@code keyPurposeSet} returned is empty or + * {@code null}, no extendedKeyUsage check will be done. Note that an + * {@code X509Certificate} that has no extendedKeyUsage extension * implicitly allows all key purposes. * - * @return an immutable Set of key purpose OIDs in string - * format (or null) + * @return an immutable {@code Set} of key purpose OIDs in string + * format (or {@code null}) * @see #setExtendedKeyUsage */ public Set getExtendedKeyUsage() { @@ -1566,19 +1566,19 @@ public class X509CertSelector implements CertSelector { } /** - * Indicates if the X509Certificate must contain all + * Indicates if the {@code X509Certificate} must contain all * or at least one of the subjectAlternativeNames * specified in the {@link #setSubjectAlternativeNames * setSubjectAlternativeNames} or {@link #addSubjectAlternativeName - * addSubjectAlternativeName} methods. If true, - * the X509Certificate must contain all of the - * specified subject alternative names. If false, the - * X509Certificate must contain at least one of the + * addSubjectAlternativeName} methods. If {@code true}, + * the {@code X509Certificate} must contain all of the + * specified subject alternative names. If {@code false}, the + * {@code X509Certificate} must contain at least one of the * specified subject alternative names. * - * @return true if the flag is enabled; - * false if the flag is disabled. The flag is - * true by default. + * @return {@code true} if the flag is enabled; + * {@code false} if the flag is disabled. The flag is + * {@code true} by default. * @see #setMatchAllSubjectAltNames */ public boolean getMatchAllSubjectAltNames() { @@ -1587,35 +1587,35 @@ public class X509CertSelector implements CertSelector { /** * Returns a copy of the subjectAlternativeNames criterion. - * The X509Certificate must contain all or at least one + * The {@code X509Certificate} must contain all or at least one * of the specified subjectAlternativeNames, depending on the value * of the matchAllNames flag (see {@link #getMatchAllSubjectAltNames * getMatchAllSubjectAltNames}). If the value returned is - * null, no subjectAlternativeNames check will be performed. + * {@code null}, no subjectAlternativeNames check will be performed. *

    - * If the value returned is not null, it is a - * Collection with + * If the value returned is not {@code null}, it is a + * {@code Collection} with * one entry for each name to be included in the subject alternative name - * criterion. Each entry is a List whose first entry is an - * Integer (the name type, 0-8) and whose second - * entry is a String or a byte array (the name, in + * criterion. Each entry is a {@code List} whose first entry is an + * {@code Integer} (the name type, 0-8) and whose second + * entry is a {@code String} or a byte array (the name, in * string or ASN.1 DER encoded form, respectively). * There can be multiple names of the same type. Note that the - * Collection returned may contain duplicate names (same name + * {@code Collection} returned may contain duplicate names (same name * and name type). *

    - * Each subject alternative name in the Collection - * may be specified either as a String or as an ASN.1 encoded + * Each subject alternative name in the {@code Collection} + * may be specified either as a {@code String} or as an ASN.1 encoded * byte array. For more details about the formats used, see * {@link #addSubjectAlternativeName(int type, String name) * addSubjectAlternativeName(int type, String name)} and * {@link #addSubjectAlternativeName(int type, byte [] name) * addSubjectAlternativeName(int type, byte [] name)}. *

    - * Note that a deep copy is performed on the Collection to + * Note that a deep copy is performed on the {@code Collection} to * protect against subsequent modifications. * - * @return a Collection of names (or null) + * @return a {@code Collection} of names (or {@code null}) * @see #setSubjectAlternativeNames */ public Collection> getSubjectAlternativeNames() { @@ -1628,21 +1628,21 @@ public class X509CertSelector implements CertSelector { /** * Clone an object of the form passed to * setSubjectAlternativeNames and setPathToNames. - * Throw a RuntimeException if the argument is malformed. + * Throw a {@code RuntimeException} if the argument is malformed. *

    * This method wraps cloneAndCheckNames, changing any - * IOException into a RuntimeException. This + * {@code IOException} into a {@code RuntimeException}. This * method should be used when the object being * cloned has already been checked, so there should never be any exceptions. * - * @param names a Collection with one entry per name. - * Each entry is a List whose first entry + * @param names a {@code Collection} with one entry per name. + * Each entry is a {@code List} whose first entry * is an Integer (the name type, 0-8) and whose second * entry is a String or a byte array (the name, in * string or ASN.1 DER encoded form, respectively). * There can be multiple names of the same type. Null * is not an acceptable value. - * @return a deep copy of the specified Collection + * @return a deep copy of the specified {@code Collection} * @throws RuntimeException if a parsing error occurs */ private static Set> cloneNames(Collection> names) { @@ -1657,16 +1657,16 @@ public class X509CertSelector implements CertSelector { /** * Clone and check an argument of the form passed to * setSubjectAlternativeNames and setPathToNames. - * Throw an IOException if the argument is malformed. + * Throw an {@code IOException} if the argument is malformed. * - * @param names a Collection with one entry per name. - * Each entry is a List whose first entry + * @param names a {@code Collection} with one entry per name. + * Each entry is a {@code List} whose first entry * is an Integer (the name type, 0-8) and whose second * entry is a String or a byte array (the name, in * string or ASN.1 DER encoded form, respectively). * There can be multiple names of the same type. - * null is not an acceptable value. - * @return a deep copy of the specified Collection + * {@code null} is not an acceptable value. + * @return a deep copy of the specified {@code Collection} * @throws IOException if a parsing error occurs */ private static Set> cloneAndCheckNames(Collection> names) throws IOException { @@ -1709,7 +1709,7 @@ public class X509CertSelector implements CertSelector { } /** - * Returns the name constraints criterion. The X509Certificate + * Returns the name constraints criterion. The {@code X509Certificate} * must have subject and subject alternative names that * meet the specified name constraints. *

    @@ -1725,7 +1725,7 @@ public class X509CertSelector implements CertSelector { * * @return a byte array containing the ASN.1 DER encoding of * a NameConstraints extension used for checking name constraints. - * null if no name constraints check will be performed. + * {@code null} if no name constraints check will be performed. * @see #setNameConstraints */ public byte[] getNameConstraints() { @@ -1738,7 +1738,7 @@ public class X509CertSelector implements CertSelector { /** * Returns the basic constraints constraint. If the value is greater than - * or equal to zero, the X509Certificates must include a + * or equal to zero, the {@code X509Certificates} must include a * basicConstraints extension with a pathLen of at least this value. * If the value is -2, only end-entity certificates are accepted. If * the value is -1, no basicConstraints check is done. @@ -1751,15 +1751,15 @@ public class X509CertSelector implements CertSelector { } /** - * Returns the policy criterion. The X509Certificate must + * Returns the policy criterion. The {@code X509Certificate} must * include at least one of the specified policies in its certificate policies - * extension. If the Set returned is empty, then the - * X509Certificate must include at least some specified policy - * in its certificate policies extension. If the Set returned is - * null, no policy check will be performed. + * extension. If the {@code Set} returned is empty, then the + * {@code X509Certificate} must include at least some specified policy + * in its certificate policies extension. If the {@code Set} returned is + * {@code null}, no policy check will be performed. * - * @return an immutable Set of certificate policy OIDs in - * string format (or null) + * @return an immutable {@code Set} of certificate policy OIDs in + * string format (or {@code null}) * @see #setPolicy */ public Set getPolicy() { @@ -1768,33 +1768,33 @@ public class X509CertSelector implements CertSelector { /** * Returns a copy of the pathToNames criterion. The - * X509Certificate must not include name constraints that would + * {@code X509Certificate} must not include name constraints that would * prohibit building a path to the specified names. If the value - * returned is null, no pathToNames check will be performed. + * returned is {@code null}, no pathToNames check will be performed. *

    - * If the value returned is not null, it is a - * Collection with one + * If the value returned is not {@code null}, it is a + * {@code Collection} with one * entry for each name to be included in the pathToNames - * criterion. Each entry is a List whose first entry is an - * Integer (the name type, 0-8) and whose second - * entry is a String or a byte array (the name, in + * criterion. Each entry is a {@code List} whose first entry is an + * {@code Integer} (the name type, 0-8) and whose second + * entry is a {@code String} or a byte array (the name, in * string or ASN.1 DER encoded form, respectively). * There can be multiple names of the same type. Note that the - * Collection returned may contain duplicate names (same + * {@code Collection} returned may contain duplicate names (same * name and name type). *

    - * Each name in the Collection - * may be specified either as a String or as an ASN.1 encoded + * Each name in the {@code Collection} + * may be specified either as a {@code String} or as an ASN.1 encoded * byte array. For more details about the formats used, see * {@link #addPathToName(int type, String name) * addPathToName(int type, String name)} and * {@link #addPathToName(int type, byte [] name) * addPathToName(int type, byte [] name)}. *

    - * Note that a deep copy is performed on the Collection to + * Note that a deep copy is performed on the {@code Collection} to * protect against subsequent modifications. * - * @return a Collection of names (or null) + * @return a {@code Collection} of names (or {@code null}) * @see #setPathToNames */ public Collection> getPathToNames() { @@ -1805,10 +1805,10 @@ public class X509CertSelector implements CertSelector { } /** - * Return a printable representation of the CertSelector. + * Return a printable representation of the {@code CertSelector}. * - * @return a String describing the contents of the - * CertSelector + * @return a {@code String} describing the contents of the + * {@code CertSelector} */ public String toString() { StringBuffer sb = new StringBuffer(); @@ -1927,22 +1927,22 @@ public class X509CertSelector implements CertSelector { /** * Returns an Extension object given any X509Certificate and extension oid. - * Throw an IOException if the extension byte value is + * Throw an {@code IOException} if the extension byte value is * malformed. * - * @param cert a X509Certificate - * @param extId an integer which specifies the extension index. + * @param cert a {@code X509Certificate} + * @param extId an {@code integer} which specifies the extension index. * Currently, the supported extensions are as follows: * index 0 - PrivateKeyUsageExtension * index 1 - SubjectAlternativeNameExtension * index 2 - NameConstraintsExtension * index 3 - CertificatePoliciesExtension * index 4 - ExtendedKeyUsageExtension - * @return an Extension object whose real type is as specified + * @return an {@code Extension} object whose real type is as specified * by the extension oid. - * @throws IOException if cannot construct the Extension + * @throws IOException if cannot construct the {@code Extension} * object with the extension encoding retrieved from the passed in - * X509Certificate. + * {@code X509Certificate}. */ private static Extension getExtensionObject(X509Certificate cert, int extId) throws IOException { @@ -1990,11 +1990,11 @@ public class X509CertSelector implements CertSelector { } /** - * Decides whether a Certificate should be selected. + * Decides whether a {@code Certificate} should be selected. * - * @param cert the Certificate to be checked - * @return true if the Certificate should be - * selected, false otherwise + * @param cert the {@code Certificate} to be checked + * @return {@code true} if the {@code Certificate} should be + * selected, {@code false} otherwise */ public boolean match(Certificate cert) { if (!(cert instanceof X509Certificate)) { diff --git a/src/share/classes/java/security/cert/X509Certificate.java b/src/share/classes/java/security/cert/X509Certificate.java index f257d028f7ba93b16f6f4cd54e22f1929eafb582..0aba5da60c0205f240ba6ab3de4c2de8c28ef9c4 100644 --- a/src/share/classes/java/security/cert/X509Certificate.java +++ b/src/share/classes/java/security/cert/X509Certificate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -66,7 +66,7 @@ import sun.security.x509.X509CertImpl; * RFC 3280: Internet X.509 * Public Key Infrastructure Certificate and CRL Profile. *

    - * The ASN.1 definition of tbsCertificate is: + * The ASN.1 definition of {@code tbsCertificate} is: *

      * TBSCertificate  ::=  SEQUENCE  {
      *     version         [0]  EXPLICIT Version DEFAULT v1,
    @@ -126,10 +126,12 @@ implements X509Extension {
          * is valid. It is defined in
          * ASN.1 as:
          * 
    -     * validity             Validity

    + * validity Validity + * * Validity ::= SEQUENCE { * notBefore CertificateValidityDate, - * notAfter CertificateValidityDate }

    + * notAfter CertificateValidityDate } + * * CertificateValidityDate ::= CHOICE { * utcTime UTCTime, * generalTime GeneralizedTime } @@ -151,9 +153,9 @@ implements X509Extension { * is valid at that date/time. * * @exception CertificateExpiredException if the certificate has expired - * with respect to the date supplied. + * with respect to the {@code date} supplied. * @exception CertificateNotYetValidException if the certificate is not - * yet valid with respect to the date supplied. + * yet valid with respect to the {@code date} supplied. * * @see #checkValidity() */ @@ -161,11 +163,12 @@ implements X509Extension { throws CertificateExpiredException, CertificateNotYetValidException; /** - * Gets the version (version number) value from the + * Gets the {@code version} (version number) value from the * certificate. * The ASN.1 definition for this is: *

    -     * version  [0] EXPLICIT Version DEFAULT v1

    + * version [0] EXPLICIT Version DEFAULT v1 + * * Version ::= INTEGER { v1(0), v2(1), v3(2) } *

    * @return the version number, i.e. 1, 2 or 3. @@ -173,14 +176,14 @@ implements X509Extension { public abstract int getVersion(); /** - * Gets the serialNumber value from the certificate. + * Gets the {@code serialNumber} value from the certificate. * The serial number is an integer assigned by the certification * authority to each certificate. It must be unique for each * certificate issued by a given CA (i.e., the issuer name and * serial number identify a unique certificate). * The ASN.1 definition for this is: *
    -     * serialNumber     CertificateSerialNumber

    + * serialNumber CertificateSerialNumber * * CertificateSerialNumber ::= INTEGER *

    @@ -191,12 +194,12 @@ implements X509Extension { /** * Denigrated, replaced by {@linkplain - * #getIssuerX500Principal()}. This method returns the issuer + * #getIssuerX500Principal()}. This method returns the {@code issuer} * as an implementation specific Principal object, which should not be * relied upon by portable code. * *

    - * Gets the issuer (issuer distinguished name) value from + * Gets the {@code issuer} (issuer distinguished name) value from * the certificate. The issuer name identifies the entity that signed (and * issued) the certificate. * @@ -204,7 +207,7 @@ implements X509Extension { * X.500 distinguished name (DN). * The ASN.1 definition for this is: *

    -     * issuer    Name

    + * issuer Name * * Name ::= CHOICE { RDNSequence } * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName @@ -217,14 +220,14 @@ implements X509Extension { * AttributeType ::= OBJECT IDENTIFIER * AttributeValue ::= ANY *

    - * The Name describes a hierarchical name composed of + * The {@code Name} describes a hierarchical name composed of * attributes, * such as country name, and corresponding values, such as US. - * The type of the AttributeValue component is determined by - * the AttributeType; in general it will be a - * directoryString. A directoryString is usually - * one of PrintableString, - * TeletexString or UniversalString. + * The type of the {@code AttributeValue} component is determined by + * the {@code AttributeType}; in general it will be a + * {@code directoryString}. A {@code directoryString} is usually + * one of {@code PrintableString}, + * {@code TeletexString} or {@code UniversalString}. * * @return a Principal whose name is the issuer distinguished name. */ @@ -232,11 +235,11 @@ implements X509Extension { /** * Returns the issuer (issuer distinguished name) value from the - * certificate as an X500Principal. + * certificate as an {@code X500Principal}. *

    * It is recommended that subclasses override this method. * - * @return an X500Principal representing the issuer + * @return an {@code X500Principal} representing the issuer * distinguished name * @since 1.4 */ @@ -249,22 +252,22 @@ implements X509Extension { /** * Denigrated, replaced by {@linkplain - * #getSubjectX500Principal()}. This method returns the subject + * #getSubjectX500Principal()}. This method returns the {@code subject} * as an implementation specific Principal object, which should not be * relied upon by portable code. * *

    - * Gets the subject (subject distinguished name) value - * from the certificate. If the subject value is empty, - * then the getName() method of the returned - * Principal object returns an empty string (""). + * Gets the {@code subject} (subject distinguished name) value + * from the certificate. If the {@code subject} value is empty, + * then the {@code getName()} method of the returned + * {@code Principal} object returns an empty string (""). * *

    The ASN.1 definition for this is: *

          * subject    Name
          * 
    * - *

    See {@link #getIssuerDN() getIssuerDN} for Name + *

    See {@link #getIssuerDN() getIssuerDN} for {@code Name} * and other relevant definitions. * * @return a Principal whose name is the subject name. @@ -273,13 +276,13 @@ implements X509Extension { /** * Returns the subject (subject distinguished name) value from the - * certificate as an X500Principal. If the subject value - * is empty, then the getName() method of the returned - * X500Principal object returns an empty string (""). + * certificate as an {@code X500Principal}. If the subject value + * is empty, then the {@code getName()} method of the returned + * {@code X500Principal} object returns an empty string (""). *

    * It is recommended that subclasses override this method. * - * @return an X500Principal representing the subject + * @return an {@code X500Principal} representing the subject * distinguished name * @since 1.4 */ @@ -291,15 +294,16 @@ implements X509Extension { } /** - * Gets the notBefore date from the validity period of + * Gets the {@code notBefore} date from the validity period of * the certificate. * The relevant ASN.1 definitions are: *

    -     * validity             Validity

    + * validity Validity * * Validity ::= SEQUENCE { * notBefore CertificateValidityDate, - * notAfter CertificateValidityDate }

    + * notAfter CertificateValidityDate } + * * CertificateValidityDate ::= CHOICE { * utcTime UTCTime, * generalTime GeneralizedTime } @@ -311,7 +315,7 @@ implements X509Extension { public abstract Date getNotBefore(); /** - * Gets the notAfter date from the validity period of + * Gets the {@code notAfter} date from the validity period of * the certificate. See {@link #getNotBefore() getNotBefore} * for relevant ASN.1 definitions. * @@ -322,7 +326,7 @@ implements X509Extension { /** * Gets the DER-encoded certificate information, the - * tbsCertificate from this certificate. + * {@code tbsCertificate} from this certificate. * This can be used to verify the signature independently. * * @return the DER-encoded certificate information. @@ -332,7 +336,7 @@ implements X509Extension { throws CertificateEncodingException; /** - * Gets the signature value (the raw signature bits) from + * Gets the {@code signature} value (the raw signature bits) from * the certificate. * The ASN.1 definition for this is: *

    @@ -348,7 +352,8 @@ implements X509Extension {
          * signature algorithm. An example is the string "SHA256withRSA".
          * The ASN.1 definition for this is:
          * 
    -     * signatureAlgorithm   AlgorithmIdentifier

    + * signatureAlgorithm AlgorithmIdentifier + * * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL } @@ -357,7 +362,7 @@ implements X509Extension { * -- algorithm object identifier value *

    * - *

    The algorithm name is determined from the algorithm + *

    The algorithm name is determined from the {@code algorithm} * OID string. * * @return the signature algorithm name. @@ -400,7 +405,7 @@ implements X509Extension { public abstract byte[] getSigAlgParams(); /** - * Gets the issuerUniqueID value from the certificate. + * Gets the {@code issuerUniqueID} value from the certificate. * The issuer unique identifier is present in the certificate * to handle the possibility of reuse of issuer names over time. * RFC 3280 recommends that names not be reused and that @@ -410,7 +415,8 @@ implements X509Extension { * *

    The ASN.1 definition for this is: *

    -     * issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL

    + * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL + * * UniqueIdentifier ::= BIT STRING *

    * @@ -420,11 +426,12 @@ implements X509Extension { public abstract boolean[] getIssuerUniqueID(); /** - * Gets the subjectUniqueID value from the certificate. + * Gets the {@code subjectUniqueID} value from the certificate. * *

    The ASN.1 definition for this is: *

    -     * subjectUniqueID  [2]  IMPLICIT UniqueIdentifier OPTIONAL

    + * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL + * * UniqueIdentifier ::= BIT STRING *

    * @@ -435,7 +442,7 @@ implements X509Extension { /** * Gets a boolean array representing bits of - * the KeyUsage extension, (OID = 2.5.29.15). + * the {@code KeyUsage} extension, (OID = 2.5.29.15). * The key usage extension defines the purpose (e.g., encipherment, * signature, certificate signing) of the key contained in the * certificate. @@ -467,16 +474,16 @@ implements X509Extension { /** * Gets an unmodifiable list of Strings representing the OBJECT - * IDENTIFIERs of the ExtKeyUsageSyntax field of the + * IDENTIFIERs of the {@code ExtKeyUsageSyntax} field of the * extended key usage extension, (OID = 2.5.29.37). It indicates * one or more purposes for which the certified public key may be * used, in addition to or in place of the basic purposes * indicated in the key usage extension field. The ASN.1 * definition for this is: *
    -     * ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId

    + * ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId * - * KeyPurposeId ::= OBJECT IDENTIFIER

    + * KeyPurposeId ::= OBJECT IDENTIFIER *

    * * Key purposes may be defined by any organization with a @@ -486,7 +493,7 @@ implements X509Extension { *

    * This method was added to version 1.4 of the Java 2 Platform Standard * Edition. In order to maintain backwards compatibility with existing - * service providers, this method is not abstract + * service providers, this method is not {@code abstract} * and it provides a default implementation. Subclasses * should override this method with a correct implementation. * @@ -503,13 +510,13 @@ implements X509Extension { /** * Gets the certificate constraints path length from the - * critical BasicConstraints extension, (OID = 2.5.29.19). + * critical {@code BasicConstraints} extension, (OID = 2.5.29.19). *

    * The basic constraints extension identifies whether the subject * of the certificate is a Certificate Authority (CA) and * how deep a certification path may exist through that CA. The - * pathLenConstraint field (see below) is meaningful - * only if cA is set to TRUE. In this case, it gives the + * {@code pathLenConstraint} field (see below) is meaningful + * only if {@code cA} is set to TRUE. In this case, it gives the * maximum number of CA certificates that may follow this certificate in a * certification path. A value of zero indicates that only an end-entity * certificate may follow in the path. @@ -521,21 +528,21 @@ implements X509Extension { * pathLenConstraint INTEGER (0..MAX) OPTIONAL } *

    * - * @return the value of pathLenConstraint if the + * @return the value of {@code pathLenConstraint} if the * BasicConstraints extension is present in the certificate and the * subject of the certificate is a CA, otherwise -1. * If the subject of the certificate is a CA and - * pathLenConstraint does not appear, - * Integer.MAX_VALUE is returned to indicate that there is no + * {@code pathLenConstraint} does not appear, + * {@code Integer.MAX_VALUE} is returned to indicate that there is no * limit to the allowed length of the certification path. */ public abstract int getBasicConstraints(); /** * Gets an immutable collection of subject alternative names from the - * SubjectAltName extension, (OID = 2.5.29.17). + * {@code SubjectAltName} extension, (OID = 2.5.29.17). *

    - * The ASN.1 definition of the SubjectAltName extension is: + * The ASN.1 definition of the {@code SubjectAltName} extension is: *

          * SubjectAltName ::= GeneralNames
          *
    @@ -553,23 +560,23 @@ implements X509Extension {
          *      registeredID                    [8]     OBJECT IDENTIFIER}
          * 
    *

    - * If this certificate does not contain a SubjectAltName - * extension, null is returned. Otherwise, a - * Collection is returned with an entry representing each - * GeneralName included in the extension. Each entry is a - * List whose first entry is an Integer - * (the name type, 0-8) and whose second entry is a String + * If this certificate does not contain a {@code SubjectAltName} + * extension, {@code null} is returned. Otherwise, a + * {@code Collection} is returned with an entry representing each + * {@code GeneralName} included in the extension. Each entry is a + * {@code List} whose first entry is an {@code Integer} + * (the name type, 0-8) and whose second entry is a {@code String} * or a byte array (the name, in string or ASN.1 DER encoded form, * respectively). *

    * RFC 822, DNS, and URI - * names are returned as Strings, + * names are returned as {@code String}s, * using the well-established string formats for those types (subject to * the restrictions included in RFC 3280). IPv4 address names are * returned using dotted quad notation. IPv6 address names are returned * in the form "a1:a2:...:a8", where a1-a8 are hexadecimal values * representing the eight 16-bit pieces of the address. OID names are - * returned as Strings represented as a series of nonnegative + * returned as {@code String}s represented as a series of nonnegative * integers separated by periods. And directory names (distinguished names) * are returned in * RFC 2253 string format. No standard string format is @@ -577,19 +584,19 @@ implements X509Extension { * other type of names. They are returned as byte arrays * containing the ASN.1 DER encoded form of the name. *

    - * Note that the Collection returned may contain more + * Note that the {@code Collection} returned may contain more * than one name of the same type. Also, note that the returned - * Collection is immutable and any entries containing byte + * {@code Collection} is immutable and any entries containing byte * arrays are cloned to protect against subsequent modifications. *

    * This method was added to version 1.4 of the Java 2 Platform Standard * Edition. In order to maintain backwards compatibility with existing - * service providers, this method is not abstract + * service providers, this method is not {@code abstract} * and it provides a default implementation. Subclasses * should override this method with a correct implementation. * - * @return an immutable Collection of subject alternative - * names (or null) + * @return an immutable {@code Collection} of subject alternative + * names (or {@code null}) * @throws CertificateParsingException if the extension cannot be decoded * @since 1.4 */ @@ -600,38 +607,38 @@ implements X509Extension { /** * Gets an immutable collection of issuer alternative names from the - * IssuerAltName extension, (OID = 2.5.29.18). + * {@code IssuerAltName} extension, (OID = 2.5.29.18). *

    - * The ASN.1 definition of the IssuerAltName extension is: + * The ASN.1 definition of the {@code IssuerAltName} extension is: *

          * IssuerAltName ::= GeneralNames
          * 
    - * The ASN.1 definition of GeneralNames is defined + * The ASN.1 definition of {@code GeneralNames} is defined * in {@link #getSubjectAlternativeNames getSubjectAlternativeNames}. *

    - * If this certificate does not contain an IssuerAltName - * extension, null is returned. Otherwise, a - * Collection is returned with an entry representing each - * GeneralName included in the extension. Each entry is a - * List whose first entry is an Integer - * (the name type, 0-8) and whose second entry is a String + * If this certificate does not contain an {@code IssuerAltName} + * extension, {@code null} is returned. Otherwise, a + * {@code Collection} is returned with an entry representing each + * {@code GeneralName} included in the extension. Each entry is a + * {@code List} whose first entry is an {@code Integer} + * (the name type, 0-8) and whose second entry is a {@code String} * or a byte array (the name, in string or ASN.1 DER encoded form, * respectively). For more details about the formats used for each - * name type, see the getSubjectAlternativeNames method. + * name type, see the {@code getSubjectAlternativeNames} method. *

    - * Note that the Collection returned may contain more + * Note that the {@code Collection} returned may contain more * than one name of the same type. Also, note that the returned - * Collection is immutable and any entries containing byte + * {@code Collection} is immutable and any entries containing byte * arrays are cloned to protect against subsequent modifications. *

    * This method was added to version 1.4 of the Java 2 Platform Standard * Edition. In order to maintain backwards compatibility with existing - * service providers, this method is not abstract + * service providers, this method is not {@code abstract} * and it provides a default implementation. Subclasses * should override this method with a correct implementation. * - * @return an immutable Collection of issuer alternative - * names (or null) + * @return an immutable {@code Collection} of issuer alternative + * names (or {@code null}) * @throws CertificateParsingException if the extension cannot be decoded * @since 1.4 */ @@ -649,7 +656,7 @@ implements X509Extension { * * This method was added to version 1.8 of the Java Platform Standard * Edition. In order to maintain backwards compatibility with existing - * service providers, this method is not abstract + * service providers, this method is not {@code abstract} * and it provides a default implementation. * * @param key the PublicKey used to carry out the verification. diff --git a/src/share/classes/java/security/cert/X509Extension.java b/src/share/classes/java/security/cert/X509Extension.java index ee63e6623479c2f81f9a312195630a4fea2a37ad..03469606eedb80bed04f7c42f2d3aed73b170ac0 100644 --- a/src/share/classes/java/security/cert/X509Extension.java +++ b/src/share/classes/java/security/cert/X509Extension.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -59,9 +59,9 @@ import java.util.Set; * -- the extnId object identifier value * } *

    - * Since not all extensions are known, the getExtensionValue + * Since not all extensions are known, the {@code getExtensionValue} * method returns the DER-encoded OCTET STRING of the - * extension value (i.e., the extnValue). This can then + * extension value (i.e., the {@code extnValue}). This can then * be handled by a Class that understands the extension. * * @author Hemma Prafullchandra @@ -72,8 +72,8 @@ public interface X509Extension { /** * Check if there is a critical extension that is not supported. * - * @return true if a critical extension is found that is - * not supported, otherwise false. + * @return {@code true} if a critical extension is found that is + * not supported, otherwise {@code false}. */ public boolean hasUnsupportedCriticalExtension(); @@ -113,28 +113,28 @@ public interface X509Extension { * * Here is sample code to get a Set of non-critical extensions from an * X509CRL revoked certificate entry and print the OIDs: - *
    
    +     * 
    {@code
          * CertificateFactory cf = null;
          * X509CRL crl = null;
          * try (InputStream inStrm = new FileInputStream("DER-encoded-CRL")) {
          *     cf = CertificateFactory.getInstance("X.509");
          *     crl = (X509CRL)cf.generateCRL(inStrm);
    -     * }

    + * } * - * byte[] certData = <DER-encoded certificate data> + * byte[] certData = * ByteArrayInputStream bais = new ByteArrayInputStream(certData); * X509Certificate cert = (X509Certificate)cf.generateCertificate(bais); * X509CRLEntry badCert = - * crl.getRevokedCertificate(cert.getSerialNumber());

    + * crl.getRevokedCertificate(cert.getSerialNumber()); * * if (badCert != null) { - * Set nonCritSet = badCert.getNonCriticalExtensionOIDs();

    + * Set nonCritSet = badCert.getNonCriticalExtensionOIDs(); * if (nonCritSet != null) * for (String oid : nonCritSet) { * System.out.println(oid); * } * } - *

    + * }
    * * @return a Set (or an empty Set if none are marked non-critical) of * the extension OID strings for extensions that are marked non-critical. @@ -145,9 +145,9 @@ public interface X509Extension { /** * Gets the DER-encoded OCTET string for the extension value - * (extnValue) identified by the passed-in oid + * (extnValue) identified by the passed-in {@code oid} * String. - * The oid string is + * The {@code oid} string is * represented by a set of nonnegative whole numbers separated * by periods. * diff --git a/src/share/classes/java/security/cert/package-info.java b/src/share/classes/java/security/cert/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..58f5fb77e0a6203f8689a05404707ced087a7313 --- /dev/null +++ b/src/share/classes/java/security/cert/package-info.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Provides classes and interfaces for parsing and managing + * certificates, certificate revocation lists (CRLs), and + * certification paths. It contains support for X.509 v3 + * certificates and X.509 v2 CRLs. + * + *

    Package Specification

    + * + * + * + *

    Related Documentation

    + * + * For information about X.509 certificates and CRLs, please see: + * + * + * @since 1.2 + */ +package java.security.cert; diff --git a/src/share/classes/java/security/cert/package.html b/src/share/classes/java/security/cert/package.html deleted file mode 100644 index 239f7ffe1dc82474f3bf382369c99de7d859319d..0000000000000000000000000000000000000000 --- a/src/share/classes/java/security/cert/package.html +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - -Provides classes and interfaces for parsing and managing -certificates, certificate revocation lists (CRLs), and -certification paths. It contains support for X.509 v3 -certificates and X.509 v2 CRLs. - -

    Package Specification

    - - - -

    Related Documentation

    - -For information about X.509 certificates and CRLs, please see: - - -@since 1.2 - - diff --git a/src/share/classes/java/security/interfaces/DSAKeyPairGenerator.java b/src/share/classes/java/security/interfaces/DSAKeyPairGenerator.java index 96a091ef84a8d46e7a6ae06d47bf3cafe1cff399..390835725b90ece49c1c5c3346e16fd9a068218f 100644 --- a/src/share/classes/java/security/interfaces/DSAKeyPairGenerator.java +++ b/src/share/classes/java/security/interfaces/DSAKeyPairGenerator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,8 +30,8 @@ import java.security.*; /** * An interface to an object capable of generating DSA key pairs. * - *

    The initialize methods may each be called any number - * of times. If no initialize method is called on a + *

    The {@code initialize} methods may each be called any number + * of times. If no {@code initialize} method is called on a * DSAKeyPairGenerator, the default is to generate 1024-bit keys, using * precomputed p, q and g parameters and an instance of SecureRandom as * the random bit source. @@ -42,22 +42,22 @@ import java.security.*; *

      * *
    1. Get a key pair generator for the DSA algorithm by calling the - * KeyPairGenerator getInstance method with "DSA" + * KeyPairGenerator {@code getInstance} method with "DSA" * as its argument.

      * *

    2. Initialize the generator by casting the result to a DSAKeyPairGenerator * and calling one of the - * initialize methods from this DSAKeyPairGenerator interface.

      + * {@code initialize} methods from this DSAKeyPairGenerator interface.

      * - *

    3. Generate a key pair by calling the generateKeyPair + *
    4. Generate a key pair by calling the {@code generateKeyPair} * method from the KeyPairGenerator class. * *
    * *

    Note: it is not always necessary to do do algorithm-specific * initialization for a DSA key pair generator. That is, it is not always - * necessary to call an initialize method in this interface. - * Algorithm-independent initialization using the initialize method + * necessary to call an {@code initialize} method in this interface. + * Algorithm-independent initialization using the {@code initialize} method * in the KeyPairGenerator * interface is all that is needed when you accept defaults for algorithm-specific * parameters. @@ -80,7 +80,7 @@ public interface DSAKeyPairGenerator { * @param random the random bit source to use to generate key bits; * can be null. * - * @exception InvalidParameterException if the params + * @exception InvalidParameterException if the {@code params} * value is invalid, null, or unsupported. */ public void initialize(DSAParams params, SecureRandom random) @@ -92,7 +92,7 @@ public interface DSAKeyPairGenerator { * If a SecureRandom bit source is needed but not supplied, i.e. * null, a default SecureRandom instance will be used. * - *

    If genParams is true, this method generates new + *

    If {@code genParams} is true, this method generates new * p, q and g parameters. If it is false, the method uses precomputed * parameters for the modulus length requested. If there are no * precomputed parameters for that modulus length, an exception will be @@ -108,8 +108,8 @@ public interface DSAKeyPairGenerator { * @param genParams whether or not to generate new parameters for * the modulus length requested. * - * @exception InvalidParameterException if modlen is - * invalid, or unsupported, or if genParams is false and there + * @exception InvalidParameterException if {@code modlen} is + * invalid, or unsupported, or if {@code genParams} is false and there * are no precomputed parameters for the requested modulus length. */ public void initialize(int modlen, boolean genParams, SecureRandom random) diff --git a/src/share/classes/java/security/interfaces/DSAParams.java b/src/share/classes/java/security/interfaces/DSAParams.java index f20b8ec386b2e0d26b71986b24ed2023a8ddb24e..8c46ed57e276321fc10827cf056b052f1fb0bf71 100644 --- a/src/share/classes/java/security/interfaces/DSAParams.java +++ b/src/share/classes/java/security/interfaces/DSAParams.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,23 +42,23 @@ import java.math.BigInteger; public interface DSAParams { /** - * Returns the prime, p. + * Returns the prime, {@code p}. * - * @return the prime, p. + * @return the prime, {@code p}. */ public BigInteger getP(); /** - * Returns the subprime, q. + * Returns the subprime, {@code q}. * - * @return the subprime, q. + * @return the subprime, {@code q}. */ public BigInteger getQ(); /** - * Returns the base, g. + * Returns the base, {@code g}. * - * @return the base, g. + * @return the base, {@code g}. */ public BigInteger getG(); } diff --git a/src/share/classes/java/security/interfaces/DSAPrivateKey.java b/src/share/classes/java/security/interfaces/DSAPrivateKey.java index a0d189372e6ec91d4c04f6e7e1cd45239464eed4..81ab3586f699131fbf8ba90aac04dabe568099f4 100644 --- a/src/share/classes/java/security/interfaces/DSAPrivateKey.java +++ b/src/share/classes/java/security/interfaces/DSAPrivateKey.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -50,9 +50,9 @@ public interface DSAPrivateKey extends DSAKey, java.security.PrivateKey { static final long serialVersionUID = 7776497482533790279L; /** - * Returns the value of the private key, x. + * Returns the value of the private key, {@code x}. * - * @return the value of the private key, x. + * @return the value of the private key, {@code x}. */ public BigInteger getX(); } diff --git a/src/share/classes/java/security/interfaces/DSAPublicKey.java b/src/share/classes/java/security/interfaces/DSAPublicKey.java index b27373880e683e30fb1e9cbe0cace4fade7721d5..e56b795ae70a87f90700e5279d638a3bd1c9d7df 100644 --- a/src/share/classes/java/security/interfaces/DSAPublicKey.java +++ b/src/share/classes/java/security/interfaces/DSAPublicKey.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -50,9 +50,9 @@ public interface DSAPublicKey extends DSAKey, java.security.PublicKey { static final long serialVersionUID = 1234526332779022332L; /** - * Returns the value of the public key, y. + * Returns the value of the public key, {@code y}. * - * @return the value of the public key, y. + * @return the value of the public key, {@code y}. */ public BigInteger getY(); } diff --git a/src/share/classes/java/security/interfaces/package-info.java b/src/share/classes/java/security/interfaces/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..54c9397e6914efe2caa711190762d67e5cc9a2d9 --- /dev/null +++ b/src/share/classes/java/security/interfaces/package-info.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Provides interfaces for generating RSA (Rivest, Shamir and + * Adleman AsymmetricCipher algorithm) + * keys as defined in the RSA Laboratory Technical Note + * PKCS#1, and DSA (Digital Signature + * Algorithm) keys as defined in NIST's FIPS-186. + *

    + * Note that these interfaces are intended only for key + * implementations whose key material is accessible and + * available. These interfaces are not intended for key + * implementations whose key material resides in + * inaccessible, protected storage (such as in a + * hardware device). + *

    + * For more developer information on how to use these + * interfaces, including information on how to design + * {@code Key} classes for hardware devices, please refer + * to these cryptographic provider developer guides: + *

    + * + *

    Package Specification

    + * + *
      + *
    • PKCS #1: RSA Encryption Standard, Version 1.5, November 1993
    • + *
    • Federal Information Processing Standards Publication (FIPS PUB) 186: + * Digital Signature Standard (DSS)
    • + *
    + * + *

    Related Documentation

    + * + * For further documentation, please see: + * + * + * @since JDK1.1 + */ +package java.security.interfaces; diff --git a/src/share/classes/java/security/interfaces/package.html b/src/share/classes/java/security/interfaces/package.html deleted file mode 100644 index 70820dd70a57adaf4633d48521073a45867a38cc..0000000000000000000000000000000000000000 --- a/src/share/classes/java/security/interfaces/package.html +++ /dev/null @@ -1,77 +0,0 @@ - - - - - - -Provides interfaces for generating RSA (Rivest, Shamir and -Adleman AsymmetricCipher algorithm) -keys as defined in the RSA Laboratory Technical Note -PKCS#1, and DSA (Digital Signature -Algorithm) keys as defined in NIST's FIPS-186. -

    -Note that these interfaces are intended only for key -implementations whose key material is accessible and -available. These interfaces are not intended for key -implementations whose key material resides in -inaccessible, protected storage (such as in a -hardware device). -

    -For more developer information on how to use these -interfaces, including information on how to design -Key classes for hardware devices, please refer -to these cryptographic provider developer guides: -

    - -

    Package Specification

    - -
      -
    • PKCS #1: RSA Encryption Standard, Version 1.5, November 1993
    • -
    • Federal Information Processing Standards Publication (FIPS PUB) 186: - Digital Signature Standard (DSS)
    • -
    - -

    Related Documentation

    - -For further documentation, please see: - - -@since JDK1.1 - - diff --git a/src/share/classes/java/security/package-info.java b/src/share/classes/java/security/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..599e95259badf4e4294a4917e9943d00c64f5d73 --- /dev/null +++ b/src/share/classes/java/security/package-info.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Provides the classes and interfaces for the security framework. + * This includes classes that implement an easily configurable, + * fine-grained access control security architecture. + * This package also supports + * the generation and storage of cryptographic public key pairs, + * as well as a number of exportable cryptographic operations + * including those for message digest and signature generation. Finally, + * this package provides classes that support signed/guarded objects + * and secure random number generation. + * + * Many of the classes provided in this package (the cryptographic + * and secure random number generator classes in particular) are + * provider-based. The class itself defines a programming interface + * to which applications may write. The implementations themselves may + * then be written by independent third-party vendors and plugged + * in seamlessly as needed. Therefore application developers may + * take advantage of any number of provider-based implementations + * without having to add or rewrite code. + * + *

    Package Specification

    + * + * + * + *

    Related Documentation

    + * + * For further documentation, please see: + * + * + * @since 1.1 + */ +package java.security; diff --git a/src/share/classes/java/security/package.html b/src/share/classes/java/security/package.html deleted file mode 100644 index 65eb70c71af7b5e58c69dfed2eef3986420e3094..0000000000000000000000000000000000000000 --- a/src/share/classes/java/security/package.html +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - -Provides the classes and interfaces for the security framework. -This includes classes that implement an easily configurable, -fine-grained access control security architecture. -This package also supports -the generation and storage of cryptographic public key pairs, -as well as a number of exportable cryptographic operations -including those for message digest and signature generation. Finally, -this package provides classes that support signed/guarded objects -and secure random number generation. - -Many of the classes provided in this package (the cryptographic -and secure random number generator classes in particular) are -provider-based. The class itself defines a programming interface -to which applications may write. The implementations themselves may -then be written by independent third-party vendors and plugged -in seamlessly as needed. Therefore application developers may -take advantage of any number of provider-based implementations -without having to add or rewrite code. - -

    Package Specification

    - - - -

    Related Documentation

    - -For further documentation, please see: - - -@since 1.1 - - diff --git a/src/share/classes/java/security/spec/DSAGenParameterSpec.java b/src/share/classes/java/security/spec/DSAGenParameterSpec.java index a354c4807acfee0fcbb4461e69cd524cb32be5ed..932a9f05ccd801b97e77915417755087d882581e 100644 --- a/src/share/classes/java/security/spec/DSAGenParameterSpec.java +++ b/src/share/classes/java/security/spec/DSAGenParameterSpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,13 +41,13 @@ public final class DSAGenParameterSpec implements AlgorithmParameterSpec { /** * Creates a domain parameter specification for DSA parameter - * generation using primePLen and subprimeQLen. - * The value of subprimeQLen is also used as the default + * generation using {@code primePLen} and {@code subprimeQLen}. + * The value of {@code subprimeQLen} is also used as the default * length of the domain parameter seed in bits. * @param primePLen the desired length of the prime P in bits. * @param subprimeQLen the desired length of the sub-prime Q in bits. - * @exception IllegalArgumentException if primePLen - * or subprimeQLen is illegal per the specification of + * @exception IllegalArgumentException if {@code primePLen} + * or {@code subprimeQLen} is illegal per the specification of * FIPS 186-3. */ public DSAGenParameterSpec(int primePLen, int subprimeQLen) { @@ -56,14 +56,14 @@ public final class DSAGenParameterSpec implements AlgorithmParameterSpec { /** * Creates a domain parameter specification for DSA parameter - * generation using primePLen, subprimeQLen, - * and seedLen. + * generation using {@code primePLen}, {@code subprimeQLen}, + * and {@code seedLen}. * @param primePLen the desired length of the prime P in bits. * @param subprimeQLen the desired length of the sub-prime Q in bits. * @param seedLen the desired length of the domain parameter seed in bits, - * shall be equal to or greater than subprimeQLen. - * @exception IllegalArgumentException if primePLenLen, - * subprimeQLen, or seedLen is illegal per the + * shall be equal to or greater than {@code subprimeQLen}. + * @exception IllegalArgumentException if {@code primePLenLen}, + * {@code subprimeQLen}, or {@code seedLen} is illegal per the * specification of FIPS 186-3. */ public DSAGenParameterSpec(int primePLen, int subprimeQLen, int seedLen) { diff --git a/src/share/classes/java/security/spec/DSAParameterSpec.java b/src/share/classes/java/security/spec/DSAParameterSpec.java index 2c9c546669d9007bd400cb1f7d853931502ab668..eed6bdcae8b97219cd062582eebc3b372a796d7f 100644 --- a/src/share/classes/java/security/spec/DSAParameterSpec.java +++ b/src/share/classes/java/security/spec/DSAParameterSpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -61,27 +61,27 @@ java.security.interfaces.DSAParams { } /** - * Returns the prime p. + * Returns the prime {@code p}. * - * @return the prime p. + * @return the prime {@code p}. */ public BigInteger getP() { return this.p; } /** - * Returns the sub-prime q. + * Returns the sub-prime {@code q}. * - * @return the sub-prime q. + * @return the sub-prime {@code q}. */ public BigInteger getQ() { return this.q; } /** - * Returns the base g. + * Returns the base {@code g}. * - * @return the base g. + * @return the base {@code g}. */ public BigInteger getG() { return this.g; diff --git a/src/share/classes/java/security/spec/DSAPrivateKeySpec.java b/src/share/classes/java/security/spec/DSAPrivateKeySpec.java index 44d6859fd6ccb8bc7640e0aeb2c64549fbcb22f6..a004de75db3b3dc7a766ca879289fe7e875176d1 100644 --- a/src/share/classes/java/security/spec/DSAPrivateKeySpec.java +++ b/src/share/classes/java/security/spec/DSAPrivateKeySpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -69,36 +69,36 @@ public class DSAPrivateKeySpec implements KeySpec { } /** - * Returns the private key x. + * Returns the private key {@code x}. * - * @return the private key x. + * @return the private key {@code x}. */ public BigInteger getX() { return this.x; } /** - * Returns the prime p. + * Returns the prime {@code p}. * - * @return the prime p. + * @return the prime {@code p}. */ public BigInteger getP() { return this.p; } /** - * Returns the sub-prime q. + * Returns the sub-prime {@code q}. * - * @return the sub-prime q. + * @return the sub-prime {@code q}. */ public BigInteger getQ() { return this.q; } /** - * Returns the base g. + * Returns the base {@code g}. * - * @return the base g. + * @return the base {@code g}. */ public BigInteger getG() { return this.g; diff --git a/src/share/classes/java/security/spec/DSAPublicKeySpec.java b/src/share/classes/java/security/spec/DSAPublicKeySpec.java index 2dfc73842986d2e887b23f1c0d6761685b0845da..a56e6f9c08efcc95371e1c380ce5e80477199f83 100644 --- a/src/share/classes/java/security/spec/DSAPublicKeySpec.java +++ b/src/share/classes/java/security/spec/DSAPublicKeySpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -69,36 +69,36 @@ public class DSAPublicKeySpec implements KeySpec { } /** - * Returns the public key y. + * Returns the public key {@code y}. * - * @return the public key y. + * @return the public key {@code y}. */ public BigInteger getY() { return this.y; } /** - * Returns the prime p. + * Returns the prime {@code p}. * - * @return the prime p. + * @return the prime {@code p}. */ public BigInteger getP() { return this.p; } /** - * Returns the sub-prime q. + * Returns the sub-prime {@code q}. * - * @return the sub-prime q. + * @return the sub-prime {@code q}. */ public BigInteger getQ() { return this.q; } /** - * Returns the base g. + * Returns the base {@code g}. * - * @return the base g. + * @return the base {@code g}. */ public BigInteger getG() { return this.g; diff --git a/src/share/classes/java/security/spec/ECFieldF2m.java b/src/share/classes/java/security/spec/ECFieldF2m.java index f271ccbd35024897a4e5a1158a597697ae5829bd..58843ab67da59192e3f1ab23c49aeb3345faaebf 100644 --- a/src/share/classes/java/security/spec/ECFieldF2m.java +++ b/src/share/classes/java/security/spec/ECFieldF2m.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -45,9 +45,9 @@ public class ECFieldF2m implements ECField { /** * Creates an elliptic curve characteristic 2 finite - * field which has 2^m elements with normal basis. - * @param m with 2^m being the number of elements. - * @exception IllegalArgumentException if m + * field which has 2^{@code m} elements with normal basis. + * @param m with 2^{@code m} being the number of elements. + * @exception IllegalArgumentException if {@code m} * is not positive. */ public ECFieldF2m(int m) { @@ -61,24 +61,24 @@ public class ECFieldF2m implements ECField { /** * Creates an elliptic curve characteristic 2 finite - * field which has 2^m elements with + * field which has 2^{@code m} elements with * polynomial basis. * The reduction polynomial for this field is based - * on rp whose i-th bit correspondes to + * on {@code rp} whose i-th bit correspondes to * the i-th coefficient of the reduction polynomial.

    * Note: A valid reduction polynomial is either a - * trinomial (X^m + X^k + 1 - * with m > k >= 1) or a - * pentanomial (X^m + X^k3 - * + X^k2 + X^k1 + 1 with - * m > k3 > k2 - * > k1 >= 1). - * @param m with 2^m being the number of elements. + * trinomial (X^{@code m} + X^{@code k} + 1 + * with {@code m} > {@code k} >= 1) or a + * pentanomial (X^{@code m} + X^{@code k3} + * + X^{@code k2} + X^{@code k1} + 1 with + * {@code m} > {@code k3} > {@code k2} + * > {@code k1} >= 1). + * @param m with 2^{@code m} being the number of elements. * @param rp the BigInteger whose i-th bit corresponds to * the i-th coefficient of the reduction polynomial. - * @exception NullPointerException if rp is null. - * @exception IllegalArgumentException if m - * is not positive, or rp does not represent + * @exception NullPointerException if {@code rp} is null. + * @exception IllegalArgumentException if {@code m} + * is not positive, or {@code rp} does not represent * a valid reduction polynomial. */ public ECFieldF2m(int m, BigInteger rp) { @@ -106,28 +106,28 @@ public class ECFieldF2m implements ECField { /** * Creates an elliptic curve characteristic 2 finite - * field which has 2^m elements with + * field which has 2^{@code m} elements with * polynomial basis. The reduction polynomial for this - * field is based on ks whose content + * field is based on {@code ks} whose content * contains the order of the middle term(s) of the * reduction polynomial. * Note: A valid reduction polynomial is either a - * trinomial (X^m + X^k + 1 - * with m > k >= 1) or a - * pentanomial (X^m + X^k3 - * + X^k2 + X^k1 + 1 with - * m > k3 > k2 - * > k1 >= 1), so ks should + * trinomial (X^{@code m} + X^{@code k} + 1 + * with {@code m} > {@code k} >= 1) or a + * pentanomial (X^{@code m} + X^{@code k3} + * + X^{@code k2} + X^{@code k1} + 1 with + * {@code m} > {@code k3} > {@code k2} + * > {@code k1} >= 1), so {@code ks} should * have length 1 or 3. - * @param m with 2^m being the number of elements. + * @param m with 2^{@code m} being the number of elements. * @param ks the order of the middle term(s) of the * reduction polynomial. Contents of this array are copied * to protect against subsequent modification. - * @exception NullPointerException if ks is null. - * @exception IllegalArgumentException ifm - * is not positive, or the length of ks - * is neither 1 nor 3, or values in ks - * are not between m-1 and 1 (inclusive) + * @exception NullPointerException if {@code ks} is null. + * @exception IllegalArgumentException if{@code m} + * is not positive, or the length of {@code ks} + * is neither 1 nor 3, or values in {@code ks} + * are not between {@code m}-1 and 1 (inclusive) * and in descending order. */ public ECFieldF2m(int m, int[] ks) { @@ -160,7 +160,7 @@ public class ECFieldF2m implements ECField { } /** - * Returns the field size in bits which is m + * Returns the field size in bits which is {@code m} * for this characteristic 2 finite field. * @return the field size in bits. */ @@ -169,9 +169,9 @@ public class ECFieldF2m implements ECField { } /** - * Returns the value m of this characteristic + * Returns the value {@code m} of this characteristic * 2 finite field. - * @return m with 2^m being the + * @return {@code m} with 2^{@code m} being the * number of elements. */ public int getM() { @@ -211,8 +211,8 @@ public class ECFieldF2m implements ECField { * Compares this finite field for equality with the * specified object. * @param obj the object to be compared. - * @return true if obj is an instance - * of ECFieldF2m and both m and the reduction + * @return true if {@code obj} is an instance + * of ECFieldF2m and both {@code m} and the reduction * polynomial match, false otherwise. */ public boolean equals(Object obj) { diff --git a/src/share/classes/java/security/spec/ECFieldFp.java b/src/share/classes/java/security/spec/ECFieldFp.java index 183549981db3f1c1d997599db8047e9aa8c7aeb9..c578962d3c2b248f994c1777976d0f6b15b0b1c4 100644 --- a/src/share/classes/java/security/spec/ECFieldFp.java +++ b/src/share/classes/java/security/spec/ECFieldFp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,10 +43,10 @@ public class ECFieldFp implements ECField { /** * Creates an elliptic curve prime finite field - * with the specified prime p. + * with the specified prime {@code p}. * @param p the prime. - * @exception NullPointerException if p is null. - * @exception IllegalArgumentException if p + * @exception NullPointerException if {@code p} is null. + * @exception IllegalArgumentException if {@code p} * is not positive. */ public ECFieldFp(BigInteger p) { @@ -66,7 +66,7 @@ public class ECFieldFp implements ECField { }; /** - * Returns the prime p of this prime finite field. + * Returns the prime {@code p} of this prime finite field. * @return the prime. */ public BigInteger getP() { @@ -77,7 +77,7 @@ public class ECFieldFp implements ECField { * Compares this prime finite field for equality with the * specified object. * @param obj the object to be compared. - * @return true if obj is an instance + * @return true if {@code obj} is an instance * of ECFieldFp and the prime value match, false otherwise. */ public boolean equals(Object obj) { diff --git a/src/share/classes/java/security/spec/ECGenParameterSpec.java b/src/share/classes/java/security/spec/ECGenParameterSpec.java index da1694541b50a4a0e219dda31486218d8f83a2df..4f3f63b873a3b518f38f5f3dfce6fe943352b0be 100644 --- a/src/share/classes/java/security/spec/ECGenParameterSpec.java +++ b/src/share/classes/java/security/spec/ECGenParameterSpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,13 +41,13 @@ public class ECGenParameterSpec implements AlgorithmParameterSpec { /** * Creates a parameter specification for EC parameter * generation using a standard (or predefined) name - * stdName in order to generate the corresponding + * {@code stdName} in order to generate the corresponding * (precomputed) elliptic curve domain parameters. For the * list of supported names, please consult the documentation * of provider whose implementation will be used. * @param stdName the standard name of the to-be-generated EC * domain parameters. - * @exception NullPointerException if stdName + * @exception NullPointerException if {@code stdName} * is null. */ public ECGenParameterSpec(String stdName) { diff --git a/src/share/classes/java/security/spec/ECParameterSpec.java b/src/share/classes/java/security/spec/ECParameterSpec.java index 8837516e3bf44fbb3cc35d360c83d57f0f0c425a..3f7cae3b82b703c1523c095f7cb8db880dbd2f35 100644 --- a/src/share/classes/java/security/spec/ECParameterSpec.java +++ b/src/share/classes/java/security/spec/ECParameterSpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -49,12 +49,12 @@ public class ECParameterSpec implements AlgorithmParameterSpec { * @param curve the elliptic curve which this parameter * defines. * @param g the generator which is also known as the base point. - * @param n the order of the generator g. + * @param n the order of the generator {@code g}. * @param h the cofactor. - * @exception NullPointerException if curve, - * g, or n is null. - * @exception IllegalArgumentException if n - * or h is not positive. + * @exception NullPointerException if {@code curve}, + * {@code g}, or {@code n} is null. + * @exception IllegalArgumentException if {@code n} + * or {@code h} is not positive. */ public ECParameterSpec(EllipticCurve curve, ECPoint g, BigInteger n, int h) { diff --git a/src/share/classes/java/security/spec/ECPoint.java b/src/share/classes/java/security/spec/ECPoint.java index 0c2ce57d96c147622b92da4eb550d69609ac1bc6..1b051c71a136131496cf9140cebf8667ec4a3c0e 100644 --- a/src/share/classes/java/security/spec/ECPoint.java +++ b/src/share/classes/java/security/spec/ECPoint.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -54,11 +54,11 @@ public class ECPoint { /** * Creates an ECPoint from the specified affine x-coordinate - * x and affine y-coordinate y. + * {@code x} and affine y-coordinate {@code y}. * @param x the affine x-coordinate. * @param y the affine y-coordinate. - * @exception NullPointerException if x or - * y is null. + * @exception NullPointerException if {@code x} or + * {@code y} is null. */ public ECPoint(BigInteger x, BigInteger y) { if ((x==null) || (y==null)) { @@ -69,7 +69,7 @@ public class ECPoint { } /** - * Returns the affine x-coordinate x. + * Returns the affine x-coordinate {@code x}. * Note: POINT_INFINITY has a null affine x-coordinate. * @return the affine x-coordinate. */ @@ -78,7 +78,7 @@ public class ECPoint { } /** - * Returns the affine y-coordinate y. + * Returns the affine y-coordinate {@code y}. * Note: POINT_INFINITY has a null affine y-coordinate. * @return the affine y-coordinate. */ @@ -90,7 +90,7 @@ public class ECPoint { * Compares this elliptic curve point for equality with * the specified object. * @param obj the object to be compared. - * @return true if obj is an instance of + * @return true if {@code obj} is an instance of * ECPoint and the affine coordinates match, false otherwise. */ public boolean equals(Object obj) { diff --git a/src/share/classes/java/security/spec/ECPrivateKeySpec.java b/src/share/classes/java/security/spec/ECPrivateKeySpec.java index c8e2c408a86e4e09caa6ee09472264b45248cc0a..7f03cfd49e6fa995a7ee70cd0b0c100550bda8b7 100644 --- a/src/share/classes/java/security/spec/ECPrivateKeySpec.java +++ b/src/share/classes/java/security/spec/ECPrivateKeySpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -48,8 +48,8 @@ public class ECPrivateKeySpec implements KeySpec { * @param s the private value. * @param params the associated elliptic curve domain * parameters. - * @exception NullPointerException if s - * or params is null. + * @exception NullPointerException if {@code s} + * or {@code params} is null. */ public ECPrivateKeySpec(BigInteger s, ECParameterSpec params) { if (s == null) { diff --git a/src/share/classes/java/security/spec/ECPublicKeySpec.java b/src/share/classes/java/security/spec/ECPublicKeySpec.java index 2d8b510ecbdcbcac8b220b8351ced4b98fd873f0..e0cfb777c50604e58fb5a3a449e8f6997414767a 100644 --- a/src/share/classes/java/security/spec/ECPublicKeySpec.java +++ b/src/share/classes/java/security/spec/ECPublicKeySpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,9 +47,9 @@ public class ECPublicKeySpec implements KeySpec { * @param w the public point. * @param params the associated elliptic curve domain * parameters. - * @exception NullPointerException if w - * or params is null. - * @exception IllegalArgumentException if w + * @exception NullPointerException if {@code w} + * or {@code params} is null. + * @exception IllegalArgumentException if {@code w} * is point at infinity, i.e. ECPoint.POINT_INFINITY */ public ECPublicKeySpec(ECPoint w, ECParameterSpec params) { diff --git a/src/share/classes/java/security/spec/EllipticCurve.java b/src/share/classes/java/security/spec/EllipticCurve.java index d9eef25caf8fdf9740bd7fe60332043b7ba26b68..8ec97b05ed37e68b5e1498b0b4f74508b746c0c2 100644 --- a/src/share/classes/java/security/spec/EllipticCurve.java +++ b/src/share/classes/java/security/spec/EllipticCurve.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -68,15 +68,15 @@ public class EllipticCurve { /** * Creates an elliptic curve with the specified elliptic field - * field and the coefficients a and - * b. + * {@code field} and the coefficients {@code a} and + * {@code b}. * @param field the finite field that this elliptic curve is over. * @param a the first coefficient of this elliptic curve. * @param b the second coefficient of this elliptic curve. - * @exception NullPointerException if field, - * a, or b is null. - * @exception IllegalArgumentException if a - * or b is not null and not in field. + * @exception NullPointerException if {@code field}, + * {@code a}, or {@code b} is null. + * @exception IllegalArgumentException if {@code a} + * or {@code b} is not null and not in {@code field}. */ public EllipticCurve(ECField field, BigInteger a, BigInteger b) { @@ -85,18 +85,18 @@ public class EllipticCurve { /** * Creates an elliptic curve with the specified elliptic field - * field, the coefficients a and - * b, and the seed used for curve generation. + * {@code field}, the coefficients {@code a} and + * {@code b}, and the {@code seed} used for curve generation. * @param field the finite field that this elliptic curve is over. * @param a the first coefficient of this elliptic curve. * @param b the second coefficient of this elliptic curve. * @param seed the bytes used during curve generation for later * validation. Contents of this array are copied to protect against * subsequent modification. - * @exception NullPointerException if field, - * a, or b is null. - * @exception IllegalArgumentException if a - * or b is not null and not in field. + * @exception NullPointerException if {@code field}, + * {@code a}, or {@code b} is null. + * @exception IllegalArgumentException if {@code a} + * or {@code b} is not null and not in {@code field}. */ public EllipticCurve(ECField field, BigInteger a, BigInteger b, byte[] seed) { @@ -122,9 +122,9 @@ public class EllipticCurve { } /** - * Returns the finite field field that this + * Returns the finite field {@code field} that this * elliptic curve is over. - * @return the field field that this curve + * @return the field {@code field} that this curve * is over. */ public ECField getField() { @@ -132,27 +132,27 @@ public class EllipticCurve { } /** - * Returns the first coefficient a of the + * Returns the first coefficient {@code a} of the * elliptic curve. - * @return the first coefficient a. + * @return the first coefficient {@code a}. */ public BigInteger getA() { return a; } /** - * Returns the second coefficient b of the + * Returns the second coefficient {@code b} of the * elliptic curve. - * @return the second coefficient b. + * @return the second coefficient {@code b}. */ public BigInteger getB() { return b; } /** - * Returns the seeding bytes seed used + * Returns the seeding bytes {@code seed} used * during curve generation. May be null if not specified. - * @return the seeding bytes seed. A new + * @return the seeding bytes {@code seed}. A new * array is returned each time this method is called. */ public byte[] getSeed() { @@ -164,7 +164,7 @@ public class EllipticCurve { * Compares this elliptic curve for equality with the * specified object. * @param obj the object to be compared. - * @return true if obj is an instance of + * @return true if {@code obj} is an instance of * EllipticCurve and the field, A, and B match, false otherwise. */ public boolean equals(Object obj) { diff --git a/src/share/classes/java/security/spec/EncodedKeySpec.java b/src/share/classes/java/security/spec/EncodedKeySpec.java index b58781921d21b1262b3f5ae40b744211917db0f9..cc3b81e6ab3a2cedf7bb6b24c08784cb2fcdf92c 100644 --- a/src/share/classes/java/security/spec/EncodedKeySpec.java +++ b/src/share/classes/java/security/spec/EncodedKeySpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -49,7 +49,7 @@ public abstract class EncodedKeySpec implements KeySpec { * * @param encodedKey the encoded key. The contents of the * array are copied to protect against subsequent modification. - * @exception NullPointerException if encodedKey + * @exception NullPointerException if {@code encodedKey} * is null. */ public EncodedKeySpec(byte[] encodedKey) { @@ -74,9 +74,9 @@ public abstract class EncodedKeySpec implements KeySpec { * (see {@link java.security.Key Key}) can be transformed * (see {@link java.security.KeyFactory KeyFactory}) * into this key specification (or a subclass of it), - * getFormat called + * {@code getFormat} called * on the opaque key returns the same value as the - * getFormat method + * {@code getFormat} method * of this key specification. * * @return a string representation of the encoding format. diff --git a/src/share/classes/java/security/spec/InvalidKeySpecException.java b/src/share/classes/java/security/spec/InvalidKeySpecException.java index 670913d1366effaeec35814bfe836d864a93b5e7..4655c4abe0c60eec70daa072e1bf5a037e721542 100644 --- a/src/share/classes/java/security/spec/InvalidKeySpecException.java +++ b/src/share/classes/java/security/spec/InvalidKeySpecException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -63,13 +63,13 @@ public class InvalidKeySpecException extends GeneralSecurityException { } /** - * Creates a InvalidKeySpecException with the specified + * Creates a {@code InvalidKeySpecException} with the specified * detail message and cause. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, + * {@link #getCause()} method). (A {@code null} value is permitted, * and indicates that the cause is nonexistent or unknown.) * @since 1.5 */ @@ -78,13 +78,13 @@ public class InvalidKeySpecException extends GeneralSecurityException { } /** - * Creates a InvalidKeySpecException with the specified cause - * and a detail message of (cause==null ? null : cause.toString()) + * Creates a {@code InvalidKeySpecException} with the specified cause + * and a detail message of {@code (cause==null ? null : cause.toString())} * (which typically contains the class and detail message of - * cause). + * {@code cause}). * * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, + * {@link #getCause()} method). (A {@code null} value is permitted, * and indicates that the cause is nonexistent or unknown.) * @since 1.5 */ diff --git a/src/share/classes/java/security/spec/KeySpec.java b/src/share/classes/java/security/spec/KeySpec.java index 26c9777ef07859c3a60733cb3444ee1c68911178..34fec5d3125bcbf4af9b1466c4eeb13cec6e67aa 100644 --- a/src/share/classes/java/security/spec/KeySpec.java +++ b/src/share/classes/java/security/spec/KeySpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,7 +36,7 @@ package java.security.spec; *

    A key may be specified in an algorithm-specific way, or in an * algorithm-independent encoding format (such as ASN.1). * For example, a DSA private key may be specified by its components - * x, p, q, and g + * {@code x}, {@code p}, {@code q}, and {@code g} * (see {@link DSAPrivateKeySpec}), or it may be * specified using its DER encoding * (see {@link PKCS8EncodedKeySpec}). diff --git a/src/share/classes/java/security/spec/MGF1ParameterSpec.java b/src/share/classes/java/security/spec/MGF1ParameterSpec.java index c1f1de37130a4aff27bfaf66d762cc06ece9b613..1be267f0ced658ad4f1f1d134345e37e6629df2b 100644 --- a/src/share/classes/java/security/spec/MGF1ParameterSpec.java +++ b/src/share/classes/java/security/spec/MGF1ParameterSpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -92,7 +92,7 @@ public class MGF1ParameterSpec implements AlgorithmParameterSpec { * * @param mdName the algorithm name for the message digest * used in this mask generation function MGF1. - * @exception NullPointerException if mdName is null. + * @exception NullPointerException if {@code mdName} is null. */ public MGF1ParameterSpec(String mdName) { if (mdName == null) { diff --git a/src/share/classes/java/security/spec/PKCS8EncodedKeySpec.java b/src/share/classes/java/security/spec/PKCS8EncodedKeySpec.java index b6dabad364be2b203a25e33a13e86e2df6d785d3..060f266fcb1bb6efe9d29a46d98381e2e67c0beb 100644 --- a/src/share/classes/java/security/spec/PKCS8EncodedKeySpec.java +++ b/src/share/classes/java/security/spec/PKCS8EncodedKeySpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,8 +27,8 @@ package java.security.spec; /** * This class represents the ASN.1 encoding of a private key, - * encoded according to the ASN.1 type PrivateKeyInfo. - * The PrivateKeyInfo syntax is defined in the PKCS#8 standard + * encoded according to the ASN.1 type {@code PrivateKeyInfo}. + * The {@code PrivateKeyInfo} syntax is defined in the PKCS#8 standard * as follows: * *

    @@ -67,7 +67,7 @@ public class PKCS8EncodedKeySpec extends EncodedKeySpec {
          * @param encodedKey the key, which is assumed to be
          * encoded according to the PKCS #8 standard. The contents of
          * the array are copied to protect against subsequent modification.
    -     * @exception NullPointerException if encodedKey
    +     * @exception NullPointerException if {@code encodedKey}
          * is null.
          */
         public PKCS8EncodedKeySpec(byte[] encodedKey) {
    @@ -88,7 +88,7 @@ public class PKCS8EncodedKeySpec extends EncodedKeySpec {
          * Returns the name of the encoding format associated with this
          * key specification.
          *
    -     * @return the string "PKCS#8".
    +     * @return the string {@code "PKCS#8"}.
          */
         public final String getFormat() {
             return "PKCS#8";
    diff --git a/src/share/classes/java/security/spec/PSSParameterSpec.java b/src/share/classes/java/security/spec/PSSParameterSpec.java
    index 37a2eeb26255c9ef38ccb7a31c1b14343f0a1ca3..a9b82d8e42b5cb2c129817749bb236804cc5cc59 100644
    --- a/src/share/classes/java/security/spec/PSSParameterSpec.java
    +++ b/src/share/classes/java/security/spec/PSSParameterSpec.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -91,14 +91,14 @@ public class PSSParameterSpec implements AlgorithmParameterSpec {
         public static final PSSParameterSpec DEFAULT = new PSSParameterSpec();
     
         /**
    -     * Constructs a new PSSParameterSpec as defined in
    +     * Constructs a new {@code PSSParameterSpec} as defined in
          * the PKCS #1 standard using the default values.
          */
         private PSSParameterSpec() {
         }
     
         /**
    -     * Creates a new PSSParameterSpec as defined in
    +     * Creates a new {@code PSSParameterSpec} as defined in
          * the PKCS #1 standard using the specified message digest,
          * mask generation function, parameters for mask generation
          * function, salt length, and trailer field values.
    @@ -111,10 +111,10 @@ public class PSSParameterSpec implements AlgorithmParameterSpec {
          * getMGFParameters().
          * @param saltLen the length of salt.
          * @param trailerField the value of the trailer field.
    -     * @exception NullPointerException if mdName,
    -     * or mgfName is null.
    -     * @exception IllegalArgumentException if saltLen
    -     * or trailerField is less than 0.
    +     * @exception NullPointerException if {@code mdName},
    +     * or {@code mgfName} is null.
    +     * @exception IllegalArgumentException if {@code saltLen}
    +     * or {@code trailerField} is less than 0.
          * @since 1.5
          */
         public PSSParameterSpec(String mdName, String mgfName,
    @@ -143,13 +143,13 @@ public class PSSParameterSpec implements AlgorithmParameterSpec {
         }
     
         /**
    -     * Creates a new PSSParameterSpec
    +     * Creates a new {@code PSSParameterSpec}
          * using the specified salt length and other default values as
          * defined in PKCS#1.
          *
          * @param saltLen the length of salt in bits to be used in PKCS#1
          * PSS encoding.
    -     * @exception IllegalArgumentException if saltLen is
    +     * @exception IllegalArgumentException if {@code saltLen} is
          * less than 0.
          */
         public PSSParameterSpec(int saltLen) {
    diff --git a/src/share/classes/java/security/spec/RSAKeyGenParameterSpec.java b/src/share/classes/java/security/spec/RSAKeyGenParameterSpec.java
    index e9a10fa58a8c2bae44fd1f3c708aade4d63f5d39..a73c6cd46b71b75a62d1494f7c13277d78432020 100644
    --- a/src/share/classes/java/security/spec/RSAKeyGenParameterSpec.java
    +++ b/src/share/classes/java/security/spec/RSAKeyGenParameterSpec.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -55,7 +55,7 @@ public class RSAKeyGenParameterSpec implements AlgorithmParameterSpec {
         public static final BigInteger F4 = BigInteger.valueOf(65537);
     
         /**
    -     * Constructs a new RSAParameterSpec object from the
    +     * Constructs a new {@code RSAParameterSpec} object from the
          * given keysize and public-exponent value.
          *
          * @param keysize the modulus size (specified in number of bits)
    diff --git a/src/share/classes/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java b/src/share/classes/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java
    index 97346d6e22a4477602916420d811304d21f3f133..a198e43a2e1947733a3019c9b3c1b3d533c54df9 100644
    --- a/src/share/classes/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java
    +++ b/src/share/classes/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2001, 2003, Oracle and/or its affiliates. All rights reserved.
    + * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
      * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      *
      * This code is free software; you can redistribute it and/or modify it
    @@ -57,12 +57,12 @@ public class RSAMultiPrimePrivateCrtKeySpec extends RSAPrivateKeySpec {
         private final RSAOtherPrimeInfo otherPrimeInfo[];
     
        /**
    -    * Creates a new RSAMultiPrimePrivateCrtKeySpec
    +    * Creates a new {@code RSAMultiPrimePrivateCrtKeySpec}
         * given the modulus, publicExponent, privateExponent,
         * primeP, primeQ, primeExponentP, primeExponentQ,
         * crtCoefficient, and otherPrimeInfo as defined in PKCS#1 v2.1.
         *
    -    * 

    Note that the contents of otherPrimeInfo + *

    Note that the contents of {@code otherPrimeInfo} * are copied to protect against subsequent modification when * constructing this object. * @@ -78,13 +78,13 @@ public class RSAMultiPrimePrivateCrtKeySpec extends RSAPrivateKeySpec { * @param otherPrimeInfo triplets of the rest of primes, null can be * specified if there are only two prime factors (p and q). * @exception NullPointerException if any of the parameters, i.e. - * modulus, - * publicExponent, privateExponent, - * primeP, primeQ, - * primeExponentP, primeExponentQ, - * crtCoefficient, is null. + * {@code modulus}, + * {@code publicExponent}, {@code privateExponent}, + * {@code primeP}, {@code primeQ}, + * {@code primeExponentP}, {@code primeExponentQ}, + * {@code crtCoefficient}, is null. * @exception IllegalArgumentException if an empty, i.e. 0-length, - * otherPrimeInfo is specified. + * {@code otherPrimeInfo} is specified. */ public RSAMultiPrimePrivateCrtKeySpec(BigInteger modulus, BigInteger publicExponent, diff --git a/src/share/classes/java/security/spec/RSAOtherPrimeInfo.java b/src/share/classes/java/security/spec/RSAOtherPrimeInfo.java index e0889152dcd0c632b8ad0d23c086bab72b777d52..10d8471765dc331b13e349bf6ddd6561ae45ee94 100644 --- a/src/share/classes/java/security/spec/RSAOtherPrimeInfo.java +++ b/src/share/classes/java/security/spec/RSAOtherPrimeInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,7 +58,7 @@ public class RSAOtherPrimeInfo { /** - * Creates a new RSAOtherPrimeInfo + * Creates a new {@code RSAOtherPrimeInfo} * given the prime, primeExponent, and * crtCoefficient as defined in PKCS#1. * @@ -67,8 +67,8 @@ public class RSAOtherPrimeInfo { * @param crtCoefficient the Chinese Remainder Theorem * coefficient. * @exception NullPointerException if any of the parameters, i.e. - * prime, primeExponent, - * crtCoefficient, is null. + * {@code prime}, {@code primeExponent}, + * {@code crtCoefficient}, is null. * */ public RSAOtherPrimeInfo(BigInteger prime, diff --git a/src/share/classes/java/security/spec/RSAPrivateCrtKeySpec.java b/src/share/classes/java/security/spec/RSAPrivateCrtKeySpec.java index c8d8faa5e531eed05c6ce61669de2088aa7f436e..d0ba70be44308d6bb67631990f5527aba36cb247 100644 --- a/src/share/classes/java/security/spec/RSAPrivateCrtKeySpec.java +++ b/src/share/classes/java/security/spec/RSAPrivateCrtKeySpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,7 +55,7 @@ public class RSAPrivateCrtKeySpec extends RSAPrivateKeySpec { /** - * Creates a new RSAPrivateCrtKeySpec + * Creates a new {@code RSAPrivateCrtKeySpec} * given the modulus, publicExponent, privateExponent, * primeP, primeQ, primeExponentP, primeExponentQ, and * crtCoefficient as defined in PKCS#1. diff --git a/src/share/classes/java/security/spec/X509EncodedKeySpec.java b/src/share/classes/java/security/spec/X509EncodedKeySpec.java index 7dd3d7bf244ad38c9f3dd7027761d426fa42d016..b9984de87e39b22a6ce45955d7d3e91e0fbbfb24 100644 --- a/src/share/classes/java/security/spec/X509EncodedKeySpec.java +++ b/src/share/classes/java/security/spec/X509EncodedKeySpec.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,8 +27,8 @@ package java.security.spec; /** * This class represents the ASN.1 encoding of a public key, - * encoded according to the ASN.1 type SubjectPublicKeyInfo. - * The SubjectPublicKeyInfo syntax is defined in the X.509 + * encoded according to the ASN.1 type {@code SubjectPublicKeyInfo}. + * The {@code SubjectPublicKeyInfo} syntax is defined in the X.509 * standard as follows: * *

    @@ -57,7 +57,7 @@ public class X509EncodedKeySpec extends EncodedKeySpec {
          * @param encodedKey the key, which is assumed to be
          * encoded according to the X.509 standard. The contents of the
          * array are copied to protect against subsequent modification.
    -     * @exception NullPointerException if encodedKey
    +     * @exception NullPointerException if {@code encodedKey}
          * is null.
          */
         public X509EncodedKeySpec(byte[] encodedKey) {
    @@ -78,7 +78,7 @@ public class X509EncodedKeySpec extends EncodedKeySpec {
          * Returns the name of the encoding format associated with this
          * key specification.
          *
    -     * @return the string "X.509".
    +     * @return the string {@code "X.509"}.
          */
         public final String getFormat() {
             return "X.509";
    diff --git a/src/share/classes/java/security/spec/package-info.java b/src/share/classes/java/security/spec/package-info.java
    new file mode 100644
    index 0000000000000000000000000000000000000000..cb393088e5b5727eb4dcfa7244b3cc9c5506d6f7
    --- /dev/null
    +++ b/src/share/classes/java/security/spec/package-info.java
    @@ -0,0 +1,73 @@
    +/*
    + * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
    + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    + *
    + * This code is free software; you can redistribute it and/or modify it
    + * under the terms of the GNU General Public License version 2 only, as
    + * published by the Free Software Foundation.  Oracle designates this
    + * particular file as subject to the "Classpath" exception as provided
    + * by Oracle in the LICENSE file that accompanied this code.
    + *
    + * This code is distributed in the hope that it will be useful, but WITHOUT
    + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    + * version 2 for more details (a copy is included in the LICENSE file that
    + * accompanied this code).
    + *
    + * You should have received a copy of the GNU General Public License version
    + * 2 along with this work; if not, write to the Free Software Foundation,
    + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    + *
    + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    + * or visit www.oracle.com if you need additional information or have any
    + * questions.
    + */
    +
    +/**
    + * Provides classes and interfaces for key specifications and algorithm
    + * parameter specifications.
    + *
    + * 

    A key specification is a transparent representation of the key material + * that constitutes a key. A key may be specified in an algorithm-specific + * way, or in an algorithm-independent encoding format (such as ASN.1). + * This package contains key specifications for DSA public and private keys, + * RSA public and private keys, PKCS #8 private keys in DER-encoded format, + * and X.509 public and private keys in DER-encoded format. + * + *

    An algorithm parameter specification is a transparent representation + * of the sets of parameters used with an algorithm. This package contains + * an algorithm parameter specification for parameters used with the + * DSA algorithm. + * + *

    Package Specification

    + * + *
      + *
    • PKCS #1: RSA Encryption Standard, Version 1.5, November 1993
    • + *
    • PKCS #8: Private-Key Information Syntax Standard, + * Version 1.2, November 1993
    • + *
    • Federal Information Processing Standards Publication (FIPS PUB) 186: + * Digital Signature Standard (DSS)
    • + *
    + * + *

    Related Documentation

    + * + * For documentation that includes information about algorithm parameter + * and key specifications, please see: + * + * + * @since 1.2 + */ +package java.security.spec; diff --git a/src/share/classes/java/security/spec/package.html b/src/share/classes/java/security/spec/package.html deleted file mode 100644 index 54558ae198aadc817bc565bcf277f02def1842c6..0000000000000000000000000000000000000000 --- a/src/share/classes/java/security/spec/package.html +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - - - -Provides classes and interfaces for key specifications and algorithm -parameter specifications. - -

    A key specification is a transparent representation of the key material -that constitutes a key. A key may be specified in an algorithm-specific -way, or in an algorithm-independent encoding format (such as ASN.1). -This package contains key specifications for DSA public and private keys, -RSA public and private keys, PKCS #8 private keys in DER-encoded format, -and X.509 public and private keys in DER-encoded format. - -

    An algorithm parameter specification is a transparent representation -of the sets of parameters used with an algorithm. This package contains -an algorithm parameter specification for parameters used with the -DSA algorithm. - -

    Package Specification

    - -
      -
    • PKCS #1: RSA Encryption Standard, Version 1.5, November 1993
    • -
    • PKCS #8: Private-Key Information Syntax Standard, - Version 1.2, November 1993
    • -
    • Federal Information Processing Standards Publication (FIPS PUB) 186: - Digital Signature Standard (DSS)
    • -
    - -

    Related Documentation

    - -For documentation that includes information about algorithm parameter -and key specifications, please see: - - -@since 1.2 - - diff --git a/src/share/classes/java/sql/Blob.java b/src/share/classes/java/sql/Blob.java index 46b7c2f20139fd86043fc15fced07850ac42c42d..90bb251c07b8a6afa20e18040b387528b966f1bd 100644 --- a/src/share/classes/java/sql/Blob.java +++ b/src/share/classes/java/sql/Blob.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,7 +29,7 @@ import java.io.InputStream; /** * The representation (mapping) in - * the JavaTM programming + * the Java™ programming * language of an SQL * BLOB value. An SQL BLOB is a built-in type * that stores a Binary Large Object as a column value in a row of diff --git a/src/share/classes/java/sql/CallableStatement.java b/src/share/classes/java/sql/CallableStatement.java index a39af405220850be577583e8974a038d18ceee95..dc98859bf8bd22b91e0595f8becfb1a3b3a4cb19 100644 --- a/src/share/classes/java/sql/CallableStatement.java +++ b/src/share/classes/java/sql/CallableStatement.java @@ -2445,6 +2445,7 @@ public interface CallableStatement extends PreparedStatement { * @param parameterIndex the first parameter is 1, the second is 2, and so on * @param type Class representing the Java data type to convert the * designated parameter to. + * @param the type of the class modeled by this Class object * @return an instance of {@code type} holding the OUT parameter value * @throws SQLException if conversion is not supported, type is null or * another error occurs. The getCause() method of the @@ -2473,6 +2474,7 @@ public interface CallableStatement extends PreparedStatement { * @param parameterName the name of the parameter * @param type Class representing the Java data type to convert * the designated parameter to. + * @param the type of the class modeled by this Class object * @return an instance of {@code type} holding the OUT parameter * value * @throws SQLException if conversion is not supported, type is null or diff --git a/src/share/classes/java/sql/Clob.java b/src/share/classes/java/sql/Clob.java index 868c862a0131db0a4a1fe3aa1f5e2cfe7a02c4c7..8ffc38af75437476f112bf38156c218f8ed06969 100644 --- a/src/share/classes/java/sql/Clob.java +++ b/src/share/classes/java/sql/Clob.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,7 +28,7 @@ package java.sql; import java.io.Reader; /** - * The mapping in the JavaTM programming language + * The mapping in the Java™ programming language * for the SQL CLOB type. * An SQL CLOB is a built-in type * that stores a Character Large Object as a column value in a row of diff --git a/src/share/classes/java/sql/DatabaseMetaData.java b/src/share/classes/java/sql/DatabaseMetaData.java index 035365512b7b7924455a993a36d80ef4403760ac..63c6f131c4f06185753d75a4391d1f37bd714b4f 100644 --- a/src/share/classes/java/sql/DatabaseMetaData.java +++ b/src/share/classes/java/sql/DatabaseMetaData.java @@ -31,7 +31,7 @@ package java.sql; *

    * This interface is implemented by driver vendors to let users know the capabilities * of a Database Management System (DBMS) in combination with - * the driver based on JDBCTM technology + * the driver based on JDBC™ technology * ("JDBC driver") that is used with it. Different relational DBMSs often support * different features, implement features in different ways, and use different * data types. In addition, a driver may implement a feature on top of what the @@ -3074,7 +3074,7 @@ public interface DatabaseMetaData extends Wrapper { * * @param holdability one of the following constants: * ResultSet.HOLD_CURSORS_OVER_COMMIT or - * ResultSet.CLOSE_CURSORS_AT_COMMIT + * ResultSet.CLOSE_CURSORS_AT_COMMIT * @return true if so; false otherwise * @exception SQLException if a database access error occurs * @see Connection diff --git a/src/share/classes/java/sql/Driver.java b/src/share/classes/java/sql/Driver.java index 27ad3e0407ddbfdbd38accd94ae87f42ca580566..3bb3e0c4576dc6d4d4ee21e4c819f17c6d5d313e 100644 --- a/src/share/classes/java/sql/Driver.java +++ b/src/share/classes/java/sql/Driver.java @@ -144,7 +144,7 @@ public interface Driver { /** * Reports whether this driver is a genuine JDBC - * CompliantTM driver. + * Compliant™ driver. * A driver may only report true here if it passes the JDBC * compliance tests; otherwise it is required to return false. *

    @@ -173,7 +173,8 @@ public interface Driver { * In the worst case, this may be the root Logger. * * @return the parent Logger for this driver - * @throws SQLFeatureNotSupportedException if the driver does not use java.util.logging. + * @throws SQLFeatureNotSupportedException if the driver does not use + * {@code java.util.logging}. * @since 1.7 */ public Logger getParentLogger() throws SQLFeatureNotSupportedException; diff --git a/src/share/classes/java/sql/DriverAction.java b/src/share/classes/java/sql/DriverAction.java index 167168c9b85acbb3763f5eeed91f6bf129ff5755..59d98259620171c0129758bd43b0e89bccf32f75 100644 --- a/src/share/classes/java/sql/DriverAction.java +++ b/src/share/classes/java/sql/DriverAction.java @@ -33,7 +33,7 @@ package java.sql; * directly by applications. A JDBC Driver may choose * to create its {@code DriverAction} implementation in a private class * to avoid it being called directly. - * + *

    * The JDBC driver's static initialization block must call * {@linkplain DriverManager#registerDriver(java.sql.Driver, java.sql.DriverAction) } in order * to inform {@code DriverManager} which {@code DriverAction} implementation to diff --git a/src/share/classes/java/sql/NClob.java b/src/share/classes/java/sql/NClob.java index a70ed6190a6e06712eedf97ace76924b368897eb..f3d535c0afd7bdc67fe37770249a081b3106fb49 100644 --- a/src/share/classes/java/sql/NClob.java +++ b/src/share/classes/java/sql/NClob.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,7 +28,7 @@ package java.sql; import java.sql.Clob; /** - * The mapping in the JavaTM programming language + * The mapping in the Java™ programming language * for the SQL NCLOB type. * An SQL NCLOB is a built-in type * that stores a Character Large Object using the National Character Set diff --git a/src/share/classes/java/sql/ResultSet.java b/src/share/classes/java/sql/ResultSet.java index 7029c935906459ebb45e7db41dd89f6fd9e5b08a..ad954e89d1d78a1dd4917f290b47e5e9a248828f 100644 --- a/src/share/classes/java/sql/ResultSet.java +++ b/src/share/classes/java/sql/ResultSet.java @@ -90,7 +90,7 @@ import java.io.InputStream; * the intended columns, which can be assured with the SQL AS clause. *

    * A set of updater methods were added to this interface - * in the JDBC 2.0 API (JavaTM 2 SDK, + * in the JDBC 2.0 API (Java™ 2 SDK, * Standard Edition, version 1.2). The comments regarding parameters * to the getter methods also apply to parameters to the * updater methods. @@ -148,7 +148,7 @@ import java.io.InputStream; public interface ResultSet extends Wrapper, AutoCloseable { /** - * Moves the cursor froward one row from its current position. + * Moves the cursor forward one row from its current position. * A ResultSet cursor is initially positioned * before the first row; the first call to the method * next makes the first row the current row; the @@ -4101,7 +4101,7 @@ public interface ResultSet extends Wrapper, AutoCloseable { * Appendix B, Table B-3 and conversion of appropriate user defined SQL * types to a Java type which implements {@code SQLData}, or {@code Struct}. * Additional conversions may be supported and are vendor defined. - * + * @param the type of the class modeled by this Class object * @param columnIndex the first column is 1, the second is 2, ... * @param type Class representing the Java data type to convert the designated * column to. @@ -4135,6 +4135,7 @@ public interface ResultSet extends Wrapper, AutoCloseable { * of the column * @param type Class representing the Java data type to convert the designated * column to. + * @param the type of the class modeled by this Class object * @return an instance of {@code type} holding the column value * @throws SQLException if conversion is not supported, type is null or * another error occurs. The getCause() method of the @@ -4208,6 +4209,7 @@ public interface ResultSet extends Wrapper, AutoCloseable { * @param columnLabel the label for the column specified with the SQL AS * clause. If the SQL AS clause was not specified, then the label is * the name of the column + * @param x the new column value * @param targetSqlType the SQL type to be sent to the database * @param scaleOrLength for an object of {@code java.math.BigDecimal} , * this is the number of digits after the decimal point. For diff --git a/src/share/classes/java/sql/SQLInput.java b/src/share/classes/java/sql/SQLInput.java index 8d2540dc499f678661f6635dbadf403f9a428c3c..b768fa95e1e54e821aa2ebbb7c9e585d1b45c35e 100644 --- a/src/share/classes/java/sql/SQLInput.java +++ b/src/share/classes/java/sql/SQLInput.java @@ -444,6 +444,7 @@ public interface SQLInput { *

    * The default implementation will throw {@code SQLFeatureNotSupportedException} * + * @param the type of the class modeled by this Class object * @param type Class representing the Java data type to convert the attribute to. * @return the attribute at the head of the stream as an {@code Object} in the * Java programming language;{@code null} if the attribute is SQL {@code NULL} diff --git a/src/share/classes/java/sql/SQLPermission.java b/src/share/classes/java/sql/SQLPermission.java index 3aa5a42860bf8986612d2db205f8410f5b397454..d264706ab7d68de65a60cf6e8c9e7911d87eedcf 100644 --- a/src/share/classes/java/sql/SQLPermission.java +++ b/src/share/classes/java/sql/SQLPermission.java @@ -103,7 +103,6 @@ import java.security.*; * Permits an application to remove a JDBC driver from the list of * registered Drivers and release its resources. * - * * *

    * @since 1.3 diff --git a/src/share/classes/java/sql/SQLXML.java b/src/share/classes/java/sql/SQLXML.java index 88e3baada72ed3b3fa237a59dca02255e05b51b9..2acc5d1d350a1514a4a700a34c1929a6b9ad6ae7 100644 --- a/src/share/classes/java/sql/SQLXML.java +++ b/src/share/classes/java/sql/SQLXML.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -360,6 +360,7 @@ public interface SQLXML * xmlReader.parse(saxSource.getInputSource()); *

    * + * @param the type of the class modeled by this Class object * @param sourceClass The class of the source, or null. * If the class is null, a vendor specifc Source implementation will be returned. * The following classes are supported at a minimum: @@ -401,6 +402,7 @@ public interface SQLXML * contentHandler.endDocument(); *
    * + * @param the type of the class modeled by this Class object * @param resultClass The class of the result, or null. * If resultClass is null, a vendor specific Result implementation will be returned. * The following classes are supported at a minimum: diff --git a/src/share/classes/java/sql/Wrapper.java b/src/share/classes/java/sql/Wrapper.java index 2eaa003f2404a14704f0f7d032d76701a440f5f0..ee77431c0cdfe1d0e6e0fbd77628456b2a93d161 100644 --- a/src/share/classes/java/sql/Wrapper.java +++ b/src/share/classes/java/sql/Wrapper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,6 +53,7 @@ public interface Wrapper { * or a proxy for that result. If the receiver is not a * wrapper and does not implement the interface, then an SQLException is thrown. * + * @param the type of the class modeled by this Class object * @param iface A Class defining an interface that the result must implement. * @return an object that implements the interface. May be a proxy for the actual implementing object. * @throws java.sql.SQLException If no object found that implements the interface diff --git a/src/share/classes/java/time/format/DateTimeFormatter.java b/src/share/classes/java/time/format/DateTimeFormatter.java index 158c741dff4e1e73866aedadbd43575a1b7f2160..2552f96e5ad36f3e5abdb8343eaff2bcaa418e82 100644 --- a/src/share/classes/java/time/format/DateTimeFormatter.java +++ b/src/share/classes/java/time/format/DateTimeFormatter.java @@ -1304,6 +1304,7 @@ public final class DateTimeFormatter { * LocalTime time = parsed.query(LocalTime::from); * Period extraDays = parsed.query(DateTimeFormatter.parsedExcessDays()); *
    + * @return a query that provides access to the excess days that were parsed */ public static final TemporalQuery parsedExcessDays() { return PARSED_EXCESS_DAYS; @@ -1344,6 +1345,7 @@ public final class DateTimeFormatter { * // validate leap-second is correct and apply correct smoothing * } *
    + * @return a query that provides access to whether a leap-second was parsed */ public static final TemporalQuery parsedLeapSecond() { return PARSED_LEAP_SECOND; diff --git a/src/share/classes/java/util/ArrayPrefixHelpers.java b/src/share/classes/java/util/ArrayPrefixHelpers.java new file mode 100644 index 0000000000000000000000000000000000000000..ef59ec7d47897ab3cfe181974dd9bbf07919322c --- /dev/null +++ b/src/share/classes/java/util/ArrayPrefixHelpers.java @@ -0,0 +1,697 @@ +/* + * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package java.util; + +/* + * Written by Doug Lea with assistance from members of JCP JSR-166 + * Expert Group and released to the public domain, as explained at + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.CountedCompleter; +import java.util.function.BinaryOperator; +import java.util.function.IntBinaryOperator; +import java.util.function.LongBinaryOperator; +import java.util.function.DoubleBinaryOperator; + +/** + * ForkJoin tasks to perform Arrays.parallelPrefix operations. + * + * @author Doug Lea + * @since 1.8 + */ +class ArrayPrefixHelpers { + private ArrayPrefixHelpers() {}; // non-instantiable + + /* + * Parallel prefix (aka cumulate, scan) task classes + * are based loosely on Guy Blelloch's original + * algorithm (http://www.cs.cmu.edu/~scandal/alg/scan.html): + * Keep dividing by two to threshold segment size, and then: + * Pass 1: Create tree of partial sums for each segment + * Pass 2: For each segment, cumulate with offset of left sibling + * + * This version improves performance within FJ framework mainly by + * allowing the second pass of ready left-hand sides to proceed + * even if some right-hand side first passes are still executing. + * It also combines first and second pass for leftmost segment, + * and skips the first pass for rightmost segment (whose result is + * not needed for second pass). It similarly manages to avoid + * requiring that users supply an identity basis for accumulations + * by tracking those segments/subtasks for which the first + * existing element is used as base. + * + * Managing this relies on ORing some bits in the pendingCount for + * phases/states: CUMULATE, SUMMED, and FINISHED. CUMULATE is the + * main phase bit. When false, segments compute only their sum. + * When true, they cumulate array elements. CUMULATE is set at + * root at beginning of second pass and then propagated down. But + * it may also be set earlier for subtrees with lo==0 (the left + * spine of tree). SUMMED is a one bit join count. For leafs, it + * is set when summed. For internal nodes, it becomes true when + * one child is summed. When the second child finishes summing, + * we then moves up tree to trigger the cumulate phase. FINISHED + * is also a one bit join count. For leafs, it is set when + * cumulated. For internal nodes, it becomes true when one child + * is cumulated. When the second child finishes cumulating, it + * then moves up tree, completing at the root. + * + * To better exploit locality and reduce overhead, the compute + * method loops starting with the current task, moving if possible + * to one of its subtasks rather than forking. + * + * As usual for this sort of utility, there are 4 versions, that + * are simple copy/paste/adapt variants of each other. (The + * double and int versions differ from long version soley by + * replacing "long" (with case-matching)). + */ + + // see above + static final int CUMULATE = 1; + static final int SUMMED = 2; + static final int FINISHED = 4; + + /** The smallest subtask array partition size to use as threshold */ + static final int MIN_PARTITION = 16; + + static final class CumulateTask extends CountedCompleter { + final T[] array; + final BinaryOperator function; + CumulateTask left, right; + T in, out; + final int lo, hi, origin, fence, threshold; + + /** Root task constructor */ + public CumulateTask(CumulateTask parent, + BinaryOperator function, + T[] array, int lo, int hi) { + super(parent); + this.function = function; this.array = array; + this.lo = this.origin = lo; this.hi = this.fence = hi; + int p; + this.threshold = + (p = (hi - lo) / (ForkJoinPool.getCommonPoolParallelism() << 3)) + <= MIN_PARTITION ? MIN_PARTITION : p; + } + + /** Subtask constructor */ + CumulateTask(CumulateTask parent, BinaryOperator function, + T[] array, int origin, int fence, int threshold, + int lo, int hi) { + super(parent); + this.function = function; this.array = array; + this.origin = origin; this.fence = fence; + this.threshold = threshold; + this.lo = lo; this.hi = hi; + } + + public final void compute() { + final BinaryOperator fn; + final T[] a; + if ((fn = this.function) == null || (a = this.array) == null) + throw new NullPointerException(); // hoist checks + int th = threshold, org = origin, fnc = fence, l, h; + CumulateTask t = this; + outer: while ((l = t.lo) >= 0 && (h = t.hi) <= a.length) { + if (h - l > th) { + CumulateTask lt = t.left, rt = t.right, f; + if (lt == null) { // first pass + int mid = (l + h) >>> 1; + f = rt = t.right = + new CumulateTask(t, fn, a, org, fnc, th, mid, h); + t = lt = t.left = + new CumulateTask(t, fn, a, org, fnc, th, l, mid); + } + else { // possibly refork + T pin = t.in; + lt.in = pin; + f = t = null; + if (rt != null) { + T lout = lt.out; + rt.in = (l == org ? lout : + fn.apply(pin, lout)); + for (int c;;) { + if (((c = rt.getPendingCount()) & CUMULATE) != 0) + break; + if (rt.compareAndSetPendingCount(c, c|CUMULATE)){ + t = rt; + break; + } + } + } + for (int c;;) { + if (((c = lt.getPendingCount()) & CUMULATE) != 0) + break; + if (lt.compareAndSetPendingCount(c, c|CUMULATE)) { + if (t != null) + f = t; + t = lt; + break; + } + } + if (t == null) + break; + } + if (f != null) + f.fork(); + } + else { + int state; // Transition to sum, cumulate, or both + for (int b;;) { + if (((b = t.getPendingCount()) & FINISHED) != 0) + break outer; // already done + state = ((b & CUMULATE) != 0? FINISHED : + (l > org) ? SUMMED : (SUMMED|FINISHED)); + if (t.compareAndSetPendingCount(b, b|state)) + break; + } + + T sum; + if (state != SUMMED) { + int first; + if (l == org) { // leftmost; no in + sum = a[org]; + first = org + 1; + } + else { + sum = t.in; + first = l; + } + for (int i = first; i < h; ++i) // cumulate + a[i] = sum = fn.apply(sum, a[i]); + } + else if (h < fnc) { // skip rightmost + sum = a[l]; + for (int i = l + 1; i < h; ++i) // sum only + sum = fn.apply(sum, a[i]); + } + else + sum = t.in; + t.out = sum; + for (CumulateTask par;;) { // propagate + if ((par = (CumulateTask)t.getCompleter()) == null) { + if ((state & FINISHED) != 0) // enable join + t.quietlyComplete(); + break outer; + } + int b = par.getPendingCount(); + if ((b & state & FINISHED) != 0) + t = par; // both done + else if ((b & state & SUMMED) != 0) { // both summed + int nextState; CumulateTask lt, rt; + if ((lt = par.left) != null && + (rt = par.right) != null) { + T lout = lt.out; + par.out = (rt.hi == fnc ? lout : + fn.apply(lout, rt.out)); + } + int refork = (((b & CUMULATE) == 0 && + par.lo == org) ? CUMULATE : 0); + if ((nextState = b|state|refork) == b || + par.compareAndSetPendingCount(b, nextState)) { + state = SUMMED; // drop finished + t = par; + if (refork != 0) + par.fork(); + } + } + else if (par.compareAndSetPendingCount(b, b|state)) + break outer; // sib not ready + } + } + } + } + } + + static final class LongCumulateTask extends CountedCompleter { + final long[] array; + final LongBinaryOperator function; + LongCumulateTask left, right; + long in, out; + final int lo, hi, origin, fence, threshold; + + /** Root task constructor */ + public LongCumulateTask(LongCumulateTask parent, + LongBinaryOperator function, + long[] array, int lo, int hi) { + super(parent); + this.function = function; this.array = array; + this.lo = this.origin = lo; this.hi = this.fence = hi; + int p; + this.threshold = + (p = (hi - lo) / (ForkJoinPool.getCommonPoolParallelism() << 3)) + <= MIN_PARTITION ? MIN_PARTITION : p; + } + + /** Subtask constructor */ + LongCumulateTask(LongCumulateTask parent, LongBinaryOperator function, + long[] array, int origin, int fence, int threshold, + int lo, int hi) { + super(parent); + this.function = function; this.array = array; + this.origin = origin; this.fence = fence; + this.threshold = threshold; + this.lo = lo; this.hi = hi; + } + + public final void compute() { + final LongBinaryOperator fn; + final long[] a; + if ((fn = this.function) == null || (a = this.array) == null) + throw new NullPointerException(); // hoist checks + int th = threshold, org = origin, fnc = fence, l, h; + LongCumulateTask t = this; + outer: while ((l = t.lo) >= 0 && (h = t.hi) <= a.length) { + if (h - l > th) { + LongCumulateTask lt = t.left, rt = t.right, f; + if (lt == null) { // first pass + int mid = (l + h) >>> 1; + f = rt = t.right = + new LongCumulateTask(t, fn, a, org, fnc, th, mid, h); + t = lt = t.left = + new LongCumulateTask(t, fn, a, org, fnc, th, l, mid); + } + else { // possibly refork + long pin = t.in; + lt.in = pin; + f = t = null; + if (rt != null) { + long lout = lt.out; + rt.in = (l == org ? lout : + fn.applyAsLong(pin, lout)); + for (int c;;) { + if (((c = rt.getPendingCount()) & CUMULATE) != 0) + break; + if (rt.compareAndSetPendingCount(c, c|CUMULATE)){ + t = rt; + break; + } + } + } + for (int c;;) { + if (((c = lt.getPendingCount()) & CUMULATE) != 0) + break; + if (lt.compareAndSetPendingCount(c, c|CUMULATE)) { + if (t != null) + f = t; + t = lt; + break; + } + } + if (t == null) + break; + } + if (f != null) + f.fork(); + } + else { + int state; // Transition to sum, cumulate, or both + for (int b;;) { + if (((b = t.getPendingCount()) & FINISHED) != 0) + break outer; // already done + state = ((b & CUMULATE) != 0? FINISHED : + (l > org) ? SUMMED : (SUMMED|FINISHED)); + if (t.compareAndSetPendingCount(b, b|state)) + break; + } + + long sum; + if (state != SUMMED) { + int first; + if (l == org) { // leftmost; no in + sum = a[org]; + first = org + 1; + } + else { + sum = t.in; + first = l; + } + for (int i = first; i < h; ++i) // cumulate + a[i] = sum = fn.applyAsLong(sum, a[i]); + } + else if (h < fnc) { // skip rightmost + sum = a[l]; + for (int i = l + 1; i < h; ++i) // sum only + sum = fn.applyAsLong(sum, a[i]); + } + else + sum = t.in; + t.out = sum; + for (LongCumulateTask par;;) { // propagate + if ((par = (LongCumulateTask)t.getCompleter()) == null) { + if ((state & FINISHED) != 0) // enable join + t.quietlyComplete(); + break outer; + } + int b = par.getPendingCount(); + if ((b & state & FINISHED) != 0) + t = par; // both done + else if ((b & state & SUMMED) != 0) { // both summed + int nextState; LongCumulateTask lt, rt; + if ((lt = par.left) != null && + (rt = par.right) != null) { + long lout = lt.out; + par.out = (rt.hi == fnc ? lout : + fn.applyAsLong(lout, rt.out)); + } + int refork = (((b & CUMULATE) == 0 && + par.lo == org) ? CUMULATE : 0); + if ((nextState = b|state|refork) == b || + par.compareAndSetPendingCount(b, nextState)) { + state = SUMMED; // drop finished + t = par; + if (refork != 0) + par.fork(); + } + } + else if (par.compareAndSetPendingCount(b, b|state)) + break outer; // sib not ready + } + } + } + } + } + + static final class DoubleCumulateTask extends CountedCompleter { + final double[] array; + final DoubleBinaryOperator function; + DoubleCumulateTask left, right; + double in, out; + final int lo, hi, origin, fence, threshold; + + /** Root task constructor */ + public DoubleCumulateTask(DoubleCumulateTask parent, + DoubleBinaryOperator function, + double[] array, int lo, int hi) { + super(parent); + this.function = function; this.array = array; + this.lo = this.origin = lo; this.hi = this.fence = hi; + int p; + this.threshold = + (p = (hi - lo) / (ForkJoinPool.getCommonPoolParallelism() << 3)) + <= MIN_PARTITION ? MIN_PARTITION : p; + } + + /** Subtask constructor */ + DoubleCumulateTask(DoubleCumulateTask parent, DoubleBinaryOperator function, + double[] array, int origin, int fence, int threshold, + int lo, int hi) { + super(parent); + this.function = function; this.array = array; + this.origin = origin; this.fence = fence; + this.threshold = threshold; + this.lo = lo; this.hi = hi; + } + + public final void compute() { + final DoubleBinaryOperator fn; + final double[] a; + if ((fn = this.function) == null || (a = this.array) == null) + throw new NullPointerException(); // hoist checks + int th = threshold, org = origin, fnc = fence, l, h; + DoubleCumulateTask t = this; + outer: while ((l = t.lo) >= 0 && (h = t.hi) <= a.length) { + if (h - l > th) { + DoubleCumulateTask lt = t.left, rt = t.right, f; + if (lt == null) { // first pass + int mid = (l + h) >>> 1; + f = rt = t.right = + new DoubleCumulateTask(t, fn, a, org, fnc, th, mid, h); + t = lt = t.left = + new DoubleCumulateTask(t, fn, a, org, fnc, th, l, mid); + } + else { // possibly refork + double pin = t.in; + lt.in = pin; + f = t = null; + if (rt != null) { + double lout = lt.out; + rt.in = (l == org ? lout : + fn.applyAsDouble(pin, lout)); + for (int c;;) { + if (((c = rt.getPendingCount()) & CUMULATE) != 0) + break; + if (rt.compareAndSetPendingCount(c, c|CUMULATE)){ + t = rt; + break; + } + } + } + for (int c;;) { + if (((c = lt.getPendingCount()) & CUMULATE) != 0) + break; + if (lt.compareAndSetPendingCount(c, c|CUMULATE)) { + if (t != null) + f = t; + t = lt; + break; + } + } + if (t == null) + break; + } + if (f != null) + f.fork(); + } + else { + int state; // Transition to sum, cumulate, or both + for (int b;;) { + if (((b = t.getPendingCount()) & FINISHED) != 0) + break outer; // already done + state = ((b & CUMULATE) != 0? FINISHED : + (l > org) ? SUMMED : (SUMMED|FINISHED)); + if (t.compareAndSetPendingCount(b, b|state)) + break; + } + + double sum; + if (state != SUMMED) { + int first; + if (l == org) { // leftmost; no in + sum = a[org]; + first = org + 1; + } + else { + sum = t.in; + first = l; + } + for (int i = first; i < h; ++i) // cumulate + a[i] = sum = fn.applyAsDouble(sum, a[i]); + } + else if (h < fnc) { // skip rightmost + sum = a[l]; + for (int i = l + 1; i < h; ++i) // sum only + sum = fn.applyAsDouble(sum, a[i]); + } + else + sum = t.in; + t.out = sum; + for (DoubleCumulateTask par;;) { // propagate + if ((par = (DoubleCumulateTask)t.getCompleter()) == null) { + if ((state & FINISHED) != 0) // enable join + t.quietlyComplete(); + break outer; + } + int b = par.getPendingCount(); + if ((b & state & FINISHED) != 0) + t = par; // both done + else if ((b & state & SUMMED) != 0) { // both summed + int nextState; DoubleCumulateTask lt, rt; + if ((lt = par.left) != null && + (rt = par.right) != null) { + double lout = lt.out; + par.out = (rt.hi == fnc ? lout : + fn.applyAsDouble(lout, rt.out)); + } + int refork = (((b & CUMULATE) == 0 && + par.lo == org) ? CUMULATE : 0); + if ((nextState = b|state|refork) == b || + par.compareAndSetPendingCount(b, nextState)) { + state = SUMMED; // drop finished + t = par; + if (refork != 0) + par.fork(); + } + } + else if (par.compareAndSetPendingCount(b, b|state)) + break outer; // sib not ready + } + } + } + } + } + + static final class IntCumulateTask extends CountedCompleter { + final int[] array; + final IntBinaryOperator function; + IntCumulateTask left, right; + int in, out; + final int lo, hi, origin, fence, threshold; + + /** Root task constructor */ + public IntCumulateTask(IntCumulateTask parent, + IntBinaryOperator function, + int[] array, int lo, int hi) { + super(parent); + this.function = function; this.array = array; + this.lo = this.origin = lo; this.hi = this.fence = hi; + int p; + this.threshold = + (p = (hi - lo) / (ForkJoinPool.getCommonPoolParallelism() << 3)) + <= MIN_PARTITION ? MIN_PARTITION : p; + } + + /** Subtask constructor */ + IntCumulateTask(IntCumulateTask parent, IntBinaryOperator function, + int[] array, int origin, int fence, int threshold, + int lo, int hi) { + super(parent); + this.function = function; this.array = array; + this.origin = origin; this.fence = fence; + this.threshold = threshold; + this.lo = lo; this.hi = hi; + } + + public final void compute() { + final IntBinaryOperator fn; + final int[] a; + if ((fn = this.function) == null || (a = this.array) == null) + throw new NullPointerException(); // hoist checks + int th = threshold, org = origin, fnc = fence, l, h; + IntCumulateTask t = this; + outer: while ((l = t.lo) >= 0 && (h = t.hi) <= a.length) { + if (h - l > th) { + IntCumulateTask lt = t.left, rt = t.right, f; + if (lt == null) { // first pass + int mid = (l + h) >>> 1; + f = rt = t.right = + new IntCumulateTask(t, fn, a, org, fnc, th, mid, h); + t = lt = t.left = + new IntCumulateTask(t, fn, a, org, fnc, th, l, mid); + } + else { // possibly refork + int pin = t.in; + lt.in = pin; + f = t = null; + if (rt != null) { + int lout = lt.out; + rt.in = (l == org ? lout : + fn.applyAsInt(pin, lout)); + for (int c;;) { + if (((c = rt.getPendingCount()) & CUMULATE) != 0) + break; + if (rt.compareAndSetPendingCount(c, c|CUMULATE)){ + t = rt; + break; + } + } + } + for (int c;;) { + if (((c = lt.getPendingCount()) & CUMULATE) != 0) + break; + if (lt.compareAndSetPendingCount(c, c|CUMULATE)) { + if (t != null) + f = t; + t = lt; + break; + } + } + if (t == null) + break; + } + if (f != null) + f.fork(); + } + else { + int state; // Transition to sum, cumulate, or both + for (int b;;) { + if (((b = t.getPendingCount()) & FINISHED) != 0) + break outer; // already done + state = ((b & CUMULATE) != 0? FINISHED : + (l > org) ? SUMMED : (SUMMED|FINISHED)); + if (t.compareAndSetPendingCount(b, b|state)) + break; + } + + int sum; + if (state != SUMMED) { + int first; + if (l == org) { // leftmost; no in + sum = a[org]; + first = org + 1; + } + else { + sum = t.in; + first = l; + } + for (int i = first; i < h; ++i) // cumulate + a[i] = sum = fn.applyAsInt(sum, a[i]); + } + else if (h < fnc) { // skip rightmost + sum = a[l]; + for (int i = l + 1; i < h; ++i) // sum only + sum = fn.applyAsInt(sum, a[i]); + } + else + sum = t.in; + t.out = sum; + for (IntCumulateTask par;;) { // propagate + if ((par = (IntCumulateTask)t.getCompleter()) == null) { + if ((state & FINISHED) != 0) // enable join + t.quietlyComplete(); + break outer; + } + int b = par.getPendingCount(); + if ((b & state & FINISHED) != 0) + t = par; // both done + else if ((b & state & SUMMED) != 0) { // both summed + int nextState; IntCumulateTask lt, rt; + if ((lt = par.left) != null && + (rt = par.right) != null) { + int lout = lt.out; + par.out = (rt.hi == fnc ? lout : + fn.applyAsInt(lout, rt.out)); + } + int refork = (((b & CUMULATE) == 0 && + par.lo == org) ? CUMULATE : 0); + if ((nextState = b|state|refork) == b || + par.compareAndSetPendingCount(b, nextState)) { + state = SUMMED; // drop finished + t = par; + if (refork != 0) + par.fork(); + } + } + else if (par.compareAndSetPendingCount(b, b|state)) + break outer; // sib not ready + } + } + } + } + } + + +} \ No newline at end of file diff --git a/src/share/classes/java/util/Arrays.java b/src/share/classes/java/util/Arrays.java index 4035666d2ab7130153b6e069ae15fd0be0c56f84..196a31e5767e9f92e43eefb077765218e2accb05 100644 --- a/src/share/classes/java/util/Arrays.java +++ b/src/share/classes/java/util/Arrays.java @@ -1559,6 +1559,183 @@ public class Arrays { } } + // Parallel prefix + + /** + * Cumulates, in parallel, each element of the given array in place, + * using the supplied function. For example if the array initially + * holds {@code [2, 1, 0, 3]} and the operation performs addition, + * then upon return the array holds {@code [2, 3, 3, 6]}. + * Parallel prefix computation is usually more efficient than + * sequential loops for large arrays. + * + * @param array the array, which is modified in-place by this method + * @param op a side-effect-free, associative function to perform the + * cumulation + * @throws NullPointerException if the specified array or function is null + * @since 1.8 + */ + public static void parallelPrefix(T[] array, BinaryOperator op) { + if (array.length > 0) + new ArrayPrefixHelpers.CumulateTask<> + (null, op, array, 0, array.length).invoke(); + } + + /** + * Performs {@link #parallelPrefix(Object[], BinaryOperator)} + * for the given subrange of the array. + * + * @param array the array + * @param fromIndex the index of the first element, inclusive + * @param toIndex the index of the last element, exclusive + * @param op a side-effect-free, associative function to perform the + * cumulation + * @throws IllegalArgumentException if {@code fromIndex > toIndex} + * @throws ArrayIndexOutOfBoundsException + * if {@code fromIndex < 0} or {@code toIndex > array.length} + * @throws NullPointerException if the specified array or function is null + * @since 1.8 + */ + public static void parallelPrefix(T[] array, int fromIndex, + int toIndex, BinaryOperator op) { + rangeCheck(array.length, fromIndex, toIndex); + if (fromIndex < toIndex) + new ArrayPrefixHelpers.CumulateTask<> + (null, op, array, fromIndex, toIndex).invoke(); + } + + /** + * Cumulates, in parallel, each element of the given array in place, + * using the supplied function. For example if the array initially + * holds {@code [2, 1, 0, 3]} and the operation performs addition, + * then upon return the array holds {@code [2, 3, 3, 6]}. + * Parallel prefix computation is usually more efficient than + * sequential loops for large arrays. + * + * @param array the array, which is modified in-place by this method + * @param op a side-effect-free, associative function to perform the + * cumulation + * @throws NullPointerException if the specified array or function is null + * @since 1.8 + */ + public static void parallelPrefix(long[] array, LongBinaryOperator op) { + if (array.length > 0) + new ArrayPrefixHelpers.LongCumulateTask + (null, op, array, 0, array.length).invoke(); + } + + /** + * Performs {@link #parallelPrefix(long[], LongBinaryOperator)} + * for the given subrange of the array. + * + * @param array the array + * @param fromIndex the index of the first element, inclusive + * @param toIndex the index of the last element, exclusive + * @param op a side-effect-free, associative function to perform the + * cumulation + * @throws IllegalArgumentException if {@code fromIndex > toIndex} + * @throws ArrayIndexOutOfBoundsException + * if {@code fromIndex < 0} or {@code toIndex > array.length} + * @throws NullPointerException if the specified array or function is null + * @since 1.8 + */ + public static void parallelPrefix(long[] array, int fromIndex, + int toIndex, LongBinaryOperator op) { + rangeCheck(array.length, fromIndex, toIndex); + if (fromIndex < toIndex) + new ArrayPrefixHelpers.LongCumulateTask + (null, op, array, fromIndex, toIndex).invoke(); + } + + /** + * Cumulates, in parallel, each element of the given array in place, + * using the supplied function. For example if the array initially + * holds {@code [2.0, 1.0, 0.0, 3.0]} and the operation performs addition, + * then upon return the array holds {@code [2.0, 3.0, 3.0, 6.0]}. + * Parallel prefix computation is usually more efficient than + * sequential loops for large arrays. + * + *

    Because floating-point operations may not be strictly associative, + * the returned result may not be identical to the value that would be + * obtained if the operation was performed sequentially. + * + * @param array the array, which is modified in-place by this method + * @param op a side-effect-free function to perform the cumulation + * @throws NullPointerException if the specified array or function is null + * @since 1.8 + */ + public static void parallelPrefix(double[] array, DoubleBinaryOperator op) { + if (array.length > 0) + new ArrayPrefixHelpers.DoubleCumulateTask + (null, op, array, 0, array.length).invoke(); + } + + /** + * Performs {@link #parallelPrefix(double[], DoubleBinaryOperator)} + * for the given subrange of the array. + * + * @param array the array + * @param fromIndex the index of the first element, inclusive + * @param toIndex the index of the last element, exclusive + * @param op a side-effect-free, associative function to perform the + * cumulation + * @throws IllegalArgumentException if {@code fromIndex > toIndex} + * @throws ArrayIndexOutOfBoundsException + * if {@code fromIndex < 0} or {@code toIndex > array.length} + * @throws NullPointerException if the specified array or function is null + * @since 1.8 + */ + public static void parallelPrefix(double[] array, int fromIndex, + int toIndex, DoubleBinaryOperator op) { + rangeCheck(array.length, fromIndex, toIndex); + if (fromIndex < toIndex) + new ArrayPrefixHelpers.DoubleCumulateTask + (null, op, array, fromIndex, toIndex).invoke(); + } + + /** + * Cumulates, in parallel, each element of the given array in place, + * using the supplied function. For example if the array initially + * holds {@code [2, 1, 0, 3]} and the operation performs addition, + * then upon return the array holds {@code [2, 3, 3, 6]}. + * Parallel prefix computation is usually more efficient than + * sequential loops for large arrays. + * + * @param array the array, which is modified in-place by this method + * @param op a side-effect-free, associative function to perform the + * cumulation + * @throws NullPointerException if the specified array or function is null + * @since 1.8 + */ + public static void parallelPrefix(int[] array, IntBinaryOperator op) { + if (array.length > 0) + new ArrayPrefixHelpers.IntCumulateTask + (null, op, array, 0, array.length).invoke(); + } + + /** + * Performs {@link #parallelPrefix(int[], IntBinaryOperator)} + * for the given subrange of the array. + * + * @param array the array + * @param fromIndex the index of the first element, inclusive + * @param toIndex the index of the last element, exclusive + * @param op a side-effect-free, associative function to perform the + * cumulation + * @throws IllegalArgumentException if {@code fromIndex > toIndex} + * @throws ArrayIndexOutOfBoundsException + * if {@code fromIndex < 0} or {@code toIndex > array.length} + * @throws NullPointerException if the specified array or function is null + * @since 1.8 + */ + public static void parallelPrefix(int[] array, int fromIndex, + int toIndex, IntBinaryOperator op) { + rangeCheck(array.length, fromIndex, toIndex); + if (fromIndex < toIndex) + new ArrayPrefixHelpers.IntCumulateTask + (null, op, array, fromIndex, toIndex).invoke(); + } + // Searching /** diff --git a/src/share/classes/java/util/Collections.java b/src/share/classes/java/util/Collections.java index da258793ba635548c50177780efae634990f9cd5..ad4540db14a710e9ae2ccba635f67534b4dc2f3d 100644 --- a/src/share/classes/java/util/Collections.java +++ b/src/share/classes/java/util/Collections.java @@ -4304,6 +4304,11 @@ public class Collections { } private Object readResolve() { return Collections.reverseOrder(); } + + @Override + public Comparator> reversed() { + return Comparator.naturalOrder(); + } } /** @@ -4367,6 +4372,11 @@ public class Collections { public int hashCode() { return cmp.hashCode() ^ Integer.MIN_VALUE; } + + @Override + public Comparator reversed() { + return cmp; + } } /** diff --git a/src/share/classes/java/util/Comparator.java b/src/share/classes/java/util/Comparator.java index 017c2e78e2ced52e4167a4328711c49264ebe0d7..cd65ca4ea06e05e5314cd68f9ce2f2a9ae1d4f7e 100644 --- a/src/share/classes/java/util/Comparator.java +++ b/src/share/classes/java/util/Comparator.java @@ -25,10 +25,12 @@ package java.util; +import java.io.Serializable; import java.util.function.Function; import java.util.function.ToIntFunction; import java.util.function.ToLongFunction; import java.util.function.ToDoubleFunction; +import java.util.Comparators; /** * A comparison function, which imposes a total ordering on some @@ -175,88 +177,357 @@ public interface Comparator { * Returns a comparator that imposes the reverse ordering of this * comparator. * - * @return A comparator that imposes the reverse ordering of this + * @return a comparator that imposes the reverse ordering of this * comparator. * @since 1.8 */ - default Comparator reverseOrder() { + default Comparator reversed() { return Collections.reverseOrder(this); } /** - * Constructs a lexicographic order comparator with another comparator. - * For example, a {@code Comparator byLastName} can be composed - * with another {@code Comparator byFirstName}, then {@code - * byLastName.thenComparing(byFirstName)} creates a {@code - * Comparator} which sorts by last name, and for equal last names - * sorts by first name. - * - * @param other the other comparator used when equals on this. + * Returns a lexicographic-order comparator with another comparator. + * If this {@code Comparator} considers two elements equal, i.e. + * {@code compare(a, b) == 0}, {@code other} is used to determine the order. + * + *

    The returned comparator is serializable if the specified comparator + * is also serializable. + * + * @apiNote + * For example, to sort a collection of {@code String} based on the length + * and then case-insensitive natural ordering, the comparator can be + * composed using following code, + * + *

    {@code
    +     *     Comparator cmp = Comparator.comparing(String::length)
    +     *             .thenComparing(String.CASE_INSENSITIVE_ORDER);
    +     * }
    + * + * @param other the other comparator to be used when this comparator + * compares two objects that are equal. + * @return a lexicographic-order comparator composed of this and then the + * other comparator * @throws NullPointerException if the argument is null. * @since 1.8 */ default Comparator thenComparing(Comparator other) { - return Comparators.compose(this, other); + Objects.requireNonNull(other); + return (Comparator & Serializable) (c1, c2) -> { + int res = compare(c1, c2); + return (res != 0) ? res : other.compare(c1, c2); + }; } /** - * Constructs a lexicographic order comparator with a function that - * extracts a {@code Comparable} key. This default implementation calls - * {@code thenComparing(this, Comparators.comparing(keyExtractor))}. + * Returns a lexicographic-order comparator with a function that + * extracts a key to be compared with the given {@code Comparator}. + * + * @implSpec This default implementation behaves as if {@code + * thenComparing(comparing(keyExtractor, cmp))}. * - * @param the {@link Comparable} type for comparison - * @param keyExtractor the function used to extract the {@link Comparable} sort key + * @param the type of the sort key + * @param keyExtractor the function used to extract the sort key + * @param keyComparator the {@code Comparator} used to compare the sort key + * @return a lexicographic-order comparator composed of this comparator + * and then comparing on the key extracted by the keyExtractor function * @throws NullPointerException if the argument is null. - * @see Comparators#comparing(Function) + * @see #comparing(Function, Comparator) * @see #thenComparing(Comparator) * @since 1.8 */ - default > Comparator thenComparing(Function keyExtractor) { - return thenComparing(Comparators.comparing(keyExtractor)); + default > Comparator thenComparing( + Function keyExtractor, + Comparator keyComparator) + { + return thenComparing(comparing(keyExtractor, keyComparator)); } /** - * Constructs a lexicographic order comparator with a function that - * extracts a {@code int} value. This default implementation calls {@code - * thenComparing(this, Comparators.comparing(keyExtractor))}. + * Returns a lexicographic-order comparator with a function that + * extracts a {@code Comparable} sort key. + * + * @implSpec This default implementation behaves as if {@code + * thenComparing(comparing(keyExtractor))}. * - * @param keyExtractor the function used to extract the integer value + * @param the type of the {@link Comparable} sort key + * @param keyExtractor the function used to extract the {@link + * Comparable} sort key + * @return a lexicographic-order comparator composed of this and then the + * {@link Comparable} sort key. * @throws NullPointerException if the argument is null. - * @see Comparators#comparing(ToIntFunction) + * @see #comparing(Function) + * @see #thenComparing(Comparator) + * @since 1.8 + */ + default > Comparator thenComparing( + Function keyExtractor) + { + return thenComparing(comparing(keyExtractor)); + } + + /** + * Returns a lexicographic-order comparator with a function that + * extracts a {@code int} sort key. + * + * @implSpec This default implementation behaves as if {@code + * thenComparing(comparing(keyExtractor))}. + * + * @param keyExtractor the function used to extract the integer sort key + * @return a lexicographic-order comparator composed of this and then the + * {@code int} sort key + * @throws NullPointerException if the argument is null. + * @see #comparing(ToIntFunction) * @see #thenComparing(Comparator) * @since 1.8 */ default Comparator thenComparing(ToIntFunction keyExtractor) { - return thenComparing(Comparators.comparing(keyExtractor)); + return thenComparing(comparing(keyExtractor)); } /** - * Constructs a lexicographic order comparator with a function that - * extracts a {@code long} value. This default implementation calls - * {@code thenComparing(this, Comparators.comparing(keyExtractor))}. + * Returns a lexicographic-order comparator with a function that + * extracts a {@code long} sort key. + * + * @implSpec This default implementation behaves as if {@code + * thenComparing(comparing(keyExtractor))}. * - * @param keyExtractor the function used to extract the long value + * @param keyExtractor the function used to extract the long sort key + * @return a lexicographic-order comparator composed of this and then the + * {@code long} sort key * @throws NullPointerException if the argument is null. - * @see Comparators#comparing(ToLongFunction) + * @see #comparing(ToLongFunction) * @see #thenComparing(Comparator) * @since 1.8 */ default Comparator thenComparing(ToLongFunction keyExtractor) { - return thenComparing(Comparators.comparing(keyExtractor)); + return thenComparing(comparing(keyExtractor)); } /** - * Constructs a lexicographic order comparator with a function that - * extracts a {@code double} value. This default implementation calls - * {@code thenComparing(this, Comparators.comparing(keyExtractor))}. + * Returns a lexicographic-order comparator with a function that + * extracts a {@code double} sort key. * - * @param keyExtractor the function used to extract the double value + * @implSpec This default implementation behaves as if {@code + * thenComparing(comparing(keyExtractor))}. + * + * @param keyExtractor the function used to extract the double sort key + * @return a lexicographic-order comparator composed of this and then the + * {@code double} sort key * @throws NullPointerException if the argument is null. - * @see Comparators#comparing(ToDoubleFunction) + * @see #comparing(ToDoubleFunction) * @see #thenComparing(Comparator) * @since 1.8 */ default Comparator thenComparing(ToDoubleFunction keyExtractor) { - return thenComparing(Comparators.comparing(keyExtractor)); + return thenComparing(comparing(keyExtractor)); + } + + /** + * Returns a comparator that imposes the reverse of the natural + * ordering. + * + *

    The returned comparator is serializable and throws {@link + * NullPointerException} when comparing {@code null}. + * + * @param the {@link Comparable} type of element to be compared + * @return a comparator that imposes the reverse of the natural + * ordering on {@code Comparable} objects. + * @see Comparable + * @since 1.8 + */ + public static > Comparator reverseOrder() { + return Collections.reverseOrder(); + } + + /** + * Returns a comparator that compares {@link Comparable} objects in natural + * order. + * + *

    The returned comparator is serializable and throws {@link + * NullPointerException} when comparing {@code null}. + * + * @param the {@link Comparable} type of element to be compared + * @return a comparator that imposes the natural ordering on {@code + * Comparable} objects. + * @see Comparable + * @since 1.8 + */ + public static > Comparator naturalOrder() { + return (Comparator) Comparators.NaturalOrderComparator.INSTANCE; + } + + /** + * Returns a null-friendly comparator that considers {@code null} to be + * less than non-null. When both are {@code null}, they are considered + * equal. If both are non-null, the specified {@code Comparator} is used + * to determine the order. If the specified comparator is {@code null}, + * then the returned comparator considers all non-null values to be equal. + * + *

    The returned comparator is serializable if the specified comparator + * is serializable. + * + * @param the type of the elements to be compared + * @param comparator a {@code Comparator} for comparing non-null values + * @return a comparator that considers {@code null} to be less than + * non-null, and compares non-null objects with the supplied + * {@code Comparator}. + * @since 1.8 + */ + public static Comparator nullsFirst(Comparator comparator) { + return new Comparators.NullComparator(true, comparator); + } + + /** + * Returns a null-friendly comparator that considers {@code null} to be + * greater than non-null. When both are {@code null}, they are considered + * equal. If both are non-null, the specified {@code Comparator} is used + * to determine the order. If the specified comparator is {@code null}, + * then the returned comparator considers all non-null values to be equal. + * + *

    The returned comparator is serializable if the specified comparator + * is serializable. + * + * @param the type of the elements to be compared + * @param comparator a {@code Comparator} for comparing non-null values + * @return a comparator that considers {@code null} to be greater than + * non-null, and compares non-null objects with the supplied + * {@code Comparator}. + * @since 1.8 + */ + public static Comparator nullsLast(Comparator comparator) { + return new Comparators.NullComparator(false, comparator); + } + + /** + * Accepts a function that extracts a sort key from a type {@code T}, and + * returns a {@code Comparator} that compares by that sort key using + * the specified {@link Comparator}. + * + *

    The returned comparator is serializable if the specified function + * and comparator are both serializable. + * + * @apiNote + * For example, to obtain a {@code Comparator} that compares {@code + * Person} objects by their last name ignoring case differences, + * + *

    {@code
    +     *     Comparator cmp = Comparator.comparing(
    +     *             Person::getLastName,
    +     *             String.CASE_INSENSITIVE_ORDER);
    +     * }
    + * + * @param the type of element to be compared + * @param the type of the sort key + * @param keyExtractor the function used to extract the sort key + * @param keyComparator the {@code Comparator} used to compare the sort key + * @return a comparator that compares by an extracted key using the + * specified {@code Comparator} + * @throws NullPointerException if either argument is null + * @since 1.8 + */ + public static Comparator comparing( + Function keyExtractor, + Comparator keyComparator) + { + Objects.requireNonNull(keyExtractor); + Objects.requireNonNull(keyComparator); + return (Comparator & Serializable) + (c1, c2) -> keyComparator.compare(keyExtractor.apply(c1), + keyExtractor.apply(c2)); + } + + /** + * Accepts a function that extracts a {@link java.lang.Comparable + * Comparable} sort key from a type {@code T}, and returns a {@code + * Comparator} that compares by that sort key. + * + *

    The returned comparator is serializable if the specified function + * is also serializable. + * + * @apiNote + * For example, to obtain a {@code Comparator} that compares {@code + * Person} objects by their last name, + * + *

    {@code
    +     *     Comparator byLastName = Comparator.comparing(Person::getLastName);
    +     * }
    + * + * @param the type of element to be compared + * @param the type of the {@code Comparable} sort key + * @param keyExtractor the function used to extract the {@link + * Comparable} sort key + * @return a comparator that compares by an extracted key + * @throws NullPointerException if the argument is null + * @since 1.8 + */ + public static > Comparator comparing( + Function keyExtractor) + { + Objects.requireNonNull(keyExtractor); + return (Comparator & Serializable) + (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2)); + } + + /** + * Accepts a function that extracts an {@code int} sort key from a type + * {@code T}, and returns a {@code Comparator} that compares by that + * sort key. + * + *

    The returned comparator is serializable if the specified function + * is also serializable. + * + * @param the type of element to be compared + * @param keyExtractor the function used to extract the integer sort key + * @return a comparator that compares by an extracted key + * @see #comparing(Function) + * @throws NullPointerException if the argument is null + * @since 1.8 + */ + public static Comparator comparing(ToIntFunction keyExtractor) { + Objects.requireNonNull(keyExtractor); + return (Comparator & Serializable) + (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2)); + } + + /** + * Accepts a function that extracts a {@code long} sort key from a type + * {@code T}, and returns a {@code Comparator} that compares by that + * sort key. + * + *

    The returned comparator is serializable if the specified function is + * also serializable. + * + * @param the type of element to be compared + * @param keyExtractor the function used to extract the long sort key + * @return a comparator that compares by an extracted key + * @see #comparing(Function) + * @throws NullPointerException if the argument is null + * @since 1.8 + */ + public static Comparator comparing(ToLongFunction keyExtractor) { + Objects.requireNonNull(keyExtractor); + return (Comparator & Serializable) + (c1, c2) -> Long.compare(keyExtractor.applyAsLong(c1), keyExtractor.applyAsLong(c2)); + } + + /** + * Accepts a function that extracts a {@code double} sort key from a type + * {@code T}, and returns a {@code Comparator} that compares by that + * sort key. + * + *

    The returned comparator is serializable if the specified function + * is also serializable. + * + * @param the type of element to be compared + * @param keyExtractor the function used to extract the double sort key + * @return a comparator that compares by an extracted key + * @see #comparing(Function) + * @throws NullPointerException if the argument is null + * @since 1.8 + */ + public static Comparator comparing(ToDoubleFunction keyExtractor) { + Objects.requireNonNull(keyExtractor); + return (Comparator & Serializable) + (c1, c2) -> Double.compare(keyExtractor.applyAsDouble(c1), keyExtractor.applyAsDouble(c2)); } } diff --git a/src/share/classes/java/util/Comparators.java b/src/share/classes/java/util/Comparators.java index 97b7412f5c9564856a46acc9057d9468b1c49e5a..a90383210854756b2589a16c9740abc3d6ee3cec 100644 --- a/src/share/classes/java/util/Comparators.java +++ b/src/share/classes/java/util/Comparators.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,16 +32,9 @@ import java.util.function.ToIntFunction; import java.util.function.ToLongFunction; /** - * This class consists of {@code static} utility methods for comparators. Mostly - * factory method that returns a {@link Comparator}. - * - *

    Unless otherwise noted, passing a {@code null} argument to a method in - * this class will cause a {@link NullPointerException} to be thrown. - * - * @see Comparator - * @since 1.8 + * Package private supporting class for {@link Comparator}. */ -public class Comparators { +class Comparators { private Comparators() { throw new AssertionError("no instances"); } @@ -51,231 +44,55 @@ public class Comparators { * * @see Comparable */ - private enum NaturalOrderComparator implements Comparator> { + enum NaturalOrderComparator implements Comparator> { INSTANCE; @Override public int compare(Comparable c1, Comparable c2) { return c1.compareTo(c2); } - } - - /** - * Returns a comparator that imposes the reverse of the natural - * ordering. - * - *

    The returned comparator is serializable. - * - * @param {@link Comparable} type - * - * @return A comparator that imposes the reverse of the natural - * ordering on a collection of objects that implement - * the {@link Comparable} interface. - * @see Comparable - */ - public static > Comparator reverseOrder() { - return Collections.reverseOrder(); - } - - /** - * Returns a comparator that imposes the reverse ordering of the specified - * {@link Comparator}. - * - *

    The returned comparator is serializable (assuming the specified - * comparator is also serializable). - * - * @param the element type to be compared - * @param cmp a comparator whose ordering is to be reversed by the returned - * comparator - * @return A comparator that imposes the reverse ordering of the - * specified comparator. - */ - public static Comparator reverseOrder(Comparator cmp) { - Objects.requireNonNull(cmp); - return Collections.reverseOrder(cmp); - } - - /** - * Gets a comparator compares {@link Comparable} type in natural order. - * - * @param {@link Comparable} type - */ - public static > Comparator naturalOrder() { - return (Comparator) NaturalOrderComparator.INSTANCE; - } - - /** - * Gets a comparator compares {@link Map.Entry} in natural order on key. - * - * @param {@link Comparable} key type - * @param value type - */ - public static , V> Comparator> naturalOrderKeys() { - return (Comparator> & Serializable) - (c1, c2) -> c1.getKey().compareTo(c2.getKey()); - } - - /** - * Gets a comparator compares {@link Map.Entry} in natural order on value. - * - * @param key type - * @param {@link Comparable} value type - */ - public static > Comparator> naturalOrderValues() { - return (Comparator> & Serializable) - (c1, c2) -> c1.getValue().compareTo(c2.getValue()); - } - - /** - * Gets a comparator compares {@link Map.Entry} by key using the given - * {@link Comparator}. - * - *

    The returned comparator is serializable assuming the specified - * comparators are also serializable. - * - * @param key type - * @param value type - * @param cmp the key {@link Comparator} - */ - public static Comparator> byKey(Comparator cmp) { - Objects.requireNonNull(cmp); - return (Comparator> & Serializable) - (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey()); - } - - /** - * Gets a comparator compares {@link Map.Entry} by value using the given - * {@link Comparator}. - * - * @param key type - * @param value type - * @param cmp the value {@link Comparator} - */ - public static Comparator> byValue(Comparator cmp) { - Objects.requireNonNull(cmp); - return (Comparator> & Serializable) - (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue()); - } - /** - * Accepts a function that extracts a {@link java.lang.Comparable - * Comparable} sort key from a type {@code T}, and returns a {@code - * Comparator} that compares by that sort key. For example, if a class - * {@code Person} has a {@code String}-valued getter {@code getLastName}, - * then {@code comparing(Person::getLastName)} would return a {@code - * Comparator} that compares {@code Person} objects by their last - * name. - * - * @param the original element type - * @param the {@link Comparable} type for comparison - * @param keyExtractor the function used to extract the {@link Comparable} sort key - */ - public static > Comparator comparing(Function keyExtractor) { - Objects.requireNonNull(keyExtractor); - return (Comparator & Serializable) - (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2)); - } - - /** - * Accepts a function that extracts an {@code int} value from a type {@code - * T}, and returns a {@code Comparator} that compares by that value. - * - *

    The returned comparator is serializable assuming the specified - * function is also serializable. - * - * @see #comparing(Function) - * @param the original element type - * @param keyExtractor the function used to extract the integer value - */ - public static Comparator comparing(ToIntFunction keyExtractor) { - Objects.requireNonNull(keyExtractor); - return (Comparator & Serializable) - (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2)); - } - - /** - * Accepts a function that extracts a {@code long} value from a type {@code - * T}, and returns a {@code Comparator} that compares by that value. - * - *

    The returned comparator is serializable assuming the specified - * function is also serializable. - * - * @see #comparing(Function) - * @param the original element type - * @param keyExtractor the function used to extract the long value - */ - public static Comparator comparing(ToLongFunction keyExtractor) { - Objects.requireNonNull(keyExtractor); - return (Comparator & Serializable) - (c1, c2) -> Long.compare(keyExtractor.applyAsLong(c1), keyExtractor.applyAsLong(c2)); + @Override + public Comparator> reversed() { + return Comparator.reverseOrder(); + } } /** - * Accepts a function that extracts a {@code double} value from a type - * {@code T}, and returns a {@code Comparator} that compares by that - * value. - * - *

    The returned comparator is serializable assuming the specified - * function is also serializable. - * - * @see #comparing(Function) - * @param the original element type - * @param keyExtractor the function used to extract the double value + * Null-friendly comparators */ - public static Comparator comparing(ToDoubleFunction keyExtractor) { - Objects.requireNonNull(keyExtractor); - return (Comparator & Serializable) - (c1, c2) -> Double.compare(keyExtractor.applyAsDouble(c1), keyExtractor.applyAsDouble(c2)); - } + final static class NullComparator implements Comparator, Serializable { + private static final long serialVersionUID = -7569533591570686392L; + private final boolean nullFirst; + // if null, non-null Ts are considered equal + private final Comparator real; + + @SuppressWarnings("unchecked") + NullComparator(boolean nullFirst, Comparator real) { + this.nullFirst = nullFirst; + this.real = (Comparator) real; + } - /** - * Constructs a lexicographic order from two {@link Comparator}s. For - * example, if you have comparators {@code byLastName} and {@code - * byFirstName}, each of type {@code Comparator}, then {@code - * compose(byLastName, byFirstName)} creates a {@code Comparator} - * which sorts by last name, and for equal last names sorts by first name. - * - *

    The returned comparator is serializable assuming the specified - * comparators are also serializable. - * - * @param the element type to be compared - * @param first the first comparator - * @param second the secondary comparator used when equals on the first - */ - public static Comparator compose(Comparator first, Comparator second) { - Objects.requireNonNull(first); - Objects.requireNonNull(second); - return (Comparator & Serializable) (c1, c2) -> { - int res = first.compare(c1, c2); - return (res != 0) ? res : second.compare(c1, c2); - }; - } + @Override + public int compare(T a, T b) { + if (a == null) { + return (b == null) ? 0 : (nullFirst ? -1 : 1); + } else if (b == null) { + return nullFirst ? 1: -1; + } else { + return (real == null) ? 0 : real.compare(a, b); + } + } - /** - * Constructs a {@link BinaryOperator} which returns the lesser of two elements - * according to the specified {@code Comparator} - * - * @param comparator A {@code Comparator} for comparing the two values - * @param the type of the elements to be compared - * @return a {@code BinaryOperator} which returns the lesser of its operands, - * according to the supplied {@code Comparator} - */ - public static BinaryOperator lesserOf(Comparator comparator) { - Objects.requireNonNull(comparator); - return (a, b) -> comparator.compare(a, b) <= 0 ? a : b; - } + @Override + public Comparator thenComparing(Comparator other) { + Objects.requireNonNull(other); + return new NullComparator(nullFirst, real == null ? other : real.thenComparing(other)); + } - /** - * Constructs a {@link BinaryOperator} which returns the greater of two elements - * according to the specified {@code Comparator} - * - * @param comparator A {@code Comparator} for comparing the two values - * @param the type of the elements to be compared - * @return a {@code BinaryOperator} which returns the greater of its operands, - * according to the supplied {@code Comparator} - */ - public static BinaryOperator greaterOf(Comparator comparator) { - Objects.requireNonNull(comparator); - return (a, b) -> comparator.compare(a, b) >= 0 ? a : b; + @Override + public Comparator reversed() { + return new NullComparator(!nullFirst, real == null ? null : real.reversed()); + } } } diff --git a/src/share/classes/java/util/Map.java b/src/share/classes/java/util/Map.java index bfb72d7f10b953a5e26aea241a3995f673acc5e0..8ad16ee8323359c562f3f4aee4ea55a0eec93aca 100644 --- a/src/share/classes/java/util/Map.java +++ b/src/share/classes/java/util/Map.java @@ -28,6 +28,7 @@ package java.util; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Function; +import java.io.Serializable; /** * An object that maps keys to values. A map cannot contain duplicate keys; @@ -446,6 +447,74 @@ public interface Map { * @see #equals(Object) */ int hashCode(); + + /** + * Returns a comparator that compares {@link Map.Entry} in natural order on key. + * + *

    The returned comparator is serializable and throws {@link + * NullPointerException} when comparing an entry with a null key. + * + * @param the {@link Comparable} type of then map keys + * @param the type of the map values + * @return a comparator that compares {@link Map.Entry} in natural order on key. + * @see Comparable + */ + public static , V> Comparator> comparingByKey() { + return (Comparator> & Serializable) + (c1, c2) -> c1.getKey().compareTo(c2.getKey()); + } + + /** + * Returns a comparator that compares {@link Map.Entry} in natural order on value. + * + *

    The returned comparator is serializable and throws {@link + * NullPointerException} when comparing an entry with null values. + * + * @param the type of the map keys + * @param the {@link Comparable} type of the map values + * @return a comparator that compares {@link Map.Entry} in natural order on value. + * @see Comparable + */ + public static > Comparator> comparingByValue() { + return (Comparator> & Serializable) + (c1, c2) -> c1.getValue().compareTo(c2.getValue()); + } + + /** + * Returns a comparator that compares {@link Map.Entry} by key using the given + * {@link Comparator}. + * + *

    The returned comparator is serializable if the specified comparator + * is also serializable. + * + * @param the type of the map keys + * @param the type of the map values + * @param cmp the key {@link Comparator} + * @return a comparator that compares {@link Map.Entry} by the key. + */ + public static Comparator> comparingByKey(Comparator cmp) { + Objects.requireNonNull(cmp); + return (Comparator> & Serializable) + (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey()); + } + + /** + * Returns a comparator that compares {@link Map.Entry} by value using the given + * {@link Comparator}. + * + *

    The returned comparator is serializable if the specified comparator + * is also serializable. + * + * @param the type of the map keys + * @param the type of the map values + * @param cmp the value {@link Comparator} + * @return a comparator that compares {@link Map.Entry} by the value. + */ + public static Comparator> comparingByValue(Comparator cmp) { + Objects.requireNonNull(cmp); + return (Comparator> & Serializable) + (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue()); + } } // Comparison and hashing diff --git a/src/share/classes/java/util/Properties.java b/src/share/classes/java/util/Properties.java index 3e899d0011318fc4406318e9808ef81f5f093816..ed0bf857d66d45780a4c7aff44617e2bfbc8ae95 100644 --- a/src/share/classes/java/util/Properties.java +++ b/src/share/classes/java/util/Properties.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -443,6 +443,9 @@ class Properties extends Hashtable { if (len == 0 || isCommentLine) { return -1; } + if (precedingBackslash) { + len--; + } return len; } } @@ -510,6 +513,9 @@ class Properties extends Hashtable { :inStream.read(inByteBuf); inOff = 0; if (inLimit <= 0) { + if (precedingBackslash) { + len--; + } return len; } } diff --git a/src/share/classes/java/util/TreeMap.java b/src/share/classes/java/util/TreeMap.java index f34832c85a4d90b246eba8b72ea0dc31216bc1a6..44d7449e07a394ec39a2d8428f9fd146f1c1120a 100644 --- a/src/share/classes/java/util/TreeMap.java +++ b/src/share/classes/java/util/TreeMap.java @@ -2938,13 +2938,13 @@ public class TreeMap public int characteristics() { return (side == 0 ? Spliterator.SIZED : 0) | - Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED; + Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED; } @Override public Comparator> getComparator() { return tree.comparator != null ? - Comparators.byKey(tree.comparator) : null; + Map.Entry.comparingByKey(tree.comparator) : null; } } } diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicBoolean.java b/src/share/classes/java/util/concurrent/atomic/AtomicBoolean.java index 04bc975f9c8c14e595b6aa1806424e4fa0033d4a..bb2dd42e7305e9bc1e598d899f1e7b2fabc4d7db 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicBoolean.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicBoolean.java @@ -92,7 +92,7 @@ public class AtomicBoolean implements java.io.Serializable { * * @param expect the expected value * @param update the new value - * @return true if successful. False return indicates that + * @return {@code true} if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(boolean expect, boolean update) { @@ -105,13 +105,13 @@ public class AtomicBoolean implements java.io.Serializable { * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * - *

    May fail spuriously - * and does not provide ordering guarantees, so is only rarely an - * appropriate alternative to {@code compareAndSet}. + *

    May fail + * spuriously and does not provide ordering guarantees, so is + * only rarely an appropriate alternative to {@code compareAndSet}. * * @param expect the expected value * @param update the new value - * @return true if successful + * @return {@code true} if successful */ public boolean weakCompareAndSet(boolean expect, boolean update) { int e = expect ? 1 : 0; diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicInteger.java b/src/share/classes/java/util/concurrent/atomic/AtomicInteger.java index 8fed658a54c6da33a765ce7b9fe465fb7acd8d6b..c67e42f3bf10a838616143594b658587a8f16c85 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicInteger.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicInteger.java @@ -126,7 +126,7 @@ public class AtomicInteger extends Number implements java.io.Serializable { * * @param expect the expected value * @param update the new value - * @return true if successful. False return indicates that + * @return {@code true} if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(int expect, int update) { @@ -137,13 +137,13 @@ public class AtomicInteger extends Number implements java.io.Serializable { * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * - *

    May fail spuriously - * and does not provide ordering guarantees, so is only rarely an - * appropriate alternative to {@code compareAndSet}. + *

    May fail + * spuriously and does not provide ordering guarantees, so is + * only rarely an appropriate alternative to {@code compareAndSet}. * * @param expect the expected value * @param update the new value - * @return true if successful + * @return {@code true} if successful */ public final boolean weakCompareAndSet(int expect, int update) { return unsafe.compareAndSwapInt(this, valueOffset, expect, update); @@ -155,7 +155,7 @@ public class AtomicInteger extends Number implements java.io.Serializable { * @return the previous value */ public final int getAndIncrement() { - return getAndAdd(1); + return unsafe.getAndAddInt(this, valueOffset, 1); } /** @@ -164,7 +164,7 @@ public class AtomicInteger extends Number implements java.io.Serializable { * @return the previous value */ public final int getAndDecrement() { - return getAndAdd(-1); + return unsafe.getAndAddInt(this, valueOffset, -1); } /** @@ -183,7 +183,7 @@ public class AtomicInteger extends Number implements java.io.Serializable { * @return the updated value */ public final int incrementAndGet() { - return getAndAdd(1) + 1; + return unsafe.getAndAddInt(this, valueOffset, 1) + 1; } /** @@ -192,7 +192,7 @@ public class AtomicInteger extends Number implements java.io.Serializable { * @return the updated value */ public final int decrementAndGet() { - return getAndAdd(-1) - 1; + return unsafe.getAndAddInt(this, valueOffset, -1) - 1; } /** @@ -202,7 +202,7 @@ public class AtomicInteger extends Number implements java.io.Serializable { * @return the updated value */ public final int addAndGet(int delta) { - return getAndAdd(delta) + delta; + return unsafe.getAndAddInt(this, valueOffset, delta) + delta; } /** diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicIntegerArray.java b/src/share/classes/java/util/concurrent/atomic/AtomicIntegerArray.java index 7c259fee06f96d2f52bfdf713b8be3194d71c478..3cbf3f4b44628ba17b76e3f4e6f55d7b49ca16a9 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicIntegerArray.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicIntegerArray.java @@ -157,7 +157,7 @@ public class AtomicIntegerArray implements java.io.Serializable { * @param i the index * @param expect the expected value * @param update the new value - * @return true if successful. False return indicates that + * @return {@code true} if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(int i, int expect, int update) { @@ -172,14 +172,14 @@ public class AtomicIntegerArray implements java.io.Serializable { * Atomically sets the element at position {@code i} to the given * updated value if the current value {@code ==} the expected value. * - *

    May fail spuriously - * and does not provide ordering guarantees, so is only rarely an - * appropriate alternative to {@code compareAndSet}. + *

    May fail + * spuriously and does not provide ordering guarantees, so is + * only rarely an appropriate alternative to {@code compareAndSet}. * * @param i the index * @param expect the expected value * @param update the new value - * @return true if successful + * @return {@code true} if successful */ public final boolean weakCompareAndSet(int i, int expect, int update) { return compareAndSet(i, expect, update); @@ -247,6 +247,7 @@ public class AtomicIntegerArray implements java.io.Serializable { return getAndAdd(i, delta) + delta; } + /** * Atomically updates the element at index {@code i} with the results * of applying the given function, returning the previous value. The diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java b/src/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java index e761b6ec73d63ca286b5c31f799aa39f97f8547f..af72a4755d4ebea0303e5ac5446957b75164d72b 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java @@ -37,14 +37,13 @@ package java.util.concurrent.atomic; import java.util.function.IntUnaryOperator; import java.util.function.IntBinaryOperator; import sun.misc.Unsafe; -import sun.reflect.CallerSensitive; -import sun.reflect.Reflection; - import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; +import sun.reflect.CallerSensitive; +import sun.reflect.Reflection; /** * A reflection-based utility that enables atomic updates to @@ -81,8 +80,10 @@ public abstract class AtomicIntegerFieldUpdater { * access control */ @CallerSensitive - public static AtomicIntegerFieldUpdater newUpdater(Class tclass, String fieldName) { - return new AtomicIntegerFieldUpdaterImpl(tclass, fieldName, Reflection.getCallerClass()); + public static AtomicIntegerFieldUpdater newUpdater(Class tclass, + String fieldName) { + return new AtomicIntegerFieldUpdaterImpl + (tclass, fieldName, Reflection.getCallerClass()); } /** @@ -101,7 +102,7 @@ public abstract class AtomicIntegerFieldUpdater { * @param obj An object whose field to conditionally set * @param expect the expected value * @param update the new value - * @return true if successful + * @return {@code true} if successful * @throws ClassCastException if {@code obj} is not an instance * of the class possessing the field established in the constructor */ @@ -114,14 +115,14 @@ public abstract class AtomicIntegerFieldUpdater { * other calls to {@code compareAndSet} and {@code set}, but not * necessarily with respect to other changes in the field. * - *

    May fail spuriously - * and does not provide ordering guarantees, so is only rarely an - * appropriate alternative to {@code compareAndSet}. + *

    May fail + * spuriously and does not provide ordering guarantees, so is + * only rarely an appropriate alternative to {@code compareAndSet}. * * @param obj An object whose field to conditionally set * @param expect the expected value * @param update the new value - * @return true if successful + * @return {@code true} if successful * @throws ClassCastException if {@code obj} is not an instance * of the class possessing the field established in the constructor */ @@ -363,7 +364,8 @@ public abstract class AtomicIntegerFieldUpdater { /** * Standard hotspot implementation using intrinsics */ - private static class AtomicIntegerFieldUpdaterImpl extends AtomicIntegerFieldUpdater { + private static class AtomicIntegerFieldUpdaterImpl + extends AtomicIntegerFieldUpdater { private static final Unsafe unsafe = Unsafe.getUnsafe(); private final long offset; private final Class tclass; @@ -371,8 +373,7 @@ public abstract class AtomicIntegerFieldUpdater { AtomicIntegerFieldUpdaterImpl(final Class tclass, final String fieldName, - final Class caller) - { + final Class caller) { final Field field; final int modifiers; try { diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicLong.java b/src/share/classes/java/util/concurrent/atomic/AtomicLong.java index 35af7759ac75b6849b102cdb01a73621d6c9cf7d..85ea910a96ca66e021c0d94b8809d6d3de9446f6 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicLong.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicLong.java @@ -140,7 +140,7 @@ public class AtomicLong extends Number implements java.io.Serializable { * * @param expect the expected value * @param update the new value - * @return true if successful. False return indicates that + * @return {@code true} if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(long expect, long update) { @@ -151,13 +151,13 @@ public class AtomicLong extends Number implements java.io.Serializable { * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * - *

    May fail spuriously - * and does not provide ordering guarantees, so is only rarely an - * appropriate alternative to {@code compareAndSet}. + *

    May fail + * spuriously and does not provide ordering guarantees, so is + * only rarely an appropriate alternative to {@code compareAndSet}. * * @param expect the expected value * @param update the new value - * @return true if successful + * @return {@code true} if successful */ public final boolean weakCompareAndSet(long expect, long update) { return unsafe.compareAndSwapLong(this, valueOffset, expect, update); @@ -169,7 +169,7 @@ public class AtomicLong extends Number implements java.io.Serializable { * @return the previous value */ public final long getAndIncrement() { - return getAndAdd(1); + return unsafe.getAndAddLong(this, valueOffset, 1L); } /** @@ -178,7 +178,7 @@ public class AtomicLong extends Number implements java.io.Serializable { * @return the previous value */ public final long getAndDecrement() { - return getAndAdd(-1); + return unsafe.getAndAddLong(this, valueOffset, -1L); } /** @@ -197,7 +197,7 @@ public class AtomicLong extends Number implements java.io.Serializable { * @return the updated value */ public final long incrementAndGet() { - return getAndAdd(1) + 1; + return unsafe.getAndAddLong(this, valueOffset, 1L) + 1L; } /** @@ -206,7 +206,7 @@ public class AtomicLong extends Number implements java.io.Serializable { * @return the updated value */ public final long decrementAndGet() { - return getAndAdd(-1) - 1; + return unsafe.getAndAddLong(this, valueOffset, -1L) - 1L; } /** @@ -216,7 +216,7 @@ public class AtomicLong extends Number implements java.io.Serializable { * @return the updated value */ public final long addAndGet(long delta) { - return getAndAdd(delta) + delta; + return unsafe.getAndAddLong(this, valueOffset, delta) + delta; } /** diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicLongArray.java b/src/share/classes/java/util/concurrent/atomic/AtomicLongArray.java index 216479abecae38b061f97380326a32a38ecf96e3..bf7aa6ecca805cfd741d17682a914795395dbdfd 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicLongArray.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicLongArray.java @@ -156,7 +156,7 @@ public class AtomicLongArray implements java.io.Serializable { * @param i the index * @param expect the expected value * @param update the new value - * @return true if successful. False return indicates that + * @return {@code true} if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(int i, long expect, long update) { @@ -171,14 +171,14 @@ public class AtomicLongArray implements java.io.Serializable { * Atomically sets the element at position {@code i} to the given * updated value if the current value {@code ==} the expected value. * - *

    May fail spuriously - * and does not provide ordering guarantees, so is only rarely an - * appropriate alternative to {@code compareAndSet}. + *

    May fail + * spuriously and does not provide ordering guarantees, so is + * only rarely an appropriate alternative to {@code compareAndSet}. * * @param i the index * @param expect the expected value * @param update the new value - * @return true if successful + * @return {@code true} if successful */ public final boolean weakCompareAndSet(int i, long expect, long update) { return compareAndSet(i, expect, update); diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java b/src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java index 7ac0e73d60122b688dbc93b69916cec6dbc7b84e..9a298d64931fe53c5f6403ae2f1f007cf693270d 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java @@ -37,14 +37,13 @@ package java.util.concurrent.atomic; import java.util.function.LongUnaryOperator; import java.util.function.LongBinaryOperator; import sun.misc.Unsafe; -import sun.reflect.CallerSensitive; -import sun.reflect.Reflection; - import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; +import sun.reflect.CallerSensitive; +import sun.reflect.Reflection; /** * A reflection-based utility that enables atomic updates to @@ -71,17 +70,18 @@ public abstract class AtomicLongFieldUpdater { * generic types match. * * @param tclass the class of the objects holding the field - * @param fieldName the name of the field to be updated. + * @param fieldName the name of the field to be updated * @return the updater * @throws IllegalArgumentException if the field is not a - * volatile long type. + * volatile long type * @throws RuntimeException with a nested reflection-based * exception if the class does not hold field or is the wrong type, * or the field is inaccessible to the caller according to Java language * access control */ @CallerSensitive - public static AtomicLongFieldUpdater newUpdater(Class tclass, String fieldName) { + public static AtomicLongFieldUpdater newUpdater(Class tclass, + String fieldName) { Class caller = Reflection.getCallerClass(); if (AtomicLong.VM_SUPPORTS_LONG_CAS) return new CASUpdater(tclass, fieldName, caller); @@ -105,9 +105,9 @@ public abstract class AtomicLongFieldUpdater { * @param obj An object whose field to conditionally set * @param expect the expected value * @param update the new value - * @return true if successful + * @return {@code true} if successful * @throws ClassCastException if {@code obj} is not an instance - * of the class possessing the field established in the constructor. + * of the class possessing the field established in the constructor */ public abstract boolean compareAndSet(T obj, long expect, long update); @@ -118,16 +118,16 @@ public abstract class AtomicLongFieldUpdater { * other calls to {@code compareAndSet} and {@code set}, but not * necessarily with respect to other changes in the field. * - *

    May fail spuriously - * and does not provide ordering guarantees, so is only rarely an - * appropriate alternative to {@code compareAndSet}. + *

    May fail + * spuriously and does not provide ordering guarantees, so is + * only rarely an appropriate alternative to {@code compareAndSet}. * * @param obj An object whose field to conditionally set * @param expect the expected value * @param update the new value - * @return true if successful + * @return {@code true} if successful * @throws ClassCastException if {@code obj} is not an instance - * of the class possessing the field established in the constructor. + * of the class possessing the field established in the constructor */ public abstract boolean weakCompareAndSet(T obj, long expect, long update); @@ -370,7 +370,8 @@ public abstract class AtomicLongFieldUpdater { private final Class tclass; private final Class cclass; - CASUpdater(final Class tclass, final String fieldName, final Class caller) { + CASUpdater(final Class tclass, final String fieldName, + final Class caller) { final Field field; final int modifiers; try { @@ -493,7 +494,8 @@ public abstract class AtomicLongFieldUpdater { private final Class tclass; private final Class cclass; - LockedUpdater(final Class tclass, final String fieldName, final Class caller) { + LockedUpdater(final Class tclass, final String fieldName, + final Class caller) { Field field = null; int modifiers = 0; try { diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicMarkableReference.java b/src/share/classes/java/util/concurrent/atomic/AtomicMarkableReference.java index b1dc71dfdce8aa5936d856f00427d65b5ce09ed6..f7becccb13a509c3db8a09ae2256116e09ec1b49 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicMarkableReference.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicMarkableReference.java @@ -112,15 +112,15 @@ public class AtomicMarkableReference { * current reference is {@code ==} to the expected reference * and the current mark is equal to the expected mark. * - *

    May fail spuriously - * and does not provide ordering guarantees, so is only rarely an - * appropriate alternative to {@code compareAndSet}. + *

    May fail + * spuriously and does not provide ordering guarantees, so is + * only rarely an appropriate alternative to {@code compareAndSet}. * * @param expectedReference the expected value of the reference * @param newReference the new value for the reference * @param expectedMark the expected value of the mark * @param newMark the new value for the mark - * @return true if successful + * @return {@code true} if successful */ public boolean weakCompareAndSet(V expectedReference, V newReference, @@ -140,7 +140,7 @@ public class AtomicMarkableReference { * @param newReference the new value for the reference * @param expectedMark the expected value of the mark * @param newMark the new value for the mark - * @return true if successful + * @return {@code true} if successful */ public boolean compareAndSet(V expectedReference, V newReference, @@ -178,7 +178,7 @@ public class AtomicMarkableReference { * * @param expectedReference the expected value of the reference * @param newMark the new value for the mark - * @return true if successful + * @return {@code true} if successful */ public boolean attemptMark(V expectedReference, boolean newMark) { Pair current = pair; diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicReference.java b/src/share/classes/java/util/concurrent/atomic/AtomicReference.java index ddce0734300675e87a725e76ec9897a5618b7e0a..04fbe52effa293be52aaddd561754812c9701322 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicReference.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicReference.java @@ -109,7 +109,7 @@ public class AtomicReference implements java.io.Serializable { * if the current value {@code ==} the expected value. * @param expect the expected value * @param update the new value - * @return true if successful. False return indicates that + * @return {@code true} if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(V expect, V update) { @@ -120,13 +120,13 @@ public class AtomicReference implements java.io.Serializable { * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * - *

    May fail spuriously - * and does not provide ordering guarantees, so is only rarely an - * appropriate alternative to {@code compareAndSet}. + *

    May fail + * spuriously and does not provide ordering guarantees, so is + * only rarely an appropriate alternative to {@code compareAndSet}. * * @param expect the expected value * @param update the new value - * @return true if successful + * @return {@code true} if successful */ public final boolean weakCompareAndSet(V expect, V update) { return unsafe.compareAndSwapObject(this, valueOffset, expect, update); diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicReferenceArray.java b/src/share/classes/java/util/concurrent/atomic/AtomicReferenceArray.java index f8787ba1d405e8d64d4853bc6c892e9c96ca4120..4500bdf2fcbfecaaf1c1913edb8a144e7dad5278 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicReferenceArray.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicReferenceArray.java @@ -34,10 +34,9 @@ */ package java.util.concurrent.atomic; - -import java.util.Arrays; import java.util.function.UnaryOperator; import java.util.function.BinaryOperator; +import java.util.Arrays; import java.lang.reflect.Array; import sun.misc.Unsafe; @@ -60,19 +59,18 @@ public class AtomicReferenceArray implements java.io.Serializable { private final Object[] array; // must have exact type Object[] static { - int scale; try { unsafe = Unsafe.getUnsafe(); arrayFieldOffset = unsafe.objectFieldOffset (AtomicReferenceArray.class.getDeclaredField("array")); base = unsafe.arrayBaseOffset(Object[].class); - scale = unsafe.arrayIndexScale(Object[].class); + int scale = unsafe.arrayIndexScale(Object[].class); + if ((scale & (scale - 1)) != 0) + throw new Error("data type scale not a power of two"); + shift = 31 - Integer.numberOfLeadingZeros(scale); } catch (Exception e) { throw new Error(e); } - if ((scale & (scale - 1)) != 0) - throw new Error("data type scale not a power of two"); - shift = 31 - Integer.numberOfLeadingZeros(scale); } private long checkedByteOffset(int i) { @@ -173,7 +171,7 @@ public class AtomicReferenceArray implements java.io.Serializable { * @param i the index * @param expect the expected value * @param update the new value - * @return true if successful. False return indicates that + * @return {@code true} if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(int i, E expect, E update) { @@ -188,20 +186,20 @@ public class AtomicReferenceArray implements java.io.Serializable { * Atomically sets the element at position {@code i} to the given * updated value if the current value {@code ==} the expected value. * - *

    May fail spuriously - * and does not provide ordering guarantees, so is only rarely an - * appropriate alternative to {@code compareAndSet}. + *

    May fail + * spuriously and does not provide ordering guarantees, so is + * only rarely an appropriate alternative to {@code compareAndSet}. * * @param i the index * @param expect the expected value * @param update the new value - * @return true if successful + * @return {@code true} if successful */ public final boolean weakCompareAndSet(int i, E expect, E update) { return compareAndSet(i, expect, update); } - /** + /** * Atomically updates the element at index {@code i} with the results * of applying the given function, returning the previous value. The * function should be side-effect-free, since it may be re-applied diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java b/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java index 2cd0e1df369db537b948dbe8c802dbf1e6b98343..901b71c9d2b45152c22ce153ee2f337fcdffce3e 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java @@ -37,14 +37,13 @@ package java.util.concurrent.atomic; import java.util.function.UnaryOperator; import java.util.function.BinaryOperator; import sun.misc.Unsafe; -import sun.reflect.CallerSensitive; -import sun.reflect.Reflection; - import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; +import sun.reflect.CallerSensitive; +import sun.reflect.Reflection; /** * A reflection-based utility that enables atomic updates to @@ -82,29 +81,30 @@ import java.security.PrivilegedActionException; * @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. * The Class arguments are needed to check that reflective types and * generic types match. * - * @param tclass the class of the objects holding the field. + * @param tclass the class of the objects holding the field * @param vclass the class of the field - * @param fieldName the name of the field to be updated. + * @param fieldName the name of the field to be updated * @return the updater - * @throws IllegalArgumentException if the field is not a volatile reference type. + * @throws ClassCastException if the field is of the wrong type + * @throws IllegalArgumentException if the field is not volatile * @throws RuntimeException with a nested reflection-based * exception if the class does not hold field or is the wrong type, * or the field is inaccessible to the caller according to Java language * access control */ @CallerSensitive - public static AtomicReferenceFieldUpdater newUpdater(Class tclass, Class vclass, String fieldName) { - return new AtomicReferenceFieldUpdaterImpl(tclass, - vclass, - fieldName, - Reflection.getCallerClass()); + public static AtomicReferenceFieldUpdater newUpdater(Class tclass, + Class vclass, + String fieldName) { + return new AtomicReferenceFieldUpdaterImpl + (tclass, vclass, fieldName, Reflection.getCallerClass()); } /** @@ -123,7 +123,7 @@ public abstract class AtomicReferenceFieldUpdater { * @param obj An object whose field to conditionally set * @param expect the expected value * @param update the new value - * @return true if successful + * @return {@code true} if successful */ public abstract boolean compareAndSet(T obj, V expect, V update); @@ -134,14 +134,14 @@ public abstract class AtomicReferenceFieldUpdater { * other calls to {@code compareAndSet} and {@code set}, but not * necessarily with respect to other changes in the field. * - *

    May fail spuriously - * and does not provide ordering guarantees, so is only rarely an - * appropriate alternative to {@code compareAndSet}. + *

    May fail + * spuriously and does not provide ordering guarantees, so is + * only rarely an appropriate alternative to {@code compareAndSet}. * * @param obj An object whose field to conditionally set * @param expect the expected value * @param update the new value - * @return true if successful + * @return {@code true} if successful */ public abstract boolean weakCompareAndSet(T obj, V expect, V update); @@ -301,10 +301,9 @@ public abstract class AtomicReferenceFieldUpdater { */ AtomicReferenceFieldUpdaterImpl(final Class tclass, - Class vclass, + final Class vclass, final String fieldName, - final Class caller) - { + final Class caller) { final Field field; final Class fieldClass; final int modifiers; diff --git a/src/share/classes/java/util/concurrent/atomic/AtomicStampedReference.java b/src/share/classes/java/util/concurrent/atomic/AtomicStampedReference.java index 5f8f1a03db92b3b2eb956c1a72cd00741f78f7e4..56feb2febe718571074bac291f252cb4094efa61 100644 --- a/src/share/classes/java/util/concurrent/atomic/AtomicStampedReference.java +++ b/src/share/classes/java/util/concurrent/atomic/AtomicStampedReference.java @@ -112,15 +112,15 @@ public class AtomicStampedReference { * current reference is {@code ==} to the expected reference * and the current stamp is equal to the expected stamp. * - *

    May fail spuriously - * and does not provide ordering guarantees, so is only rarely an - * appropriate alternative to {@code compareAndSet}. + *

    May fail + * spuriously and does not provide ordering guarantees, so is + * only rarely an appropriate alternative to {@code compareAndSet}. * * @param expectedReference the expected value of the reference * @param newReference the new value for the reference * @param expectedStamp the expected value of the stamp * @param newStamp the new value for the stamp - * @return true if successful + * @return {@code true} if successful */ public boolean weakCompareAndSet(V expectedReference, V newReference, @@ -140,7 +140,7 @@ public class AtomicStampedReference { * @param newReference the new value for the reference * @param expectedStamp the expected value of the stamp * @param newStamp the new value for the stamp - * @return true if successful + * @return {@code true} if successful */ public boolean compareAndSet(V expectedReference, V newReference, @@ -178,7 +178,7 @@ public class AtomicStampedReference { * * @param expectedReference the expected value of the reference * @param newStamp the new value for the stamp - * @return true if successful + * @return {@code true} if successful */ public boolean attemptStamp(V expectedReference, int newStamp) { Pair current = pair; diff --git a/src/share/classes/java/util/concurrent/atomic/DoubleAccumulator.java b/src/share/classes/java/util/concurrent/atomic/DoubleAccumulator.java index 277f185f8693d51bccce260aa7257844ac432126..841f6477d46cffbd6713c8df3d03020913d230d4 100644 --- a/src/share/classes/java/util/concurrent/atomic/DoubleAccumulator.java +++ b/src/share/classes/java/util/concurrent/atomic/DoubleAccumulator.java @@ -65,7 +65,7 @@ import java.util.function.DoubleBinaryOperator; *

    Class {@link DoubleAdder} provides analogs of the functionality * of this class for the common special case of maintaining sums. The * call {@code new DoubleAdder()} is equivalent to {@code new - * DoubleAccumulator((x, y) -> x + y, 0.0}. + * DoubleAccumulator((x, y) -> x + y, 0.0)}. * *

    This class extends {@link Number}, but does not define * methods such as {@code equals}, {@code hashCode} and {@code @@ -84,11 +84,13 @@ public class DoubleAccumulator extends Striped64 implements Serializable { /** * Creates a new instance using the given accumulator function * and identity element. + * @param accumulatorFunction a side-effect-free function of two arguments + * @param identity identity (initial value) for the accumulator function */ public DoubleAccumulator(DoubleBinaryOperator accumulatorFunction, double identity) { this.function = accumulatorFunction; - base = this.identity = Double.doubleToRawLongBits(identity); + base = this.identity = Double.doubleToRawLongBits(identity); } /** diff --git a/src/share/classes/java/util/concurrent/atomic/DoubleAdder.java b/src/share/classes/java/util/concurrent/atomic/DoubleAdder.java index 30ff552747d1aab121b3e26007f9ea65f7a4864b..2db7ca89c597d5adbd8e8f691fc81ce2696f3448 100644 --- a/src/share/classes/java/util/concurrent/atomic/DoubleAdder.java +++ b/src/share/classes/java/util/concurrent/atomic/DoubleAdder.java @@ -63,7 +63,7 @@ import java.io.Serializable; public class DoubleAdder extends Striped64 implements Serializable { private static final long serialVersionUID = 7249069246863182397L; - /** + /* * Note that we must use "long" for underlying representations, * because there is no compareAndSet for double, due to the fact * that the bitwise equals used in any CAS implementation is not diff --git a/src/share/classes/java/util/concurrent/atomic/LongAccumulator.java b/src/share/classes/java/util/concurrent/atomic/LongAccumulator.java index bfddcd3dcbda754a4e167b09da7338e68d868c7b..1289e6b52cf7c8e922fc0308b3118dc75e84fe9d 100644 --- a/src/share/classes/java/util/concurrent/atomic/LongAccumulator.java +++ b/src/share/classes/java/util/concurrent/atomic/LongAccumulator.java @@ -86,6 +86,8 @@ public class LongAccumulator extends Striped64 implements Serializable { /** * Creates a new instance using the given accumulator function * and identity element. + * @param accumulatorFunction a side-effect-free function of two arguments + * @param identity identity (initial value) for the accumulator function */ public LongAccumulator(LongBinaryOperator accumulatorFunction, long identity) { diff --git a/src/share/classes/java/util/concurrent/atomic/Striped64.java b/src/share/classes/java/util/concurrent/atomic/Striped64.java index 708b4c2574feb68235990f3f5e473a19f24df830..16dcb4da6cca23a9cf5131e5745d5380da83ff73 100644 --- a/src/share/classes/java/util/concurrent/atomic/Striped64.java +++ b/src/share/classes/java/util/concurrent/atomic/Striped64.java @@ -52,13 +52,13 @@ abstract class Striped64 extends Number { * accessed directly by subclasses. * * Table entries are of class Cell; a variant of AtomicLong padded - * to reduce cache contention on most processors. Padding is - * overkill for most Atomics because they are usually irregularly - * scattered in memory and thus don't interfere much with each - * other. But Atomic objects residing in arrays will tend to be - * placed adjacent to each other, and so will most often share - * cache lines (with a huge negative performance impact) without - * this precaution. + * (via @sun.misc.Contended) to reduce cache contention. Padding + * is overkill for most Atomics because they are usually + * irregularly scattered in memory and thus don't interfere much + * with each other. But Atomic objects residing in arrays will + * tend to be placed adjacent to each other, and so will most + * often share cache lines (with a huge negative performance + * impact) without this precaution. * * In part because Cells are relatively large, we avoid creating * them until they are needed. When there is no contention, all @@ -112,18 +112,13 @@ abstract class Striped64 extends Number { /** * Padded variant of AtomicLong supporting only raw accesses plus CAS. - * The value field is placed between pads, hoping that the JVM doesn't - * reorder them. * * JVM intrinsics note: It would be possible to use a release-only * form of CAS here, if it were provided. */ - static final class Cell { - volatile long p0, p1, p2, p3, p4, p5, p6; + @sun.misc.Contended static final class Cell { volatile long value; - volatile long q0, q1, q2, q3, q4, q5, q6; Cell(long x) { value = x; } - final boolean cas(long cmp, long val) { return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val); } diff --git a/src/share/classes/java/util/concurrent/atomic/package-info.java b/src/share/classes/java/util/concurrent/atomic/package-info.java index 5cc259562551ce4e0e794d7199f07ed5df67817e..ce497eb53b938f65f049a049700e280d4e534a42 100644 --- a/src/share/classes/java/util/concurrent/atomic/package-info.java +++ b/src/share/classes/java/util/concurrent/atomic/package-info.java @@ -84,19 +84,18 @@ * write your utility method as follows: *

     {@code
      * long getAndTransform(AtomicLong var) {
    - *   while (true) {
    - *     long current = var.get();
    - *     long next = transform(current);
    - *     if (var.compareAndSet(current, next))
    - *         return current;
    - *         // return next; for transformAndGet
    - *   }
    + *   long prev, next;
    + *   do {
    + *     prev = var.get();
    + *     next = transform(prev);
    + *   } while (!var.compareAndSet(prev, next));
    + *   return prev; // return next; for transformAndGet
      * }}
    * *

    The memory effects for accesses and updates of atomics generally * follow the rules for volatiles, as stated in - * - * The Java Language Specification, Third Edition (17.4 Memory Model): + * + * The Java Language Specification (17.4 Memory Model): * *

      * @@ -152,13 +151,12 @@ * semantics for their array elements, which is not supported for * ordinary arrays. * - * - *

      The atomic classes also support method {@code weakCompareAndSet}, - * which has limited applicability. On some platforms, the weak version - * may be more efficient than {@code compareAndSet} in the normal case, - * but differs in that any given invocation of the - * {@code weakCompareAndSet} method may return {@code false} - * spuriously (that is, for no apparent reason). A + *

      The atomic classes also support method + * {@code weakCompareAndSet}, which has limited applicability. On some + * platforms, the weak version may be more efficient than {@code + * compareAndSet} in the normal case, but differs in that any given + * invocation of the {@code weakCompareAndSet} method may return {@code + * false} spuriously (that is, for no apparent reason). A * {@code false} return means only that the operation may be retried if * desired, relying on the guarantee that repeated invocation when the * variable holds {@code expectedValue} and no other thread is also @@ -194,7 +192,7 @@ * *

      Atomic classes are not general purpose replacements for * {@code java.lang.Integer} and related classes. They do not - * define methods such as {@code hashCode} and + * define methods such as {@code equals}, {@code hashCode} and * {@code compareTo}. (Because atomic variables are expected to be * mutated, they are poor choices for hash table keys.) Additionally, * classes are provided only for those types that are commonly useful in diff --git a/src/share/classes/java/util/concurrent/locks/AbstractOwnableSynchronizer.java b/src/share/classes/java/util/concurrent/locks/AbstractOwnableSynchronizer.java index 39a51e5a90c6a9b9f4d55bd3a25a6e7e597b4a86..30dec97a6e04d637656a9b3b9c136cdbe88a52dd 100644 --- a/src/share/classes/java/util/concurrent/locks/AbstractOwnableSynchronizer.java +++ b/src/share/classes/java/util/concurrent/locks/AbstractOwnableSynchronizer.java @@ -39,7 +39,7 @@ package java.util.concurrent.locks; * A synchronizer that may be exclusively owned by a thread. This * class provides a basis for creating locks and related synchronizers * that may entail a notion of ownership. The - * AbstractOwnableSynchronizer class itself does not manage or + * {@code AbstractOwnableSynchronizer} class itself does not manage or * use this information. However, subclasses and tools may use * appropriately maintained values to help control and monitor access * and provide diagnostics. @@ -64,20 +64,20 @@ public abstract class AbstractOwnableSynchronizer private transient Thread exclusiveOwnerThread; /** - * Sets the thread that currently owns exclusive access. A - * null argument indicates that no thread owns access. + * Sets the thread that currently owns exclusive access. + * A {@code null} argument indicates that no thread owns access. * This method does not otherwise impose any synchronization or - * volatile field accesses. + * {@code volatile} field accesses. + * @param thread the owner thread */ - protected final void setExclusiveOwnerThread(Thread t) { - exclusiveOwnerThread = t; + protected final void setExclusiveOwnerThread(Thread thread) { + exclusiveOwnerThread = thread; } /** - * Returns the thread last set by - * setExclusiveOwnerThread, or null if never - * set. This method does not otherwise impose any synchronization - * or volatile field accesses. + * Returns the thread last set by {@code setExclusiveOwnerThread}, + * or {@code null} if never set. This method does not otherwise + * impose any synchronization or {@code volatile} field accesses. * @return the owner thread */ protected final Thread getExclusiveOwnerThread() { diff --git a/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java b/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java index 46ad577cf10baa22e07e8c93de2d9071cad8bba2..4d885f443765bb3ae7b7ba047048fd5001c7a6af 100644 --- a/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java +++ b/src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java @@ -42,11 +42,11 @@ import sun.misc.Unsafe; /** * A version of {@link AbstractQueuedSynchronizer} in - * which synchronization state is maintained as a long. + * which synchronization state is maintained as a {@code long}. * This class has exactly the same structure, properties, and methods - * as AbstractQueuedSynchronizer with the exception + * as {@code AbstractQueuedSynchronizer} with the exception * that all state-related parameters and results are defined - * as long rather than int. This class + * as {@code long} rather than {@code int}. This class * may be useful when creating synchronizers such as * multilevel locks and barriers that require * 64 bits of state. @@ -71,7 +71,7 @@ public abstract class AbstractQueuedLongSynchronizer */ /** - * Creates a new AbstractQueuedLongSynchronizer instance + * Creates a new {@code AbstractQueuedLongSynchronizer} instance * with initial synchronization state of zero. */ protected AbstractQueuedLongSynchronizer() { } @@ -104,7 +104,7 @@ public abstract class AbstractQueuedLongSynchronizer * *

      Insertion into a CLH queue requires only a single atomic * operation on "tail", so there is a simple atomic point of - * demarcation from unqueued to queued. Similarly, dequeing + * demarcation from unqueued to queued. Similarly, dequeuing * involves only updating the "head". However, it takes a bit * more work for nodes to determine who their successors are, * in part to deal with possible cancellation due to timeouts @@ -211,7 +211,7 @@ public abstract class AbstractQueuedLongSynchronizer /** * Link to predecessor node that current node/thread relies on - * for checking waitStatus. Assigned during enqueing, and nulled + * for checking waitStatus. Assigned during enqueuing, and nulled * out (for sake of GC) only upon dequeuing. Also, upon * cancellation of a predecessor, we short-circuit while * finding a non-cancelled one, which will always exist @@ -256,7 +256,7 @@ public abstract class AbstractQueuedLongSynchronizer Node nextWaiter; /** - * Returns true if node is waiting in shared mode + * Returns true if node is waiting in shared mode. */ final boolean isShared() { return nextWaiter == SHARED; @@ -312,7 +312,7 @@ public abstract class AbstractQueuedLongSynchronizer /** * Returns the current value of synchronization state. - * This operation has memory semantics of a volatile read. + * This operation has memory semantics of a {@code volatile} read. * @return current state value */ protected final long getState() { @@ -321,7 +321,7 @@ public abstract class AbstractQueuedLongSynchronizer /** * Sets the value of synchronization state. - * This operation has memory semantics of a volatile write. + * This operation has memory semantics of a {@code volatile} write. * @param newState the new state value */ protected final void setState(long newState) { @@ -331,12 +331,12 @@ public abstract class AbstractQueuedLongSynchronizer /** * Atomically sets synchronization state to the given updated * value if the current state value equals the expected value. - * This operation has memory semantics of a volatile read + * This operation has memory semantics of a {@code volatile} read * and write. * * @param expect the expected value * @param update the new value - * @return true if successful. False return indicates that the actual + * @return {@code true} if successful. False return indicates that the actual * value was not equal to the expected value. */ protected final boolean compareAndSetState(long expect, long update) { @@ -441,7 +441,7 @@ public abstract class AbstractQueuedLongSynchronizer } /** - * Release action for shared mode -- signal successor and ensure + * Release action for shared mode -- signals successor and ensures * propagation. (Note: For exclusive mode, release just amounts * to calling unparkSuccessor of head if it needs signal.) */ @@ -562,7 +562,7 @@ public abstract class AbstractQueuedLongSynchronizer /** * Checks and updates status for a node that failed to acquire. * Returns true if thread should block. This is the main signal - * control in all acquire loops. Requires that pred == node.prev + * control in all acquire loops. Requires that pred == node.prev. * * @param pred node's predecessor holding status * @param node the node @@ -1066,7 +1066,7 @@ public abstract class AbstractQueuedLongSynchronizer * thread is queued, possibly repeatedly blocking and unblocking, * invoking {@link #tryAcquireShared} until success or the thread * is interrupted. - * @param arg the acquire argument + * @param arg the acquire argument. * This value is conveyed to {@link #tryAcquireShared} but is * otherwise uninterpreted and can represent anything * you like. @@ -1441,7 +1441,7 @@ public abstract class AbstractQueuedLongSynchronizer * Returns true if successful. * @param node the node * @return true if successfully transferred (else the node was - * cancelled before signal). + * cancelled before signal) */ final boolean transferForSignal(Node node) { /* @@ -1464,11 +1464,10 @@ public abstract class AbstractQueuedLongSynchronizer } /** - * Transfers node, if necessary, to sync queue after a cancelled - * wait. Returns true if thread was cancelled before being - * signalled. - * @param current the waiting thread - * @param node its node + * Transfers node, if necessary, to sync queue after a cancelled wait. + * Returns true if thread was cancelled before being signalled. + * + * @param node the node * @return true if cancelled before the node was signalled */ final boolean transferAfterCancelledWait(Node node) { @@ -1516,7 +1515,7 @@ public abstract class AbstractQueuedLongSynchronizer * uses this synchronizer as its lock. * * @param condition the condition - * @return true if owned + * @return {@code true} if owned * @throws NullPointerException if the condition is null */ public final boolean owns(ConditionObject condition) { @@ -1526,13 +1525,13 @@ public abstract class AbstractQueuedLongSynchronizer /** * Queries whether any threads are waiting on the given condition * associated with this synchronizer. Note that because timeouts - * and interrupts may occur at any time, a true return - * does not guarantee that a future signal will awaken + * and interrupts may occur at any time, a {@code true} return + * does not guarantee that a future {@code signal} will awaken * any threads. This method is designed primarily for use in * monitoring of the system state. * * @param condition the condition - * @return true if there are any waiting threads + * @return {@code true} if there are any waiting threads * @throws IllegalMonitorStateException if exclusive synchronization * is not held * @throws IllegalArgumentException if the given condition is @@ -1599,7 +1598,7 @@ public abstract class AbstractQueuedLongSynchronizer * and Condition users. Exported versions of this class will in * general need to be accompanied by documentation describing * condition semantics that rely on those of the associated - * AbstractQueuedLongSynchronizer. + * {@code AbstractQueuedLongSynchronizer}. * *

      This class is Serializable, but all fields are transient, * so deserialized conditions have no waiters. @@ -1614,7 +1613,7 @@ public abstract class AbstractQueuedLongSynchronizer private transient Node lastWaiter; /** - * Creates a new ConditionObject instance. + * Creates a new {@code ConditionObject} instance. */ public ConditionObject() { } @@ -1967,7 +1966,7 @@ public abstract class AbstractQueuedLongSynchronizer /** * Queries whether any threads are waiting on this condition. - * Implements {@link AbstractQueuedLongSynchronizer#hasWaiters}. + * Implements {@link AbstractQueuedLongSynchronizer#hasWaiters(ConditionObject)}. * * @return {@code true} if there are any waiting threads * @throws IllegalMonitorStateException if {@link #isHeldExclusively} @@ -1986,7 +1985,7 @@ public abstract class AbstractQueuedLongSynchronizer /** * Returns an estimate of the number of threads waiting on * this condition. - * Implements {@link AbstractQueuedLongSynchronizer#getWaitQueueLength}. + * Implements {@link AbstractQueuedLongSynchronizer#getWaitQueueLength(ConditionObject)}. * * @return the estimated number of waiting threads * @throws IllegalMonitorStateException if {@link #isHeldExclusively} @@ -2006,7 +2005,7 @@ public abstract class AbstractQueuedLongSynchronizer /** * Returns a collection containing those threads that may be * waiting on this Condition. - * Implements {@link AbstractQueuedLongSynchronizer#getWaitingThreads}. + * Implements {@link AbstractQueuedLongSynchronizer#getWaitingThreads(ConditionObject)}. * * @return the collection of threads * @throws IllegalMonitorStateException if {@link #isHeldExclusively} diff --git a/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java b/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java index 6f39256c0d61aeb73eace6129a1e5cf42928cc81..f0bdeb9030e0b586a7ee528d775a140cea684f02 100644 --- a/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java +++ b/src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java @@ -45,12 +45,12 @@ import sun.misc.Unsafe; * synchronizers (semaphores, events, etc) that rely on * first-in-first-out (FIFO) wait queues. This class is designed to * be a useful basis for most kinds of synchronizers that rely on a - * single atomic int value to represent state. Subclasses + * single atomic {@code int} value to represent state. Subclasses * must define the protected methods that change this state, and which * define what that state means in terms of this object being acquired * or released. Given these, the other methods in this class carry * out all queuing and blocking mechanics. Subclasses can maintain - * other state fields, but only the atomically updated int + * other state fields, but only the atomically updated {@code int} * value manipulated using methods {@link #getState}, {@link * #setState} and {@link #compareAndSetState} is tracked with respect * to synchronization. @@ -58,7 +58,7 @@ import sun.misc.Unsafe; *

      Subclasses should be defined as non-public internal helper * classes that are used to implement the synchronization properties * of their enclosing class. Class - * AbstractQueuedSynchronizer does not implement any + * {@code AbstractQueuedSynchronizer} does not implement any * synchronization interface. Instead it defines methods such as * {@link #acquireInterruptibly} that can be invoked as * appropriate by concrete locks and related synchronizers to @@ -85,7 +85,7 @@ import sun.misc.Unsafe; * invoked with the current {@link #getState} value fully releases * this object, and {@link #acquire}, given this saved state value, * eventually restores this object to its previous acquired state. No - * AbstractQueuedSynchronizer method otherwise creates such a + * {@code AbstractQueuedSynchronizer} method otherwise creates such a * condition, so if this constraint cannot be met, do not use it. The * behavior of {@link ConditionObject} depends of course on the * semantics of its synchronizer implementation. @@ -93,13 +93,13 @@ import sun.misc.Unsafe; *

      This class provides inspection, instrumentation, and monitoring * methods for the internal queue, as well as similar methods for * condition objects. These can be exported as desired into classes - * using an AbstractQueuedSynchronizer for their + * using an {@code AbstractQueuedSynchronizer} for their * synchronization mechanics. * *

      Serialization of this class stores only the underlying atomic * integer maintaining state, so deserialized objects have empty * thread queues. Typical subclasses requiring serializability will - * define a readObject method that restores this to a known + * define a {@code readObject} method that restores this to a known * initial state upon deserialization. * *

      Usage

      @@ -115,14 +115,14 @@ import sun.misc.Unsafe; *
    • {@link #tryAcquireShared} *
    • {@link #tryReleaseShared} *
    • {@link #isHeldExclusively} - *
    + * * * Each of these methods by default throws {@link * UnsupportedOperationException}. Implementations of these methods * must be internally thread-safe, and should in general be short and * not block. Defining these methods is the only supported * means of using this class. All other methods are declared - * final because they cannot be independently varied. + * {@code final} because they cannot be independently varied. * *

    You may also find the inherited methods from {@link * AbstractOwnableSynchronizer} useful to keep track of the thread @@ -148,16 +148,16 @@ import sun.misc.Unsafe; * * (Shared mode is similar but may involve cascading signals.) * - *

    Because checks in acquire are invoked before + *

    Because checks in acquire are invoked before * enqueuing, a newly acquiring thread may barge ahead of * others that are blocked and queued. However, you can, if desired, - * define tryAcquire and/or tryAcquireShared to + * define {@code tryAcquire} and/or {@code tryAcquireShared} to * disable barging by internally invoking one or more of the inspection * methods, thereby providing a fair FIFO acquisition order. - * In particular, most fair synchronizers can define tryAcquire - * to return false if {@link #hasQueuedPredecessors} (a method + * In particular, most fair synchronizers can define {@code tryAcquire} + * to return {@code false} if {@link #hasQueuedPredecessors} (a method * specifically designed to be used by fair synchronizers) returns - * true. Other variations are possible. + * {@code true}. Other variations are possible. * *

    Throughput and scalability are generally highest for the * default barging (also known as greedy, @@ -167,7 +167,7 @@ import sun.misc.Unsafe; * threads, and each recontention has an unbiased chance to succeed * against incoming threads. Also, while acquires do not * "spin" in the usual sense, they may perform multiple - * invocations of tryAcquire interspersed with other + * invocations of {@code tryAcquire} interspersed with other * computations before blocking. This gives most of the benefits of * spins when exclusive synchronization is only briefly held, without * most of the liabilities when it isn't. If so desired, you can @@ -178,7 +178,7 @@ import sun.misc.Unsafe; * *

    This class provides an efficient and scalable basis for * synchronization in part by specializing its range of use to - * synchronizers that can rely on int state, acquire, and + * synchronizers that can rely on {@code int} state, acquire, and * release parameters, and an internal FIFO wait queue. When this does * not suffice, you can build synchronizers from a lower level using * {@link java.util.concurrent.atomic atomic} classes, your own custom @@ -200,12 +200,12 @@ import sun.misc.Unsafe; * * // Our internal helper class * private static class Sync extends AbstractQueuedSynchronizer { - * // Report whether in locked state + * // Reports whether in locked state * protected boolean isHeldExclusively() { * return getState() == 1; * } * - * // Acquire the lock if state is zero + * // Acquires the lock if state is zero * public boolean tryAcquire(int acquires) { * assert acquires == 1; // Otherwise unused * if (compareAndSetState(0, 1)) { @@ -215,7 +215,7 @@ import sun.misc.Unsafe; * return false; * } * - * // Release the lock by setting state to zero + * // Releases the lock by setting state to zero * protected boolean tryRelease(int releases) { * assert releases == 1; // Otherwise unused * if (getState() == 0) throw new IllegalMonitorStateException(); @@ -224,10 +224,10 @@ import sun.misc.Unsafe; * return true; * } * - * // Provide a Condition + * // Provides a Condition * Condition newCondition() { return new ConditionObject(); } * - * // Deserialize properly + * // Deserializes properly * private void readObject(ObjectInputStream s) * throws IOException, ClassNotFoundException { * s.defaultReadObject(); @@ -255,8 +255,8 @@ import sun.misc.Unsafe; * *

    Here is a latch class that is like a * {@link java.util.concurrent.CountDownLatch CountDownLatch} - * except that it only requires a single signal to - * fire. Because a latch is non-exclusive, it uses the shared + * except that it only requires a single {@code signal} to + * fire. Because a latch is non-exclusive, it uses the {@code shared} * acquire and release methods. * *

     {@code
    @@ -293,7 +293,7 @@ public abstract class AbstractQueuedSynchronizer
         private static final long serialVersionUID = 7373984972572414691L;
     
         /**
    -     * Creates a new AbstractQueuedSynchronizer instance
    +     * Creates a new {@code AbstractQueuedSynchronizer} instance
          * with initial synchronization state of zero.
          */
         protected AbstractQueuedSynchronizer() { }
    @@ -326,7 +326,7 @@ public abstract class AbstractQueuedSynchronizer
          *
          * 

    Insertion into a CLH queue requires only a single atomic * operation on "tail", so there is a simple atomic point of - * demarcation from unqueued to queued. Similarly, dequeing + * demarcation from unqueued to queued. Similarly, dequeuing * involves only updating the "head". However, it takes a bit * more work for nodes to determine who their successors are, * in part to deal with possible cancellation due to timeouts @@ -433,7 +433,7 @@ public abstract class AbstractQueuedSynchronizer /** * Link to predecessor node that current node/thread relies on - * for checking waitStatus. Assigned during enqueing, and nulled + * for checking waitStatus. Assigned during enqueuing, and nulled * out (for sake of GC) only upon dequeuing. Also, upon * cancellation of a predecessor, we short-circuit while * finding a non-cancelled one, which will always exist @@ -478,7 +478,7 @@ public abstract class AbstractQueuedSynchronizer Node nextWaiter; /** - * Returns true if node is waiting in shared mode + * Returns true if node is waiting in shared mode. */ final boolean isShared() { return nextWaiter == SHARED; @@ -534,7 +534,7 @@ public abstract class AbstractQueuedSynchronizer /** * Returns the current value of synchronization state. - * This operation has memory semantics of a volatile read. + * This operation has memory semantics of a {@code volatile} read. * @return current state value */ protected final int getState() { @@ -543,7 +543,7 @@ public abstract class AbstractQueuedSynchronizer /** * Sets the value of synchronization state. - * This operation has memory semantics of a volatile write. + * This operation has memory semantics of a {@code volatile} write. * @param newState the new state value */ protected final void setState(int newState) { @@ -553,12 +553,12 @@ public abstract class AbstractQueuedSynchronizer /** * Atomically sets synchronization state to the given updated * value if the current state value equals the expected value. - * This operation has memory semantics of a volatile read + * This operation has memory semantics of a {@code volatile} read * and write. * * @param expect the expected value * @param update the new value - * @return true if successful. False return indicates that the actual + * @return {@code true} if successful. False return indicates that the actual * value was not equal to the expected value. */ protected final boolean compareAndSetState(int expect, int update) { @@ -663,7 +663,7 @@ public abstract class AbstractQueuedSynchronizer } /** - * Release action for shared mode -- signal successor and ensure + * Release action for shared mode -- signals successor and ensures * propagation. (Note: For exclusive mode, release just amounts * to calling unparkSuccessor of head if it needs signal.) */ @@ -784,7 +784,7 @@ public abstract class AbstractQueuedSynchronizer /** * Checks and updates status for a node that failed to acquire. * Returns true if thread should block. This is the main signal - * control in all acquire loops. Requires that pred == node.prev + * control in all acquire loops. Requires that pred == node.prev. * * @param pred node's predecessor holding status * @param node the node @@ -1288,7 +1288,7 @@ public abstract class AbstractQueuedSynchronizer * thread is queued, possibly repeatedly blocking and unblocking, * invoking {@link #tryAcquireShared} until success or the thread * is interrupted. - * @param arg the acquire argument + * @param arg the acquire argument. * This value is conveyed to {@link #tryAcquireShared} but is * otherwise uninterpreted and can represent anything * you like. @@ -1663,7 +1663,7 @@ public abstract class AbstractQueuedSynchronizer * Returns true if successful. * @param node the node * @return true if successfully transferred (else the node was - * cancelled before signal). + * cancelled before signal) */ final boolean transferForSignal(Node node) { /* @@ -1686,11 +1686,10 @@ public abstract class AbstractQueuedSynchronizer } /** - * Transfers node, if necessary, to sync queue after a cancelled - * wait. Returns true if thread was cancelled before being - * signalled. - * @param current the waiting thread - * @param node its node + * Transfers node, if necessary, to sync queue after a cancelled wait. + * Returns true if thread was cancelled before being signalled. + * + * @param node the node * @return true if cancelled before the node was signalled */ final boolean transferAfterCancelledWait(Node node) { @@ -1738,7 +1737,7 @@ public abstract class AbstractQueuedSynchronizer * uses this synchronizer as its lock. * * @param condition the condition - * @return true if owned + * @return {@code true} if owned * @throws NullPointerException if the condition is null */ public final boolean owns(ConditionObject condition) { @@ -1748,13 +1747,13 @@ public abstract class AbstractQueuedSynchronizer /** * Queries whether any threads are waiting on the given condition * associated with this synchronizer. Note that because timeouts - * and interrupts may occur at any time, a true return - * does not guarantee that a future signal will awaken + * and interrupts may occur at any time, a {@code true} return + * does not guarantee that a future {@code signal} will awaken * any threads. This method is designed primarily for use in * monitoring of the system state. * * @param condition the condition - * @return true if there are any waiting threads + * @return {@code true} if there are any waiting threads * @throws IllegalMonitorStateException if exclusive synchronization * is not held * @throws IllegalArgumentException if the given condition is @@ -1821,7 +1820,7 @@ public abstract class AbstractQueuedSynchronizer * and Condition users. Exported versions of this class will in * general need to be accompanied by documentation describing * condition semantics that rely on those of the associated - * AbstractQueuedSynchronizer. + * {@code AbstractQueuedSynchronizer}. * *

    This class is Serializable, but all fields are transient, * so deserialized conditions have no waiters. @@ -1834,7 +1833,7 @@ public abstract class AbstractQueuedSynchronizer private transient Node lastWaiter; /** - * Creates a new ConditionObject instance. + * Creates a new {@code ConditionObject} instance. */ public ConditionObject() { } @@ -2187,7 +2186,7 @@ public abstract class AbstractQueuedSynchronizer /** * Queries whether any threads are waiting on this condition. - * Implements {@link AbstractQueuedSynchronizer#hasWaiters}. + * Implements {@link AbstractQueuedSynchronizer#hasWaiters(ConditionObject)}. * * @return {@code true} if there are any waiting threads * @throws IllegalMonitorStateException if {@link #isHeldExclusively} @@ -2206,7 +2205,7 @@ public abstract class AbstractQueuedSynchronizer /** * Returns an estimate of the number of threads waiting on * this condition. - * Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength}. + * Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength(ConditionObject)}. * * @return the estimated number of waiting threads * @throws IllegalMonitorStateException if {@link #isHeldExclusively} @@ -2226,7 +2225,7 @@ public abstract class AbstractQueuedSynchronizer /** * Returns a collection containing those threads that may be * waiting on this Condition. - * Implements {@link AbstractQueuedSynchronizer#getWaitingThreads}. + * Implements {@link AbstractQueuedSynchronizer#getWaitingThreads(ConditionObject)}. * * @return the collection of threads * @throws IllegalMonitorStateException if {@link #isHeldExclusively} diff --git a/src/share/classes/java/util/concurrent/locks/Condition.java b/src/share/classes/java/util/concurrent/locks/Condition.java index 02cbee904bcd8120ca33dd58a628752429fd206f..06fb8f1cf02e59f0c0a213918b36af3332937fb1 100644 --- a/src/share/classes/java/util/concurrent/locks/Condition.java +++ b/src/share/classes/java/util/concurrent/locks/Condition.java @@ -324,7 +324,7 @@ public interface Condition { * } * }}

    * - *

    Design note: This method requires a nanosecond argument so + *

    Design note: This method requires a nanosecond argument so * as to avoid truncation errors in reporting remaining times. * Such precision loss would make it difficult for programmers to * ensure that total waiting times are not systematically shorter diff --git a/src/share/classes/java/util/concurrent/locks/Lock.java b/src/share/classes/java/util/concurrent/locks/Lock.java index d9ae1bcc4ed40175f56e67768cc3f20eaf678feb..371a6c7c13a4f318bf71f35888f6be5c1087d390 100644 --- a/src/share/classes/java/util/concurrent/locks/Lock.java +++ b/src/share/classes/java/util/concurrent/locks/Lock.java @@ -121,8 +121,8 @@ import java.util.concurrent.TimeUnit; *

    All {@code Lock} implementations must enforce the same * memory synchronization semantics as provided by the built-in monitor * lock, as described in - * - * The Java Language Specification, Third Edition (17.4 Memory Model): + * + * The Java Language Specification (17.4 Memory Model): *

      *
    • A successful {@code lock} operation has the same memory * synchronization effects as a successful Lock action. @@ -136,7 +136,7 @@ import java.util.concurrent.TimeUnit; * *

      Implementation Considerations

      * - *

      The three forms of lock acquisition (interruptible, + *

      The three forms of lock acquisition (interruptible, * non-interruptible, and timed) may differ in their performance * characteristics, ordering guarantees, or other implementation * qualities. Further, the ability to interrupt the ongoing @@ -227,7 +227,7 @@ public interface Lock { * * @throws InterruptedException if the current thread is * interrupted while acquiring the lock (and interruption - * of lock acquisition is supported). + * of lock acquisition is supported) */ void lockInterruptibly() throws InterruptedException; diff --git a/src/share/classes/java/util/concurrent/locks/LockSupport.java b/src/share/classes/java/util/concurrent/locks/LockSupport.java index 20abfacc3c8d4c3d6f1dadea4fe64fd583b1e10c..46a0ab597c87d17ace150c256bcdc58f1e6e3051 100644 --- a/src/share/classes/java/util/concurrent/locks/LockSupport.java +++ b/src/share/classes/java/util/concurrent/locks/LockSupport.java @@ -67,10 +67,10 @@ import sun.misc.Unsafe; * {@code blocker} object parameter. This object is recorded while * the thread is blocked to permit monitoring and diagnostic tools to * identify the reasons that threads are blocked. (Such tools may - * access blockers using method {@link #getBlocker}.) The use of these - * forms rather than the original forms without this parameter is - * strongly encouraged. The normal argument to supply as a - * {@code blocker} within a lock implementation is {@code this}. + * access blockers using method {@link #getBlocker(Thread)}.) + * The use of these forms rather than the original forms without this + * parameter is strongly encouraged. The normal argument to supply as + * a {@code blocker} within a lock implementation is {@code this}. * *

      These methods are designed to be used as tools for creating * higher-level synchronization utilities, and are not in themselves diff --git a/src/share/classes/java/util/concurrent/locks/ReadWriteLock.java b/src/share/classes/java/util/concurrent/locks/ReadWriteLock.java index fd6632b0b5733e9cfcfce6ab0569d3f98d96c2d9..40b0f344238ba58f27eaee66f8dc767d0f065d51 100644 --- a/src/share/classes/java/util/concurrent/locks/ReadWriteLock.java +++ b/src/share/classes/java/util/concurrent/locks/ReadWriteLock.java @@ -36,16 +36,16 @@ package java.util.concurrent.locks; /** - * A ReadWriteLock maintains a pair of associated {@link + * A {@code ReadWriteLock} maintains a pair of associated {@link * Lock locks}, one for read-only operations and one for writing. * The {@link #readLock read lock} may be held simultaneously by * multiple reader threads, so long as there are no writers. The * {@link #writeLock write lock} is exclusive. * - *

      All ReadWriteLock implementations must guarantee that - * the memory synchronization effects of writeLock operations + *

      All {@code ReadWriteLock} implementations must guarantee that + * the memory synchronization effects of {@code writeLock} operations * (as specified in the {@link Lock} interface) also hold with respect - * to the associated readLock. That is, a thread successfully + * to the associated {@code readLock}. That is, a thread successfully * acquiring the read lock will see all updates made upon previous * release of the write lock. * @@ -120,14 +120,14 @@ public interface ReadWriteLock { /** * Returns the lock used for reading. * - * @return the lock used for reading. + * @return the lock used for reading */ Lock readLock(); /** * Returns the lock used for writing. * - * @return the lock used for writing. + * @return the lock used for writing */ Lock writeLock(); } diff --git a/src/share/classes/java/util/concurrent/locks/ReentrantLock.java b/src/share/classes/java/util/concurrent/locks/ReentrantLock.java index 5ca1335aaf6aaf1c5953f8112f8ad4142691eec8..06c7e61ab654820a4c63d337b78e112219815789 100644 --- a/src/share/classes/java/util/concurrent/locks/ReentrantLock.java +++ b/src/share/classes/java/util/concurrent/locks/ReentrantLock.java @@ -64,7 +64,7 @@ import java.util.Collection; * fair lock may obtain it multiple times in succession while other * active threads are not progressing and not currently holding the * lock. - * Also note that the untimed {@link #tryLock() tryLock} method does not + * Also note that the untimed {@link #tryLock()} method does not * honor the fairness setting. It will succeed if the lock * is available even if other threads are waiting. * @@ -88,10 +88,9 @@ import java.util.Collection; * }} * *

      In addition to implementing the {@link Lock} interface, this - * class defines methods {@code isLocked} and - * {@code getLockQueueLength}, as well as some associated - * {@code protected} access methods that may be useful for - * instrumentation and monitoring. + * class defines a number of {@code public} and {@code protected} + * methods for inspecting the state of the lock. Some of these + * methods are only useful for instrumentation and monitoring. * *

      Serialization of this class behaves in the same way as built-in * locks: a deserialized lock is in the unlocked state, regardless of @@ -124,9 +123,8 @@ public class ReentrantLock implements Lock, java.io.Serializable { abstract void lock(); /** - * Performs non-fair tryLock. tryAcquire is - * implemented in subclasses, but both need nonfair - * try for trylock method. + * Performs non-fair tryLock. tryAcquire is implemented in + * subclasses, but both need nonfair try for trylock method. */ final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); @@ -353,7 +351,7 @@ public class ReentrantLock implements Lock, java.io.Serializable { * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) } * which is almost equivalent (it also detects interruption). * - *

      If the current thread already holds this lock then the hold + *

      If the current thread already holds this lock then the hold * count is incremented by one and the method returns {@code true}. * *

      If the lock is held by another thread then this method will return @@ -538,10 +536,10 @@ public class ReentrantLock implements Lock, java.io.Serializable { /** * Queries if this lock is held by the current thread. * - *

      Analogous to the {@link Thread#holdsLock} method for built-in - * monitor locks, this method is typically used for debugging and - * testing. For example, a method that should only be called while - * a lock is held can assert that this is the case: + *

      Analogous to the {@link Thread#holdsLock(Object)} method for + * built-in monitor locks, this method is typically used for + * debugging and testing. For example, a method that should only be + * called while a lock is held can assert that this is the case: * *

       {@code
            * class X {
      diff --git a/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java b/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java
      index 3698bab27bb9e1442f533b7fd1bbf1f282907a01..519477e5244ccbc2071122dcd1862b37baadee50 100644
      --- a/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java
      +++ b/src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java
      @@ -45,7 +45,7 @@ import java.util.Collection;
        * 
        *
      • Acquisition order * - *

        This class does not impose a reader or writer preference + *

        This class does not impose a reader or writer preference * ordering for lock access. However, it does support an optional * fairness policy. * @@ -59,7 +59,7 @@ import java.util.Collection; *

        * *

        Fair mode - *
        When constructed as fair, threads contend for entry using an + *
        When constructed as fair, threads contend for entry using an * approximately arrival-order policy. When the currently held lock * is released, either the longest-waiting single writer thread will * be assigned the write lock, or if there is a group of reader threads @@ -277,7 +277,7 @@ public class ReentrantReadWriteLock static final class HoldCounter { int count = 0; // Use id, not reference, to avoid garbage retention - final long tid = Thread.currentThread().getId(); + final long tid = getThreadId(Thread.currentThread()); } /** @@ -420,7 +420,7 @@ public class ReentrantReadWriteLock firstReaderHoldCount--; } else { HoldCounter rh = cachedHoldCounter; - if (rh == null || rh.tid != current.getId()) + if (rh == null || rh.tid != getThreadId(current)) rh = readHolds.get(); int count = rh.count; if (count <= 1) { @@ -478,7 +478,7 @@ public class ReentrantReadWriteLock firstReaderHoldCount++; } else { HoldCounter rh = cachedHoldCounter; - if (rh == null || rh.tid != current.getId()) + if (rh == null || rh.tid != getThreadId(current)) cachedHoldCounter = rh = readHolds.get(); else if (rh.count == 0) readHolds.set(rh); @@ -515,7 +515,7 @@ public class ReentrantReadWriteLock } else { if (rh == null) { rh = cachedHoldCounter; - if (rh == null || rh.tid != current.getId()) { + if (rh == null || rh.tid != getThreadId(current)) { rh = readHolds.get(); if (rh.count == 0) readHolds.remove(); @@ -536,7 +536,7 @@ public class ReentrantReadWriteLock } else { if (rh == null) rh = cachedHoldCounter; - if (rh == null || rh.tid != current.getId()) + if (rh == null || rh.tid != getThreadId(current)) rh = readHolds.get(); else if (rh.count == 0) readHolds.set(rh); @@ -592,7 +592,7 @@ public class ReentrantReadWriteLock firstReaderHoldCount++; } else { HoldCounter rh = cachedHoldCounter; - if (rh == null || rh.tid != current.getId()) + if (rh == null || rh.tid != getThreadId(current)) cachedHoldCounter = rh = readHolds.get(); else if (rh.count == 0) readHolds.set(rh); @@ -643,7 +643,7 @@ public class ReentrantReadWriteLock return firstReaderHoldCount; HoldCounter rh = cachedHoldCounter; - if (rh != null && rh.tid == current.getId()) + if (rh != null && rh.tid == getThreadId(current)) return rh.count; int count = readHolds.get().count; @@ -875,7 +875,7 @@ public class ReentrantReadWriteLock /** * Attempts to release this lock. * - *

        If the number of readers is now zero then the lock + *

        If the number of readers is now zero then the lock * is made available for write lock attempts. */ public void unlock() { @@ -1017,7 +1017,7 @@ public class ReentrantReadWriteLock * #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) } * which is almost equivalent (it also detects interruption). * - *

        If the current thread already holds this lock then the + *

        If the current thread already holds this lock then the * hold count is incremented by one and the method returns * {@code true}. * @@ -1126,7 +1126,7 @@ public class ReentrantReadWriteLock * IllegalMonitorStateException} is thrown. * * @throws IllegalMonitorStateException if the current thread does not - * hold this lock. + * hold this lock */ public void unlock() { sync.release(1); @@ -1254,7 +1254,7 @@ public class ReentrantReadWriteLock * Queries the number of read locks held for this lock. This * method is designed for use in monitoring system state, not for * synchronization control. - * @return the number of read locks held. + * @return the number of read locks held */ public int getReadLockCount() { return sync.getReadLockCount(); @@ -1484,4 +1484,28 @@ public class ReentrantReadWriteLock "[Write locks = " + w + ", Read locks = " + r + "]"; } + /** + * Returns the thread id for the given thread. We must access + * this directly rather than via method Thread.getId() because + * getId() is not final, and has been known to be overridden in + * ways that do not preserve unique mappings. + */ + static final long getThreadId(Thread thread) { + return UNSAFE.getLongVolatile(thread, TID_OFFSET); + } + + // Unsafe mechanics + private static final sun.misc.Unsafe UNSAFE; + private static final long TID_OFFSET; + static { + try { + UNSAFE = sun.misc.Unsafe.getUnsafe(); + Class tk = Thread.class; + TID_OFFSET = UNSAFE.objectFieldOffset + (tk.getDeclaredField("tid")); + } catch (Exception e) { + throw new Error(e); + } + } + } diff --git a/src/share/classes/java/util/concurrent/locks/StampedLock.java b/src/share/classes/java/util/concurrent/locks/StampedLock.java index 0ca43f630f7b5327ed0b0ed3603101cb9ae27267..1506e5a4e46ba97e72212e459006d0ca13091471 100644 --- a/src/share/classes/java/util/concurrent/locks/StampedLock.java +++ b/src/share/classes/java/util/concurrent/locks/StampedLock.java @@ -366,6 +366,8 @@ public class StampedLock implements java.io.Serializable { * Behavior under timeout and interruption matches that specified * for method {@link Lock#tryLock(long,TimeUnit)}. * + * @param time the maximum time to wait for the lock + * @param unit the time unit of the {@code time} argument * @return a stamp that can be used to unlock or convert mode, * or zero if the lock is not available * @throws InterruptedException if the current thread is interrupted @@ -445,6 +447,8 @@ public class StampedLock implements java.io.Serializable { * Behavior under timeout and interruption matches that specified * for method {@link Lock#tryLock(long,TimeUnit)}. * + * @param time the maximum time to wait for the lock + * @param unit the time unit of the {@code time} argument * @return a stamp that can be used to unlock or convert mode, * or zero if the lock is not available * @throws InterruptedException if the current thread is interrupted @@ -510,7 +514,8 @@ public class StampedLock implements java.io.Serializable { * obtained from {@link #tryOptimisticRead} or a locking method * for this lock has no defined effect or result. * - * @return true if the lock has not been exclusively acquired + * @param stamp a stamp + * @return {@code true} if the lock has not been exclusively acquired * since issuance of the given stamp; else false */ public boolean validate(long stamp) { @@ -723,7 +728,7 @@ public class StampedLock implements java.io.Serializable { * stamp value. This method may be useful for recovery after * errors. * - * @return true if the lock was held, else false + * @return {@code true} if the lock was held, else false */ public boolean tryUnlockWrite() { long s; WNode h; @@ -741,7 +746,7 @@ public class StampedLock implements java.io.Serializable { * requiring a stamp value. This method may be useful for recovery * after errors. * - * @return true if the read lock was held, else false + * @return {@code true} if the read lock was held, else false */ public boolean tryUnlockRead() { long s, m; WNode h; @@ -773,18 +778,18 @@ public class StampedLock implements java.io.Serializable { } /** - * Returns true if the lock is currently held exclusively. + * Returns {@code true} if the lock is currently held exclusively. * - * @return true if the lock is currently held exclusively + * @return {@code true} if the lock is currently held exclusively */ public boolean isWriteLocked() { return (state & WBIT) != 0L; } /** - * Returns true if the lock is currently held non-exclusively. + * Returns {@code true} if the lock is currently held non-exclusively. * - * @return true if the lock is currently held non-exclusively + * @return {@code true} if the lock is currently held non-exclusively */ public boolean isReadLocked() { return (state & RBITS) != 0L; diff --git a/src/share/classes/java/util/function/BinaryOperator.java b/src/share/classes/java/util/function/BinaryOperator.java index e81bce8c5537b03edbfeb4f6e68233593a4daae4..195eba1c3c1fa2991c1a8c6dfe5b29ffa78bbb65 100644 --- a/src/share/classes/java/util/function/BinaryOperator.java +++ b/src/share/classes/java/util/function/BinaryOperator.java @@ -24,6 +24,9 @@ */ package java.util.function; +import java.util.Objects; +import java.util.Comparator; + /** * An operation upon two operands yielding a result. This is a specialization of * {@code BiFunction} where the operands and the result are all of the same type. @@ -35,4 +38,33 @@ package java.util.function; */ @FunctionalInterface public interface BinaryOperator extends BiFunction { + /** + * Returns a {@link BinaryOperator} which returns the lesser of two elements + * according to the specified {@code Comparator} + * + * @param the type of values to be compared and returned + * @param comparator a {@code Comparator} for comparing the two values + * @return a {@code BinaryOperator} which returns the lesser of its operands, + * according to the supplied {@code Comparator} + * @throws NullPointerException if the argument is null + */ + public static BinaryOperator minBy(Comparator comparator) { + Objects.requireNonNull(comparator); + return (a, b) -> comparator.compare(a, b) <= 0 ? a : b; + } + + /** + * Returns a {@link BinaryOperator} which returns the greater of two elements + * according to the specified {@code Comparator} + * + * @param the type of values to be compared and returned + * @param comparator a {@code Comparator} for comparing the two values + * @return a {@code BinaryOperator} which returns the greater of its operands, + * according to the supplied {@code Comparator} + * @throws NullPointerException if the argument is null + */ + public static BinaryOperator maxBy(Comparator comparator) { + Objects.requireNonNull(comparator); + return (a, b) -> comparator.compare(a, b) >= 0 ? a : b; + } } diff --git a/src/share/classes/java/util/function/Function.java b/src/share/classes/java/util/function/Function.java index 3cab4bf99d846203185b67f2874a9f732851d43c..084ba4cc9c766f88db7fda1d7744d2139b06f688 100644 --- a/src/share/classes/java/util/function/Function.java +++ b/src/share/classes/java/util/function/Function.java @@ -87,6 +87,7 @@ public interface Function { * Returns a {@code Function} whose {@code apply} method returns its input. * * @param the type of the input and output objects to the function + * @return a {@code Function} whose {@code apply} method returns its input */ static Function identity() { return t -> t; diff --git a/src/share/classes/java/util/function/UnaryOperator.java b/src/share/classes/java/util/function/UnaryOperator.java index 87fda16bbeb3b54fd3a2e5f78956d91687a91053..e7794ca19e50a43a22af61323d49ebeea949fc54 100644 --- a/src/share/classes/java/util/function/UnaryOperator.java +++ b/src/share/classes/java/util/function/UnaryOperator.java @@ -40,6 +40,7 @@ public interface UnaryOperator extends Function { /** * Returns a unary operator that provides its input value as the result. * + * @param the type of the input and output objects to the function * @return a unary operator that provides its input value as the result */ static UnaryOperator identity() { diff --git a/src/share/classes/java/util/jar/Pack200.java b/src/share/classes/java/util/jar/Pack200.java index dbefe59305dabb8973959f256d3ec49f3da7cb0d..cf4fb98db8f41ece258d89810b219d3f1c35b6c5 100644 --- a/src/share/classes/java/util/jar/Pack200.java +++ b/src/share/classes/java/util/jar/Pack200.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -112,7 +112,7 @@ public abstract class Pack200 { // Static methods of the Pack200 class. /** * Obtain new instance of a class that implements Packer. - * + *

          *
        • If the system property java.util.jar.Pack200.Packer * is defined, then the value is taken to be the fully-qualified name * of a concrete implementation class, which must implement Packer. @@ -122,6 +122,7 @@ public abstract class Pack200 { *

        • If an implementation has not been specified with the system * property, then the system-default implementation class is instantiated, * and the result is returned.

        • + *
        * *

        Note: The returned object is not guaranteed to operate * correctly if multiple threads use it at the same time. @@ -137,7 +138,7 @@ public abstract class Pack200 { /** * Obtain new instance of a class that implements Unpacker. - * + *

          *
        • If the system property java.util.jar.Pack200.Unpacker * is defined, then the value is taken to be the fully-qualified * name of a concrete implementation class, which must implement Unpacker. @@ -147,6 +148,7 @@ public abstract class Pack200 { *

        • If an implementation has not been specified with the * system property, then the system-default implementation class * is instantiated, and the result is returned.

        • + *
        * *

        Note: The returned object is not guaranteed to operate * correctly if multiple threads use it at the same time. @@ -350,14 +352,14 @@ public abstract class Pack200 { * directory will be passed also. *

        * Examples: - *

        
        +         * 
        {@code
                  *     Map p = packer.properties();
                  *     p.put(PASS_FILE_PFX+0, "mutants/Rogue.class");
                  *     p.put(PASS_FILE_PFX+1, "mutants/Wolverine.class");
                  *     p.put(PASS_FILE_PFX+2, "mutants/Storm.class");
                  *     # Pass all files in an entire directory hierarchy:
                  *     p.put(PASS_FILE_PFX+3, "police/");
        -         * 
        . + * }
        */ String PASS_FILE_PFX = "pack.pass.file."; @@ -378,12 +380,12 @@ public abstract class Pack200 { * This is the default value for this property. *

        * Examples: - *

        
        +         * 
        {@code
                  *     Map p = pack200.getProperties();
                  *     p.put(UNKNOWN_ATTRIBUTE, ERROR);
                  *     p.put(UNKNOWN_ATTRIBUTE, STRIP);
                  *     p.put(UNKNOWN_ATTRIBUTE, PASS);
        -         * 
        + * }
        */ String UNKNOWN_ATTRIBUTE = "pack.unknown.attribute"; diff --git a/src/share/classes/java/util/logging/Handler.java b/src/share/classes/java/util/logging/Handler.java index c44dafbb7bae00247634783628fe0ff21bc0883e..a8c3eb4b036b30b476292c6ca4b24d4e382a89bb 100644 --- a/src/share/classes/java/util/logging/Handler.java +++ b/src/share/classes/java/util/logging/Handler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -209,6 +209,7 @@ public abstract class Handler { /** * Retrieves the ErrorManager for this Handler. * + * @return the ErrorManager for this Handler * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ diff --git a/src/share/classes/java/util/logging/LogManager.java b/src/share/classes/java/util/logging/LogManager.java index deed5574d2aaf76cf45999966201a5ce2614d0f9..0d63468b3cc43db8defbceae83a33da9b3d1a603 100644 --- a/src/share/classes/java/util/logging/LogManager.java +++ b/src/share/classes/java/util/logging/LogManager.java @@ -193,13 +193,27 @@ public class LogManager { // Create and retain Logger for the root of the namespace. manager.rootLogger = manager.new RootLogger(); + // since by design the global manager's userContext and + // systemContext don't have their requiresDefaultLoggers + // flag set - we make sure to add the root logger to + // the global manager's default contexts here. manager.addLogger(manager.rootLogger); - manager.systemContext.addLocalLogger(manager.rootLogger); + manager.systemContext.addLocalLogger(manager.rootLogger, false); + manager.userContext.addLocalLogger(manager.rootLogger, false); // Adding the global Logger. Doing so in the Logger. // would deadlock with the LogManager.. - Logger.global.setLogManager(manager); - manager.addLogger(Logger.global); + // Do not call Logger.getGlobal() here as this might trigger + // the deadlock too. + @SuppressWarnings("deprecation") + final Logger global = Logger.global; + global.setLogManager(manager); + + // Make sure the global logger will be registered in the + // global manager's default contexts. + manager.addLogger(global); + manager.systemContext.addLocalLogger(global, false); + manager.userContext.addLocalLogger(global, false); // We don't call readConfiguration() here, as we may be running // very early in the JVM startup sequence. Instead readConfiguration @@ -257,7 +271,8 @@ public class LogManager { } /** - * Return the global LogManager object. + * Returns the global LogManager object. + * @return the global LogManager object */ public static LogManager getLogManager() { if (manager != null) { @@ -400,7 +415,11 @@ public class LogManager { if (javaAwtAccess.isMainAppContext()) { context = userContext; } else { - context = new LoggerContext(); + // Create a new LoggerContext for the applet. + // The new logger context has its requiresDefaultLoggers + // flag set to true - so that these loggers will be + // lazily added when the context is firt accessed. + context = new LoggerContext(true); } javaAwtAccess.put(ecx, LoggerContext.class, context); } @@ -507,9 +526,13 @@ public class LogManager { private final Hashtable namedLoggers = new Hashtable<>(); // Tree of named Loggers private final LogNode root; - + private final boolean requiresDefaultLoggers; private LoggerContext() { + this(false); + } + private LoggerContext(boolean requiresDefaultLoggers) { this.root = new LogNode(null, this); + this.requiresDefaultLoggers = requiresDefaultLoggers; } Logger demandLogger(String name, String resourceBundleName) { @@ -518,7 +541,27 @@ public class LogManager { return manager.demandLogger(name, resourceBundleName, null); } + + // Due to subtle deadlock issues getUserContext() no longer + // calls addLocalLogger(rootLogger); + // Therefore - we need to add the default loggers later on. + // Checks that the context is properly initialized + // This is necessary before calling e.g. find(name) + // or getLoggerNames() + // + private void ensureInitialized() { + if (requiresDefaultLoggers) { + // Ensure that the root and global loggers are set. + ensureDefaultLogger(manager.rootLogger); + ensureDefaultLogger(Logger.global); + } + } + + synchronized Logger findLogger(String name) { + // ensure that this context is properly initialized before + // looking for loggers. + ensureInitialized(); LoggerWeakRef ref = namedLoggers.get(name); if (ref == null) { return null; @@ -532,21 +575,76 @@ public class LogManager { return logger; } - synchronized void ensureRootLogger(Logger logger) { - if (logger.getName().isEmpty()) + // This method is called before adding a logger to the + // context. + // 'logger' is the context that will be added. + // This method will ensure that the defaults loggers are added + // before adding 'logger'. + // + private void ensureAllDefaultLoggers(Logger logger) { + if (requiresDefaultLoggers) { + final String name = logger.getName(); + if (!name.isEmpty()) { + ensureDefaultLogger(manager.rootLogger); + } + if (!Logger.GLOBAL_LOGGER_NAME.equals(name)) { + ensureDefaultLogger(Logger.global); + } + } + } + + private void ensureDefaultLogger(Logger logger) { + // Used for lazy addition of root logger and global logger + // to a LoggerContext. + + // This check is simple sanity: we do not want that this + // method be called for anything else than Logger.global + // or owner.rootLogger. + if (!requiresDefaultLoggers || logger == null + || logger != Logger.global && logger != manager.rootLogger) { + + // the case where we have a non null logger which is neither + // Logger.global nor manager.rootLogger indicates a serious + // issue - as ensureDefaultLogger should never be called + // with any other loggers than one of these two (or null - if + // e.g manager.rootLogger is not yet initialized)... + assert logger == null; + return; + } - // during initialization, rootLogger is null when - // instantiating itself RootLogger - if (findLogger("") == null && manager.rootLogger != null) { - addLocalLogger(manager.rootLogger); + // Adds the logger if it's not already there. + if (!namedLoggers.containsKey(logger.getName())) { + // It is important to prevent addLocalLogger to + // call ensureAllDefaultLoggers when we're in the process + // off adding one of those default loggers - as this would + // immediately cause a stack overflow. + // Therefore we must pass addDefaultLoggersIfNeeded=false, + // even if requiresDefaultLoggers is true. + addLocalLogger(logger, false); } } + boolean addLocalLogger(Logger logger) { + // no need to add default loggers if it's not required + return addLocalLogger(logger, requiresDefaultLoggers); + } + // Add a logger to this context. This method will only set its level // and process parent loggers. It doesn't set its handlers. - synchronized boolean addLocalLogger(Logger logger) { - ensureRootLogger(logger); + synchronized boolean addLocalLogger(Logger logger, boolean addDefaultLoggersIfNeeded) { + // addDefaultLoggersIfNeeded serves to break recursion when adding + // default loggers. If we're adding one of the default loggers + // (we're being called from ensureDefaultLogger()) then + // addDefaultLoggersIfNeeded will be false: we don't want to + // call ensureAllDefaultLoggers again. + // + // Note: addDefaultLoggersIfNeeded can also be false when + // requiresDefaultLoggers is false - since calling + // ensureAllDefaultLoggers would have no effect in this case. + if (addDefaultLoggersIfNeeded) { + ensureAllDefaultLoggers(logger); + } final String name = logger.getName(); if (name == null) { @@ -614,6 +712,9 @@ public class LogManager { } synchronized Enumeration getLoggerNames() { + // ensure that this context is properly initialized before + // returning logger names. + ensureInitialized(); return namedLoggers.keys(); } diff --git a/src/share/classes/java/util/logging/LogRecord.java b/src/share/classes/java/util/logging/LogRecord.java index 93540d9a009365fbb2b0d2a4eaca2fae0821085f..50444f1cd8af2c88b0044ecd4f1613ff3d386659 100644 --- a/src/share/classes/java/util/logging/LogRecord.java +++ b/src/share/classes/java/util/logging/LogRecord.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -211,6 +211,7 @@ public class LogRecord implements java.io.Serializable { * the message string before formatting it. The result may * be null if the message is not localizable, or if no suitable * ResourceBundle is available. + * @return the localization resource bundle */ public ResourceBundle getResourceBundle() { return resourceBundle; @@ -231,6 +232,7 @@ public class LogRecord implements java.io.Serializable { * This is the name for the ResourceBundle that should be * used to localize the message string before formatting it. * The result may be null if the message is not localizable. + * @return the localization resource bundle name */ public String getResourceBundleName() { return resourceBundleName; @@ -281,6 +283,7 @@ public class LogRecord implements java.io.Serializable { *

        * Sequence numbers are normally assigned in the LogRecord constructor, * so it should not normally be necessary to use this method. + * @param seq the sequence number */ public void setSequenceNumber(long seq) { sequenceNumber = seq; diff --git a/src/share/classes/java/util/logging/Logger.java b/src/share/classes/java/util/logging/Logger.java index 11b0c0ce672381f5d8b106759024f07f35242a6e..1c959ecd6a1c42208b0d7f214e97ec537f44c5b4 100644 --- a/src/share/classes/java/util/logging/Logger.java +++ b/src/share/classes/java/util/logging/Logger.java @@ -232,6 +232,27 @@ public class Logger { * @since 1.7 */ public static final Logger getGlobal() { + // In order to break a cyclic dependence between the LogManager + // and Logger static initializers causing deadlocks, the global + // logger is created with a special constructor that does not + // initialize its log manager. + // + // If an application calls Logger.getGlobal() before any logger + // has been initialized, it is therefore possible that the + // LogManager class has not been initialized yet, and therefore + // Logger.global.manager will be null. + // + // In order to finish the initialization of the global logger, we + // will therefore call LogManager.getLogManager() here. + // + // Care must be taken *not* to call Logger.getGlobal() in + // LogManager static initializers in order to avoid such + // deadlocks. + // + if (global != null && global.manager == null) { + // Complete initialization of the global Logger. + global.manager = LogManager.getLogManager(); + } return global; } diff --git a/src/share/classes/java/util/prefs/AbstractPreferences.java b/src/share/classes/java/util/prefs/AbstractPreferences.java index b7723d831ac77a2bd96cc0dd32549155ecc9c051..31c35d7fa46f1867950abd75031519d8f0d387c1 100644 --- a/src/share/classes/java/util/prefs/AbstractPreferences.java +++ b/src/share/classes/java/util/prefs/AbstractPreferences.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1121,6 +1121,8 @@ public abstract class AbstractPreferences extends Preferences { * removed. (The implementor needn't check for any of these things.) * *

        This method is invoked with the lock on this node held. + * @param key the key + * @param value the value */ protected abstract void putSpi(String key, String value); @@ -1139,6 +1141,7 @@ public abstract class AbstractPreferences extends Preferences { * *

        This method is invoked with the lock on this node held. * + * @param key the key * @return the value associated with the specified key at this preference * node, or null if there is no association for this * key, or the association cannot be determined at this time. @@ -1152,6 +1155,7 @@ public abstract class AbstractPreferences extends Preferences { * (The implementor needn't check for either of these things.) * *

        This method is invoked with the lock on this node held. + * @param key the key */ protected abstract void removeSpi(String key); diff --git a/src/share/classes/java/util/prefs/PreferencesFactory.java b/src/share/classes/java/util/prefs/PreferencesFactory.java index 8bf37bc3c5c56efe29df793b945342fdcffe1ad0..d7341e6569db5c604fe1e393da3b2964ea5de3b4 100644 --- a/src/share/classes/java/util/prefs/PreferencesFactory.java +++ b/src/share/classes/java/util/prefs/PreferencesFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -45,6 +45,7 @@ public interface PreferencesFactory { /** * Returns the system root preference node. (Multiple calls on this * method will return the same object reference.) + * @return the system root preference node */ Preferences systemRoot(); @@ -52,6 +53,8 @@ public interface PreferencesFactory { * Returns the user root preference node corresponding to the calling * user. In a server, the returned value will typically depend on * some implicit client-context. + * @return the user root preference node corresponding to the calling + * user */ Preferences userRoot(); } diff --git a/src/share/classes/java/util/spi/LocaleServiceProvider.java b/src/share/classes/java/util/spi/LocaleServiceProvider.java index c490dbadf8581b0c9a3f95113a2a9378a0cd0f38..87af9788f502eefcde2cbc9580047d1ee357a55a 100644 --- a/src/share/classes/java/util/spi/LocaleServiceProvider.java +++ b/src/share/classes/java/util/spi/LocaleServiceProvider.java @@ -42,7 +42,7 @@ import java.util.Locale; * interfaces to offer support for locales beyond the set of locales * supported by the Java runtime environment itself. *

        - *

        Packaging of Locale Sensitive Service Provider Implementations

        + *

        Packaging of Locale Sensitive Service Provider Implementations

        * Implementations of these locale sensitive services are packaged using the * Java Extension Mechanism * as installed extensions. A provider identifies itself with a @@ -165,7 +165,7 @@ public abstract class LocaleServiceProvider { /** * Returns {@code true} if the given {@code locale} is supported by * this locale service provider. The given {@code locale} may contain - * extensions that should be + * extensions that should be * taken into account for the support determination. * *

        The default implementation returns {@code true} if the given {@code locale} diff --git a/src/share/classes/java/util/stream/AbstractPipeline.java b/src/share/classes/java/util/stream/AbstractPipeline.java index 37575b0c72caf863a357c44f80daa29bf8b55509..efda9407152d426051f9d04642d119191ad8bdc6 100644 --- a/src/share/classes/java/util/stream/AbstractPipeline.java +++ b/src/share/classes/java/util/stream/AbstractPipeline.java @@ -375,6 +375,12 @@ abstract class AbstractPipeline> // NOTE: there are no size-injecting ops if (StreamOpFlag.SHORT_CIRCUIT.isKnown(thisOpFlags)) { backPropagationHead = p; + // Clear the short circuit flag for next pipeline stage + // This stage encapsulates short-circuiting, the next + // stage may not have any short-circuit operations, and + // if so spliterator.forEachRemaining should be be used + // for traversal + thisOpFlags = thisOpFlags & ~StreamOpFlag.IS_SHORT_CIRCUIT; } depth = 0; @@ -447,6 +453,15 @@ abstract class AbstractPipeline> // PipelineHelper + @Override + final StreamShape getSourceShape() { + AbstractPipeline p = AbstractPipeline.this; + while (p.depth > 0) { + p = p.previousStage; + } + return p.getOutputShape(); + } + @Override final long exactOutputSizeIfKnown(Spliterator spliterator) { return StreamOpFlag.SIZED.isKnown(getStreamAndOpFlags()) ? spliterator.getExactSizeIfKnown() : -1; @@ -502,6 +517,16 @@ abstract class AbstractPipeline> return (Sink) sink; } + @Override + final Spliterator wrapSpliterator(Spliterator sourceSpliterator) { + if (depth == 0) { + return (Spliterator) sourceSpliterator; + } + else { + return wrap(this, () -> sourceSpliterator, isParallel()); + } + } + @Override @SuppressWarnings("unchecked") final Node evaluate(Spliterator spliterator, diff --git a/src/share/classes/java/util/stream/AbstractTask.java b/src/share/classes/java/util/stream/AbstractTask.java index 1b7ad2122867455a9a677efe7504fa25a62eea38..75fc3a11f6048a66e96c0d0015563cfa5cde725e 100644 --- a/src/share/classes/java/util/stream/AbstractTask.java +++ b/src/share/classes/java/util/stream/AbstractTask.java @@ -316,6 +316,7 @@ abstract class AbstractTask> byDept @@ -89,7 +88,7 @@ import java.util.function.ToLongFunction; * Map highestPaidByDept * = employees.stream() * .collect(Collectors.groupingBy(Employee::getDepartment, - * Collectors.maxBy(Comparators.comparing(Employee::getSalary)))); + * Collectors.maxBy(Comparator.comparing(Employee::getSalary)))); * * // Partition students into passing and failing * Map> passingFailing = @@ -404,7 +403,7 @@ public final class Collectors { * @implSpec * This produces a result equivalent to: *

        {@code
        -     *     reducing(Comparators.lesserOf(comparator))
        +     *     reducing(BinaryOperator.minBy(comparator))
              * }
        * * @param the type of the input elements @@ -413,7 +412,7 @@ public final class Collectors { */ public static Collector minBy(Comparator comparator) { - return reducing(Comparators.lesserOf(comparator)); + return reducing(BinaryOperator.minBy(comparator)); } /** @@ -423,7 +422,7 @@ public final class Collectors { * @implSpec * This produces a result equivalent to: *
        {@code
        -     *     reducing(Comparators.greaterOf(comparator))
        +     *     reducing(BinaryOperator.maxBy(comparator))
              * }
        * * @param the type of the input elements @@ -432,7 +431,7 @@ public final class Collectors { */ public static Collector maxBy(Comparator comparator) { - return reducing(Comparators.greaterOf(comparator)); + return reducing(BinaryOperator.maxBy(comparator)); } /** @@ -491,8 +490,8 @@ public final class Collectors { *

        For example, given a stream of {@code Person}, to calculate tallest * person in each city: *

        {@code
        -     *     Comparator byHeight = Comparators.comparing(Person::getHeight);
        -     *     BinaryOperator tallerOf = Comparators.greaterOf(byHeight);
        +     *     Comparator byHeight = Comparator.comparing(Person::getHeight);
        +     *     BinaryOperator tallerOf = BinaryOperator.greaterOf(byHeight);
              *     Map tallestByCity
              *         = people.stream().collect(groupingBy(Person::getCity, reducing(tallerOf)));
              * }
        @@ -531,8 +530,8 @@ public final class Collectors { *

        For example, given a stream of {@code Person}, to calculate the longest * last name of residents in each city: *

        {@code
        -     *     Comparator byLength = Comparators.comparing(String::length);
        -     *     BinaryOperator longerOf = Comparators.greaterOf(byLength);
        +     *     Comparator byLength = Comparator.comparing(String::length);
        +     *     BinaryOperator longerOf = BinaryOperator.greaterOf(byLength);
              *     Map longestLastNameByCity
              *         = people.stream().collect(groupingBy(Person::getCity,
              *                                              reducing(Person::getLastName, longerOf)));
        diff --git a/src/share/classes/java/util/stream/DoubleStream.java b/src/share/classes/java/util/stream/DoubleStream.java
        index 1706c31572c4fabbe21a974e89bff83916fb5061..55d244fc4c31c9809b5ee854fa3df641c6066418 100644
        --- a/src/share/classes/java/util/stream/DoubleStream.java
        +++ b/src/share/classes/java/util/stream/DoubleStream.java
        @@ -743,14 +743,7 @@ public interface DoubleStream extends BaseStream {
              */
             public static DoubleStream generate(DoubleSupplier s) {
                 Objects.requireNonNull(s);
        -        return StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize(
        -                new PrimitiveIterator.OfDouble() {
        -                    @Override
        -                    public boolean hasNext() { return true; }
        -
        -                    @Override
        -                    public double nextDouble() { return s.getAsDouble(); }
        -                },
        -                Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL));
        +        return StreamSupport.doubleStream(
        +                new StreamSpliterators.InfiniteSupplyingSpliterator.OfDouble(Long.MAX_VALUE, s));
             }
         }
        diff --git a/src/share/classes/java/util/stream/ForEachOps.java b/src/share/classes/java/util/stream/ForEachOps.java
        index 944dec6211f00338377631b2794d78b2259fbc6e..6f20677cd667f33640f61d12287da13cdd8a4820 100644
        --- a/src/share/classes/java/util/stream/ForEachOps.java
        +++ b/src/share/classes/java/util/stream/ForEachOps.java
        @@ -342,7 +342,7 @@ final class ForEachOps {
                     doCompute(this);
                 }
         
        -        private static void doCompute(ForEachOrderedTask task) {
        +        private static  void doCompute(ForEachOrderedTask task) {
                     while (true) {
                         Spliterator split;
                         if (!AbstractTask.suggestSplit(task.spliterator, task.targetSize)
        diff --git a/src/share/classes/java/util/stream/IntStream.java b/src/share/classes/java/util/stream/IntStream.java
        index 3545c9b83abab6f259b76bab0e9a9b7455273b91..3eb4409c4e590653b765f36f83bd02e138cf866a 100644
        --- a/src/share/classes/java/util/stream/IntStream.java
        +++ b/src/share/classes/java/util/stream/IntStream.java
        @@ -745,15 +745,8 @@ public interface IntStream extends BaseStream {
              */
             public static IntStream generate(IntSupplier s) {
                 Objects.requireNonNull(s);
        -        return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(
        -                new PrimitiveIterator.OfInt() {
        -                    @Override
        -                    public boolean hasNext() { return true; }
        -
        -                    @Override
        -                    public int nextInt() { return s.getAsInt(); }
        -                },
        -                Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL));
        +        return StreamSupport.intStream(
        +                new StreamSpliterators.InfiniteSupplyingSpliterator.OfInt(Long.MAX_VALUE, s));
             }
         
             /**
        diff --git a/src/share/classes/java/util/stream/LongStream.java b/src/share/classes/java/util/stream/LongStream.java
        index 1a1b24143381ffb372befc4b66f65d937b572388..3bc0f76a49461ee4c610c5d98141c6248845ea76 100644
        --- a/src/share/classes/java/util/stream/LongStream.java
        +++ b/src/share/classes/java/util/stream/LongStream.java
        @@ -736,15 +736,8 @@ public interface LongStream extends BaseStream {
              */
             public static LongStream generate(LongSupplier s) {
                 Objects.requireNonNull(s);
        -        return StreamSupport.longStream(Spliterators.spliteratorUnknownSize(
        -                new PrimitiveIterator.OfLong() {
        -                    @Override
        -                    public boolean hasNext() { return true; }
        -
        -                    @Override
        -                    public long nextLong() { return s.getAsLong(); }
        -                },
        -                Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL));
        +        return StreamSupport.longStream(
        +                new StreamSpliterators.InfiniteSupplyingSpliterator.OfLong(Long.MAX_VALUE, s));
             }
         
             /**
        diff --git a/src/share/classes/java/util/stream/PipelineHelper.java b/src/share/classes/java/util/stream/PipelineHelper.java
        index 853a1ffac489ec0392386f5a67a01734f0679922..6824e3b3179c034f3e4ee3b16e0ff52dbff65312 100644
        --- a/src/share/classes/java/util/stream/PipelineHelper.java
        +++ b/src/share/classes/java/util/stream/PipelineHelper.java
        @@ -44,7 +44,7 @@ import java.util.function.IntFunction;
          * and {@link AbstractPipeline#opEvaluateParallel(PipelineHelper, java.util.Spliterator,
          * java.util.function.IntFunction)}, methods, which can use the
          * {@code PipelineHelper} to access information about the pipeline such as
        - * input shape, output shape, stream flags, and size, and use the helper methods
        + * head shape, stream flags, and size, and use the helper methods
          * such as {@link #wrapAndCopyInto(Sink, Spliterator)},
          * {@link #copyInto(Sink, Spliterator)}, and {@link #wrapSink(Sink)} to execute
          * pipeline operations.
        @@ -54,6 +54,13 @@ import java.util.function.IntFunction;
          */
         abstract class PipelineHelper {
         
        +    /**
        +     * Gets the stream shape for the source of the pipeline segment.
        +     *
        +     * @return the stream shape for the source of the pipeline segment.
        +     */
        +    abstract StreamShape getSourceShape();
        +
             /**
              * Gets the combined stream and operation flags for the output of the described
              * pipeline.  This will incorporate stream flags from the stream source, all
        @@ -145,6 +152,14 @@ abstract class PipelineHelper {
              */
             abstract Sink wrapSink(Sink sink);
         
        +    /**
        +     *
        +     * @param spliterator
        +     * @param 
        +     * @return
        +     */
        +    abstract Spliterator wrapSpliterator(Spliterator spliterator);
        +
             /**
              * Constructs a @{link Node.Builder} compatible with the output shape of
              * this {@code PipelineHelper}.
        diff --git a/src/share/classes/java/util/stream/ReferencePipeline.java b/src/share/classes/java/util/stream/ReferencePipeline.java
        index 6e3beca1f11c6bf6676c9a02c4746b9912c497a6..8a86c2d6c3b0cf4c480774c8ea7e0202f71fe424 100644
        --- a/src/share/classes/java/util/stream/ReferencePipeline.java
        +++ b/src/share/classes/java/util/stream/ReferencePipeline.java
        @@ -25,7 +25,6 @@
         package java.util.stream;
         
         import java.util.Comparator;
        -import java.util.Comparators;
         import java.util.Iterator;
         import java.util.Objects;
         import java.util.Optional;
        @@ -512,12 +511,12 @@ abstract class ReferencePipeline
         
             @Override
             public final Optional max(Comparator comparator) {
        -        return reduce(Comparators.greaterOf(comparator));
        +        return reduce(BinaryOperator.maxBy(comparator));
             }
         
             @Override
             public final Optional min(Comparator comparator) {
        -        return reduce(Comparators.lesserOf(comparator));
        +        return reduce(BinaryOperator.minBy(comparator));
         
             }
         
        diff --git a/src/share/classes/java/util/stream/SliceOps.java b/src/share/classes/java/util/stream/SliceOps.java
        index 31c6bd82446524fe72e0c177646dbe7baad1b339..78fd3d7f0d5f4508aabfb7ce08a4f240d25bf5e0 100644
        --- a/src/share/classes/java/util/stream/SliceOps.java
        +++ b/src/share/classes/java/util/stream/SliceOps.java
        @@ -24,14 +24,9 @@
          */
         package java.util.stream;
         
        -import java.util.ArrayList;
        -import java.util.List;
         import java.util.Spliterator;
         import java.util.concurrent.CountedCompleter;
        -import java.util.function.DoubleConsumer;
        -import java.util.function.IntConsumer;
         import java.util.function.IntFunction;
        -import java.util.function.LongConsumer;
         
         /**
          * Factory for instances of a short-circuiting stateful intermediate operations
        @@ -44,6 +39,63 @@ final class SliceOps {
             // No instances
             private SliceOps() { }
         
        +    /**
        +     * Calculates the sliced size given the current size, number of elements
        +     * skip, and the number of elements to limit.
        +     *
        +     * @param size the current size
        +     * @param skip the number of elements to skip, assumed to be >= 0
        +     * @param limit the number of elements to limit, assumed to be >= 0, with
        +     *        a value of {@code Long.MAX_VALUE} if there is no limit
        +     * @return the sliced size
        +     */
        +    private static long calcSize(long size, long skip, long limit) {
        +        return size >= 0 ? Math.max(-1, Math.min(size - skip, limit)) : -1;
        +    }
        +
        +    /**
        +     * Calculates the slice fence, which is one past the index of the slice
        +     * range
        +     * @param skip the number of elements to skip, assumed to be >= 0
        +     * @param limit the number of elements to limit, assumed to be >= 0, with
        +     *        a value of {@code Long.MAX_VALUE} if there is no limit
        +     * @return the slice fence.
        +     */
        +    private static long calcSliceFence(long skip, long limit) {
        +        long sliceFence = limit >= 0 ? skip + limit : Long.MAX_VALUE;
        +        // Check for overflow
        +        return (sliceFence >= 0) ? sliceFence : Long.MAX_VALUE;
        +    }
        +
        +    /**
        +     * Creates a slice spliterator given a stream shape governing the
        +     * spliterator type.  Requires that the underlying Spliterator
        +     * be SUBSIZED.
        +     */
        +    @SuppressWarnings("unchecked")
        +    private static  Spliterator sliceSpliterator(StreamShape shape,
        +                                                             Spliterator s,
        +                                                             long skip, long limit) {
        +        assert s.hasCharacteristics(Spliterator.SUBSIZED);
        +        long sliceFence = calcSliceFence(skip, limit);
        +        switch (shape) {
        +            case REFERENCE:
        +                return new StreamSpliterators
        +                        .SliceSpliterator.OfRef<>(s, skip, sliceFence);
        +            case INT_VALUE:
        +                return (Spliterator) new StreamSpliterators
        +                        .SliceSpliterator.OfInt((Spliterator.OfInt) s, skip, sliceFence);
        +            case LONG_VALUE:
        +                return (Spliterator) new StreamSpliterators
        +                        .SliceSpliterator.OfLong((Spliterator.OfLong) s, skip, sliceFence);
        +            case DOUBLE_VALUE:
        +                return (Spliterator) new StreamSpliterators
        +                        .SliceSpliterator.OfDouble((Spliterator.OfDouble) s, skip, sliceFence);
        +            default:
        +                throw new IllegalStateException("Unknown shape " + shape);
        +        }
        +    }
        +
             /**
              * Appends a "slice" operation to the provided stream.  The slice operation
              * may be may be skip-only, limit-only, or skip-and-limit.
        @@ -61,11 +113,71 @@ final class SliceOps {
         
                 return new ReferencePipeline.StatefulOp(upstream, StreamShape.REFERENCE,
                                                              flags(limit)) {
        +            Spliterator unorderedSkipLimitSpliterator(Spliterator s,
        +                                                         long skip, long limit, long sizeIfKnown) {
        +                if (skip <= sizeIfKnown) {
        +                    // Use just the limit if the number of elements
        +                    // to skip is <= the known pipeline size
        +                    limit = limit >= 0 ? Math.min(limit, sizeIfKnown - skip) : sizeIfKnown - skip;
        +                    skip = 0;
        +                }
        +                return new StreamSpliterators.UnorderedSliceSpliterator.OfRef<>(s, skip, limit);
        +            }
        +
        +            @Override
        +             Spliterator opEvaluateParallelLazy(PipelineHelper helper, Spliterator spliterator) {
        +                long size = helper.exactOutputSizeIfKnown(spliterator);
        +                if (size > 0 && spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
        +                    return new StreamSpliterators.SliceSpliterator.OfRef<>(
        +                            helper.wrapSpliterator(spliterator),
        +                            skip,
        +                            calcSliceFence(skip, limit));
        +                } else if (!StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
        +                    return unorderedSkipLimitSpliterator(
        +                            helper.wrapSpliterator(spliterator),
        +                            skip, limit, size);
        +                }
        +                else {
        +                    // @@@ OOMEs will occur for LongStream.longs().filter(i -> true).limit(n)
        +                    //     regardless of the value of n
        +                    //     Need to adjust the target size of splitting for the
        +                    //     SliceTask from say (size / k) to say min(size / k, 1 << 14)
        +                    //     This will limit the size of the buffers created at the leaf nodes
        +                    //     cancellation will be more aggressive cancelling later tasks
        +                    //     if the target slice size has been reached from a given task,
        +                    //     cancellation should also clear local results if any
        +                    return new SliceTask<>(this, helper, spliterator, i -> (T[]) new Object[i], skip, limit).
        +                            invoke().spliterator();
        +                }
        +            }
        +
                     @Override
                      Node opEvaluateParallel(PipelineHelper helper,
                                                       Spliterator spliterator,
                                                       IntFunction generator) {
        -                return new SliceTask<>(this, helper, spliterator, generator, skip, limit).invoke();
        +                long size = helper.exactOutputSizeIfKnown(spliterator);
        +                if (size > 0 && spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
        +                    // Because the pipeline is SIZED the slice spliterator
        +                    // can be created from the source, this requires matching
        +                    // to shape of the source, and is potentially more efficient
        +                    // than creating the slice spliterator from the pipeline
        +                    // wrapping spliterator
        +                    Spliterator s = sliceSpliterator(helper.getSourceShape(), spliterator, skip, limit);
        +                    return Nodes.collect(helper, s, true, generator);
        +                } else if (!StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
        +                    Spliterator s =  unorderedSkipLimitSpliterator(
        +                            helper.wrapSpliterator(spliterator),
        +                            skip, limit, size);
        +                    // Collect using this pipeline, which is empty and therefore
        +                    // can be used with the pipeline wrapping spliterator
        +                    // Note that we cannot create a slice spliterator from
        +                    // the source spliterator if the pipeline is not SIZED
        +                    return Nodes.collect(this, s, true, generator);
        +                }
        +                else {
        +                    return new SliceTask<>(this, helper, spliterator, generator, skip, limit).
        +                            invoke();
        +                }
                     }
         
                     @Override
        @@ -74,6 +186,11 @@ final class SliceOps {
                             long n = skip;
                             long m = limit >= 0 ? limit : Long.MAX_VALUE;
         
        +                    @Override
        +                    public void begin(long size) {
        +                        downstream.begin(calcSize(size, skip, m));
        +                    }
        +
                             @Override
                             public void accept(T t) {
                                 if (n == 0) {
        @@ -112,11 +229,64 @@ final class SliceOps {
         
                 return new IntPipeline.StatefulOp(upstream, StreamShape.INT_VALUE,
                                                            flags(limit)) {
        +            Spliterator.OfInt unorderedSkipLimitSpliterator(
        +                    Spliterator.OfInt s, long skip, long limit, long sizeIfKnown) {
        +                if (skip <= sizeIfKnown) {
        +                    // Use just the limit if the number of elements
        +                    // to skip is <= the known pipeline size
        +                    limit = limit >= 0 ? Math.min(limit, sizeIfKnown - skip) : sizeIfKnown - skip;
        +                    skip = 0;
        +                }
        +                return new StreamSpliterators.UnorderedSliceSpliterator.OfInt(s, skip, limit);
        +            }
        +
        +            @Override
        +             Spliterator opEvaluateParallelLazy(PipelineHelper helper,
        +                                                               Spliterator spliterator) {
        +                long size = helper.exactOutputSizeIfKnown(spliterator);
        +                if (size > 0 && spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
        +                    return new StreamSpliterators.SliceSpliterator.OfInt(
        +                            (Spliterator.OfInt) helper.wrapSpliterator(spliterator),
        +                            skip,
        +                            calcSliceFence(skip, limit));
        +                } else if (!StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
        +                    return unorderedSkipLimitSpliterator(
        +                            (Spliterator.OfInt) helper.wrapSpliterator(spliterator),
        +                            skip, limit, size);
        +                }
        +                else {
        +                    return new SliceTask<>(this, helper, spliterator, Integer[]::new, skip, limit).
        +                            invoke().spliterator();
        +                }
        +            }
        +
                     @Override
                      Node opEvaluateParallel(PipelineHelper helper,
                                                             Spliterator spliterator,
                                                             IntFunction generator) {
        -                return new SliceTask<>(this, helper, spliterator, generator, skip, limit).invoke();
        +                long size = helper.exactOutputSizeIfKnown(spliterator);
        +                if (size > 0 && spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
        +                    // Because the pipeline is SIZED the slice spliterator
        +                    // can be created from the source, this requires matching
        +                    // to shape of the source, and is potentially more efficient
        +                    // than creating the slice spliterator from the pipeline
        +                    // wrapping spliterator
        +                    Spliterator s = sliceSpliterator(helper.getSourceShape(), spliterator, skip, limit);
        +                    return Nodes.collectInt(helper, s, true);
        +                } else if (!StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
        +                    Spliterator.OfInt s =  unorderedSkipLimitSpliterator(
        +                            (Spliterator.OfInt) helper.wrapSpliterator(spliterator),
        +                            skip, limit, size);
        +                    // Collect using this pipeline, which is empty and therefore
        +                    // can be used with the pipeline wrapping spliterator
        +                    // Note that we cannot create a slice spliterator from
        +                    // the source spliterator if the pipeline is not SIZED
        +                    return Nodes.collectInt(this, s, true);
        +                }
        +                else {
        +                    return new SliceTask<>(this, helper, spliterator, generator, skip, limit).
        +                            invoke();
        +                }
                     }
         
                     @Override
        @@ -125,6 +295,11 @@ final class SliceOps {
                             long n = skip;
                             long m = limit >= 0 ? limit : Long.MAX_VALUE;
         
        +                    @Override
        +                    public void begin(long size) {
        +                        downstream.begin(calcSize(size, skip, m));
        +                    }
        +
                             @Override
                             public void accept(int t) {
                                 if (n == 0) {
        @@ -163,11 +338,64 @@ final class SliceOps {
         
                 return new LongPipeline.StatefulOp(upstream, StreamShape.LONG_VALUE,
                                                          flags(limit)) {
        +            Spliterator.OfLong unorderedSkipLimitSpliterator(
        +                    Spliterator.OfLong s, long skip, long limit, long sizeIfKnown) {
        +                if (skip <= sizeIfKnown) {
        +                    // Use just the limit if the number of elements
        +                    // to skip is <= the known pipeline size
        +                    limit = limit >= 0 ? Math.min(limit, sizeIfKnown - skip) : sizeIfKnown - skip;
        +                    skip = 0;
        +                }
        +                return new StreamSpliterators.UnorderedSliceSpliterator.OfLong(s, skip, limit);
        +            }
        +
        +            @Override
        +             Spliterator opEvaluateParallelLazy(PipelineHelper helper,
        +                                                            Spliterator spliterator) {
        +                long size = helper.exactOutputSizeIfKnown(spliterator);
        +                if (size > 0 && spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
        +                    return new StreamSpliterators.SliceSpliterator.OfLong(
        +                            (Spliterator.OfLong) helper.wrapSpliterator(spliterator),
        +                            skip,
        +                            calcSliceFence(skip, limit));
        +                } else if (!StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
        +                    return unorderedSkipLimitSpliterator(
        +                            (Spliterator.OfLong) helper.wrapSpliterator(spliterator),
        +                            skip, limit, size);
        +                }
        +                else {
        +                    return new SliceTask<>(this, helper, spliterator, Long[]::new, skip, limit).
        +                            invoke().spliterator();
        +                }
        +            }
        +
                     @Override
                      Node opEvaluateParallel(PipelineHelper helper,
                                                          Spliterator spliterator,
                                                          IntFunction generator) {
        -                return new SliceTask<>(this, helper, spliterator, generator, skip, limit).invoke();
        +                long size = helper.exactOutputSizeIfKnown(spliterator);
        +                if (size > 0 && spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
        +                    // Because the pipeline is SIZED the slice spliterator
        +                    // can be created from the source, this requires matching
        +                    // to shape of the source, and is potentially more efficient
        +                    // than creating the slice spliterator from the pipeline
        +                    // wrapping spliterator
        +                    Spliterator s = sliceSpliterator(helper.getSourceShape(), spliterator, skip, limit);
        +                    return Nodes.collectLong(helper, s, true);
        +                } else if (!StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
        +                    Spliterator.OfLong s =  unorderedSkipLimitSpliterator(
        +                            (Spliterator.OfLong) helper.wrapSpliterator(spliterator),
        +                            skip, limit, size);
        +                    // Collect using this pipeline, which is empty and therefore
        +                    // can be used with the pipeline wrapping spliterator
        +                    // Note that we cannot create a slice spliterator from
        +                    // the source spliterator if the pipeline is not SIZED
        +                    return Nodes.collectLong(this, s, true);
        +                }
        +                else {
        +                    return new SliceTask<>(this, helper, spliterator, generator, skip, limit).
        +                            invoke();
        +                }
                     }
         
                     @Override
        @@ -176,6 +404,11 @@ final class SliceOps {
                             long n = skip;
                             long m = limit >= 0 ? limit : Long.MAX_VALUE;
         
        +                    @Override
        +                    public void begin(long size) {
        +                        downstream.begin(calcSize(size, skip, m));
        +                    }
        +
                             @Override
                             public void accept(long t) {
                                 if (n == 0) {
        @@ -214,11 +447,64 @@ final class SliceOps {
         
                 return new DoublePipeline.StatefulOp(upstream, StreamShape.DOUBLE_VALUE,
                                                              flags(limit)) {
        +            Spliterator.OfDouble unorderedSkipLimitSpliterator(
        +                    Spliterator.OfDouble s, long skip, long limit, long sizeIfKnown) {
        +                if (skip <= sizeIfKnown) {
        +                    // Use just the limit if the number of elements
        +                    // to skip is <= the known pipeline size
        +                    limit = limit >= 0 ? Math.min(limit, sizeIfKnown - skip) : sizeIfKnown - skip;
        +                    skip = 0;
        +                }
        +                return new StreamSpliterators.UnorderedSliceSpliterator.OfDouble(s, skip, limit);
        +            }
        +
        +            @Override
        +             Spliterator opEvaluateParallelLazy(PipelineHelper helper,
        +                                                              Spliterator spliterator) {
        +                long size = helper.exactOutputSizeIfKnown(spliterator);
        +                if (size > 0 && spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
        +                    return new StreamSpliterators.SliceSpliterator.OfDouble(
        +                            (Spliterator.OfDouble) helper.wrapSpliterator(spliterator),
        +                            skip,
        +                            calcSliceFence(skip, limit));
        +                } else if (!StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
        +                    return unorderedSkipLimitSpliterator(
        +                            (Spliterator.OfDouble) helper.wrapSpliterator(spliterator),
        +                            skip, limit, size);
        +                }
        +                else {
        +                    return new SliceTask<>(this, helper, spliterator, Double[]::new, skip, limit).
        +                            invoke().spliterator();
        +                }
        +            }
        +
                     @Override
                      Node opEvaluateParallel(PipelineHelper helper,
                                                            Spliterator spliterator,
                                                            IntFunction generator) {
        -                return new SliceTask<>(this, helper, spliterator, generator, skip, limit).invoke();
        +                long size = helper.exactOutputSizeIfKnown(spliterator);
        +                if (size > 0 && spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
        +                    // Because the pipeline is SIZED the slice spliterator
        +                    // can be created from the source, this requires matching
        +                    // to shape of the source, and is potentially more efficient
        +                    // than creating the slice spliterator from the pipeline
        +                    // wrapping spliterator
        +                    Spliterator s = sliceSpliterator(helper.getSourceShape(), spliterator, skip, limit);
        +                    return Nodes.collectDouble(helper, s, true);
        +                } else if (!StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
        +                    Spliterator.OfDouble s =  unorderedSkipLimitSpliterator(
        +                            (Spliterator.OfDouble) helper.wrapSpliterator(spliterator),
        +                            skip, limit, size);
        +                    // Collect using this pipeline, which is empty and therefore
        +                    // can be used with the pipeline wrapping spliterator
        +                    // Note that we cannot create a slice spliterator from
        +                    // the source spliterator if the pipeline is not SIZED
        +                    return Nodes.collectDouble(this, s, true);
        +                }
        +                else {
        +                    return new SliceTask<>(this, helper, spliterator, generator, skip, limit).
        +                            invoke();
        +                }
                     }
         
                     @Override
        @@ -227,6 +513,11 @@ final class SliceOps {
                             long n = skip;
                             long m = limit >= 0 ? limit : Long.MAX_VALUE;
         
        +                    @Override
        +                    public void begin(long size) {
        +                        downstream.begin(calcSize(size, skip, m));
        +                    }
        +
                             @Override
                             public void accept(double t) {
                                 if (n == 0) {
        @@ -253,20 +544,6 @@ final class SliceOps {
                 return StreamOpFlag.NOT_SIZED | ((limit != -1) ? StreamOpFlag.IS_SHORT_CIRCUIT : 0);
             }
         
        -    // Parallel strategy -- two cases
        -    // IF we have full size information
        -    // - decompose, keeping track of each leaf's (offset, size)
        -    // - calculate leaf only if intersection between (offset, size) and desired slice
        -    // - Construct a Node containing the appropriate sections of the appropriate leaves
        -    // IF we don't
        -    // - decompose, and calculate size of each leaf
        -    // - on complete of any node, compute completed initial size from the root, and if big enough, cancel later nodes
        -    // - @@@ this can be significantly improved
        -
        -    // @@@ Currently we don't do the sized version at all
        -
        -    // @@@ Should take into account ORDERED flag; if not ORDERED, we can limit in temporal order instead
        -
             /**
              * {@code ForkJoinTask} implementing slice computation.
              *
        @@ -319,19 +596,18 @@ final class SliceOps {
                                            ? op.exactOutputSizeIfKnown(spliterator)
                                            : -1;
                         final Node.Builder nb = op.makeNodeBuilder(sizeIfKnown, generator);
        -                Sink opSink = op.opWrapSink(op.sourceOrOpFlags, nb);
        -
        -                if (!StreamOpFlag.SHORT_CIRCUIT.isKnown(op.sourceOrOpFlags))
        -                    helper.wrapAndCopyInto(opSink, spliterator);
        -                else
        -                    helper.copyIntoWithCancel(helper.wrapSink(opSink), spliterator);
        -                return nb.build();
        +                Sink opSink = op.opWrapSink(helper.getStreamAndOpFlags(), nb);
        +                helper.copyIntoWithCancel(helper.wrapSink(opSink), spliterator);
        +                // It is necessary to truncate here since the result at the root
        +                // can only be set once
        +                return doTruncate(nb.build());
                     }
                     else {
                         Node node = helper.wrapAndCopyInto(helper.makeNodeBuilder(-1, generator),
        -                                                      spliterator).build();
        +                                                          spliterator).build();
                         thisNodeSize = node.count();
                         completed = true;
        +                spliterator = null;
                         return node;
                     }
                 }
        @@ -339,198 +615,95 @@ final class SliceOps {
                 @Override
                 public final void onCompletion(CountedCompleter caller) {
                     if (!isLeaf()) {
        +                Node result;
                         thisNodeSize = leftChild.thisNodeSize + rightChild.thisNodeSize;
        -                completed = true;
        -
        -                if (isRoot()) {
        -                    // Only collect nodes once absolute size information is known
        -
        -                    ArrayList> nodes = new ArrayList<>();
        -                    visit(nodes, 0);
        -                    Node result;
        -                    if (nodes.size() == 0)
        -                        result = Nodes.emptyNode(op.getOutputShape());
        -                    else if (nodes.size() == 1)
        -                        result = nodes.get(0);
        -                    else
        -                        // This will create a tree of depth 1 and will not be a sub-tree
        -                        // for leaf nodes within the require range
        -                        result = conc(op.getOutputShape(), nodes);
        -                    setLocalResult(result);
        +                if (canceled) {
        +                    thisNodeSize = 0;
        +                    result = getEmptyResult();
        +                }
        +                else if (thisNodeSize == 0)
        +                    result = getEmptyResult();
        +                else if (leftChild.thisNodeSize == 0)
        +                    result = rightChild.getLocalResult();
        +                else {
        +                    result = Nodes.conc(op.getOutputShape(),
        +                                        leftChild.getLocalResult(), rightChild.getLocalResult());
                         }
        +                setLocalResult(isRoot() ? doTruncate(result) : result);
        +                completed = true;
                     }
        -            if (targetSize >= 0) {
        -                if (((SliceTask) getRoot()).leftSize() >= targetOffset + targetSize)
        +            if (targetSize >= 0
        +                && !isRoot()
        +                && isLeftCompleted(targetOffset + targetSize))
                             cancelLaterNodes();
        -            }
        -            // Don't call super.onCompletion(), we don't look at the child nodes until farther up the tree
        +
        +            super.onCompletion(caller);
                 }
         
        -        /** Compute the cumulative size of the longest leading prefix of completed children */
        -        private long leftSize() {
        +        @Override
        +        protected void cancel() {
        +            super.cancel();
                     if (completed)
        -                return thisNodeSize;
        -            else if (isLeaf())
        -                return 0;
        -            else {
        -                long leftSize = 0;
        -                for (SliceTask child = leftChild, p = null; child != p;
        -                     p = child, child = rightChild) {
        -                    if (child.completed)
        -                        leftSize += child.thisNodeSize;
        -                    else {
        -                        leftSize += child.leftSize();
        -                        break;
        -                    }
        -                }
        -                return leftSize;
        -            }
        +                setLocalResult(getEmptyResult());
                 }
         
        -        private void visit(List> results, int offset) {
        -            if (!isLeaf()) {
        -                for (SliceTask child = leftChild, p = null; child != p;
        -                     p = child, child = rightChild) {
        -                    child.visit(results, offset);
        -                    offset += child.thisNodeSize;
        -                }
        -            }
        -            else {
        -                if (results.size() == 0) {
        -                    if (offset + thisNodeSize >= targetOffset)
        -                        results.add(truncateNode(getLocalResult(),
        -                                                 Math.max(0, targetOffset - offset),
        -                                                 targetSize >= 0 ? Math.max(0, offset + thisNodeSize - (targetOffset + targetSize)) : 0));
        -                }
        -                else {
        -                    if (targetSize == -1 || offset < targetOffset + targetSize) {
        -                        results.add(truncateNode(getLocalResult(),
        -                                                 0,
        -                                                 targetSize >= 0 ? Math.max(0, offset + thisNodeSize - (targetOffset + targetSize)) : 0));
        -                    }
        -                }
        -            }
        +        private Node doTruncate(Node input) {
        +            long to = targetSize >= 0 ? Math.min(input.count(), targetOffset + targetSize) : thisNodeSize;
        +            return input.truncate(targetOffset, to, generator);
                 }
         
                 /**
        -         * Return a new node describing the result of truncating an existing Node
        -         * at the left and/or right.
        -         */
        -        private Node truncateNode(Node input,
        -                                         long skipLeft, long skipRight) {
        -            if (skipLeft == 0 && skipRight == 0)
        -                return input;
        -            else {
        -                return truncateNode(input, skipLeft, thisNodeSize - skipRight, generator);
        -            }
        -        }
        -        /**
        -         * Truncate a {@link Node}, returning a node describing a subsequence of
        -         * the contents of the input node.
        +         * Determine if the number of completed elements in this node and nodes
        +         * to the left of this node is greater than or equal to the target size.
                  *
        -         * @param  the type of elements of the input node and truncated node
        -         * @param input the input node
        -         * @param from the starting offset to include in the truncated node (inclusive)
        -         * @param to the ending offset ot include in the truncated node (exclusive)
        -         * @param generator the array factory (only used for reference nodes)
        -         * @return the truncated node
        +         * @param target the target size
        +         * @return true if the number of elements is greater than or equal to
        +         *         the target size, otherwise false.
                  */
        -        @SuppressWarnings("unchecked")
        -        private static  Node truncateNode(Node input, long from, long to, IntFunction generator) {
        -            StreamShape shape = input.getShape();
        -            long size = truncatedSize(input.count(), from, to);
        -            if (size == 0)
        -                return Nodes.emptyNode(shape);
        -            else if (from == 0 && to >= input.count())
        -                return input;
        -
        -            switch (shape) {
        -                case REFERENCE: {
        -                    Spliterator spliterator = input.spliterator();
        -                    Node.Builder nodeBuilder = Nodes.builder(size, generator);
        -                    nodeBuilder.begin(size);
        -                    for (int i = 0; i < from && spliterator.tryAdvance(e -> { }); i++) { }
        -                    for (int i = 0; (i < size) && spliterator.tryAdvance(nodeBuilder); i++) { }
        -                    nodeBuilder.end();
        -                    return nodeBuilder.build();
        -                }
        -                case INT_VALUE: {
        -                    Spliterator.OfInt spliterator = ((Node.OfInt) input).spliterator();
        -                    Node.Builder.OfInt nodeBuilder = Nodes.intBuilder(size);
        -                    nodeBuilder.begin(size);
        -                    for (int i = 0; i < from && spliterator.tryAdvance((IntConsumer) e -> { }); i++) { }
        -                    for (int i = 0; (i < size) && spliterator.tryAdvance((IntConsumer) nodeBuilder); i++) { }
        -                    nodeBuilder.end();
        -                    return (Node) nodeBuilder.build();
        -                }
        -                case LONG_VALUE: {
        -                    Spliterator.OfLong spliterator = ((Node.OfLong) input).spliterator();
        -                    Node.Builder.OfLong nodeBuilder = Nodes.longBuilder(size);
        -                    nodeBuilder.begin(size);
        -                    for (int i = 0; i < from && spliterator.tryAdvance((LongConsumer) e -> { }); i++) { }
        -                    for (int i = 0; (i < size) && spliterator.tryAdvance((LongConsumer) nodeBuilder); i++) { }
        -                    nodeBuilder.end();
        -                    return (Node) nodeBuilder.build();
        -                }
        -                case DOUBLE_VALUE: {
        -                    Spliterator.OfDouble spliterator = ((Node.OfDouble) input).spliterator();
        -                    Node.Builder.OfDouble nodeBuilder = Nodes.doubleBuilder(size);
        -                    nodeBuilder.begin(size);
        -                    for (int i = 0; i < from && spliterator.tryAdvance((DoubleConsumer) e -> { }); i++) { }
        -                    for (int i = 0; (i < size) && spliterator.tryAdvance((DoubleConsumer) nodeBuilder); i++) { }
        -                    nodeBuilder.end();
        -                    return (Node) nodeBuilder.build();
        +        private boolean isLeftCompleted(long target) {
        +            long size = completed ? thisNodeSize : completedSize(target);
        +            if (size >= target)
        +                return true;
        +            for (SliceTask parent = getParent(), node = this;
        +                 parent != null;
        +                 node = parent, parent = parent.getParent()) {
        +                if (node == parent.rightChild) {
        +                    SliceTask left = parent.leftChild;
        +                    if (left != null) {
        +                        size += left.completedSize(target);
        +                        if (size >= target)
        +                            return true;
        +                    }
                         }
        -                default:
        -                    throw new IllegalStateException("Unknown shape " + shape);
                     }
        -        }
        -
        -        private static long truncatedSize(long size, long from, long to) {
        -            if (from >= 0)
        -                size = Math.max(0, size - from);
        -            long limit = to - from;
        -            if (limit >= 0)
        -                size = Math.min(size, limit);
        -            return size;
        +            return size >= target;
                 }
         
                 /**
        -         * Produces a concatenated {@link Node} that has two or more children.
        -         * 

        The count of the concatenated node is equal to the sum of the count - * of each child. Traversal of the concatenated node traverses the content - * of each child in encounter order of the list of children. Splitting a - * spliterator obtained from the concatenated node preserves the encounter - * order of the list of children. + * Compute the number of completed elements in this node. + *

        + * Computation terminates if all nodes have been processed or the + * number of completed elements is greater than or equal to the target + * size. * - *

        The result may be a concatenated node, the input sole node if the size - * of the list is 1, or an empty node. - * - * @param the type of elements of the concatenated node - * @param shape the shape of the concatenated node to be created - * @param nodes the input nodes - * @return a {@code Node} covering the elements of the input nodes - * @throws IllegalStateException if all {@link Node} elements of the list - * are an not instance of type supported by this factory. + * @param target the target size + * @return return the number of completed elements */ - @SuppressWarnings("unchecked") - private static Node conc(StreamShape shape, List> nodes) { - int size = nodes.size(); - if (size == 0) - return Nodes.emptyNode(shape); - else if (size == 1) - return nodes.get(0); + private long completedSize(long target) { + if (completed) + return thisNodeSize; else { - // Create a right-balanced tree when there are more that 2 nodes - List> refNodes = (List>) nodes; - Node c = Nodes.conc(shape, refNodes.get(size - 2), refNodes.get(size - 1)); - for (int i = size - 3; i >= 0; i--) { - c = Nodes.conc(shape, refNodes.get(i), c); + SliceTask left = leftChild; + SliceTask right = rightChild; + if (left == null || right == null) { + // must be completed + return thisNodeSize; + } + else { + long leftSize = left.completedSize(target); + return (leftSize >= target) ? leftSize : leftSize + right.completedSize(target); } - return c; } } - } - } diff --git a/src/share/classes/java/util/stream/SortedOps.java b/src/share/classes/java/util/stream/SortedOps.java index 7b2a6934b4e4d06deaf076907e846e6719e88bcb..de02ba8e32f052489968ab6195fe856d78b705d0 100644 --- a/src/share/classes/java/util/stream/SortedOps.java +++ b/src/share/classes/java/util/stream/SortedOps.java @@ -27,7 +27,6 @@ package java.util.stream; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; -import java.util.Comparators; import java.util.Objects; import java.util.Spliterator; import java.util.concurrent.ForkJoinTask; @@ -114,7 +113,7 @@ final class SortedOps { StreamOpFlag.IS_ORDERED | StreamOpFlag.IS_SORTED); this.isNaturalSort = true; // Will throw CCE when we try to sort if T is not Comparable - this.comparator = (Comparator) Comparators.naturalOrder(); + this.comparator = (Comparator) Comparator.naturalOrder(); } /** diff --git a/src/share/classes/java/util/stream/Stream.java b/src/share/classes/java/util/stream/Stream.java index f06a01b7aea0c6a99ec6175e4342d0f78b2ae913..32b3585fdbff08b161e39601169e43cb0c483a60 100644 --- a/src/share/classes/java/util/stream/Stream.java +++ b/src/share/classes/java/util/stream/Stream.java @@ -880,14 +880,7 @@ public interface Stream extends BaseStream> { */ public static Stream generate(Supplier s) { Objects.requireNonNull(s); - return StreamSupport.stream(Spliterators.spliteratorUnknownSize( - new Iterator() { - @Override - public boolean hasNext() { return true; } - - @Override - public T next() { return s.get(); } - }, - Spliterator.ORDERED | Spliterator.IMMUTABLE)); + return StreamSupport.stream( + new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s)); } } diff --git a/src/share/classes/java/util/stream/StreamSpliterators.java b/src/share/classes/java/util/stream/StreamSpliterators.java index ff669dbaa18839630e11e394923b643f5e3585cb..d0dc61ed1e09622c187917483f04c3402ea15152 100644 --- a/src/share/classes/java/util/stream/StreamSpliterators.java +++ b/src/share/classes/java/util/stream/StreamSpliterators.java @@ -26,11 +26,15 @@ package java.util.stream; import java.util.Comparator; import java.util.Spliterator; +import java.util.concurrent.atomic.AtomicLong; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.DoubleConsumer; +import java.util.function.DoubleSupplier; import java.util.function.IntConsumer; +import java.util.function.IntSupplier; import java.util.function.LongConsumer; +import java.util.function.LongSupplier; import java.util.function.Supplier; /** @@ -212,9 +216,10 @@ class StreamSpliterators { @Override public final long estimateSize() { init(); - return StreamOpFlag.SIZED.isKnown(ph.getStreamAndOpFlags()) - ? spliterator.estimateSize() - : Long.MAX_VALUE; + // Use the estimate of the wrapped spliterator + // Note this may not be accurate if there are filter/flatMap + // operations filtering or adding elements to the stream + return spliterator.estimateSize(); } @Override @@ -240,7 +245,7 @@ class StreamSpliterators { // but for sub-splits only an estimate is known if ((c & Spliterator.SIZED) != 0) { c &= ~(Spliterator.SIZED | Spliterator.SUBSIZED); - c |= (spliterator.characteristics() & Spliterator.SIZED & Spliterator.SUBSIZED); + c |= (spliterator.characteristics() & (Spliterator.SIZED | Spliterator.SUBSIZED)); } return c; @@ -304,7 +309,7 @@ class StreamSpliterators { finished = true; } else { - while (tryAdvance(consumer)) { } + do { } while (tryAdvance(consumer)); } } } @@ -360,7 +365,7 @@ class StreamSpliterators { finished = true; } else { - while (tryAdvance(consumer)) { } + do { } while (tryAdvance(consumer)); } } } @@ -416,7 +421,7 @@ class StreamSpliterators { finished = true; } else { - while (tryAdvance(consumer)) { } + do { } while (tryAdvance(consumer)); } } } @@ -472,7 +477,7 @@ class StreamSpliterators { finished = true; } else { - while (tryAdvance(consumer)) { } + do { } while (tryAdvance(consumer)); } } } @@ -483,17 +488,17 @@ class StreamSpliterators { * first call to any spliterator method. * @param */ - static class DelegatingSpliterator implements Spliterator { - private final Supplier> supplier; + static class DelegatingSpliterator> + implements Spliterator { + private final Supplier supplier; - private Spliterator s; + private T_SPLITR s; - @SuppressWarnings("unchecked") - DelegatingSpliterator(Supplier> supplier) { - this.supplier = (Supplier>) supplier; + DelegatingSpliterator(Supplier supplier) { + this.supplier = supplier; } - Spliterator get() { + T_SPLITR get() { if (s == null) { s = supplier.get(); } @@ -501,8 +506,8 @@ class StreamSpliterators { } @Override - public Spliterator trySplit() { - return get().trySplit(); + public T_SPLITR trySplit() { + return (T_SPLITR) get().trySplit(); } @Override @@ -540,97 +545,881 @@ class StreamSpliterators { return getClass().getName() + "[" + get() + "]"; } - static final class OfInt extends DelegatingSpliterator implements Spliterator.OfInt { - private Spliterator.OfInt s; + static class OfPrimitive> + extends DelegatingSpliterator + implements Spliterator.OfPrimitive { + OfPrimitive(Supplier supplier) { + super(supplier); + } + + @Override + public boolean tryAdvance(T_CONS consumer) { + return get().tryAdvance(consumer); + } + + @Override + public void forEachRemaining(T_CONS consumer) { + get().forEachRemaining(consumer); + } + } + + static final class OfInt + extends OfPrimitive + implements Spliterator.OfInt { OfInt(Supplier supplier) { super(supplier); } + } + + static final class OfLong + extends OfPrimitive + implements Spliterator.OfLong { + + OfLong(Supplier supplier) { + super(supplier); + } + } + + static final class OfDouble + extends OfPrimitive + implements Spliterator.OfDouble { + + OfDouble(Supplier supplier) { + super(supplier); + } + } + } + + /** + * A slice Spliterator from a source Spliterator that reports + * {@code SUBSIZED}. + * + */ + static abstract class SliceSpliterator> { + // The start index of the slice + final long sliceOrigin; + // One past the last index of the slice + final long sliceFence; + + // The spliterator to slice + T_SPLITR s; + // current (absolute) index, modified on advance/split + long index; + // one past last (absolute) index or sliceFence, which ever is smaller + long fence; + + SliceSpliterator(T_SPLITR s, long sliceOrigin, long sliceFence, long origin, long fence) { + assert s.hasCharacteristics(Spliterator.SUBSIZED); + this.s = s; + this.sliceOrigin = sliceOrigin; + this.sliceFence = sliceFence; + this.index = origin; + this.fence = fence; + } + + protected abstract T_SPLITR makeSpliterator(T_SPLITR s, long sliceOrigin, long sliceFence, long origin, long fence); + + public T_SPLITR trySplit() { + if (sliceOrigin >= fence) + return null; + + if (index >= fence) + return null; + + // Keep splitting until the left and right splits intersect with the slice + // thereby ensuring the size estimate decreases. + // This also avoids creating empty spliterators which can result in + // existing and additionally created F/J tasks that perform + // redundant work on no elements. + while (true) { + T_SPLITR leftSplit = (T_SPLITR) s.trySplit(); + if (leftSplit == null) + return null; + + long leftSplitFenceUnbounded = index + leftSplit.estimateSize(); + long leftSplitFence = Math.min(leftSplitFenceUnbounded, sliceFence); + if (sliceOrigin >= leftSplitFence) { + // The left split does not intersect with, and is to the left of, the slice + // The right split does intersect + // Discard the left split and split further with the right split + index = leftSplitFence; + } + else if (leftSplitFence >= sliceFence) { + // The right split does not intersect with, and is to the right of, the slice + // The left split does intersect + // Discard the right split and split further with the left split + s = leftSplit; + fence = leftSplitFence; + } + else if (index >= sliceOrigin && leftSplitFenceUnbounded <= sliceFence) { + // The left split is contained within the slice, return the underlying left split + // Right split is contained within or intersects with the slice + index = leftSplitFence; + return leftSplit; + } else { + // The left split intersects with the slice + // Right split is contained within or intersects with the slice + return makeSpliterator(leftSplit, sliceOrigin, sliceFence, index, index = leftSplitFence); + } + } + } + + public long estimateSize() { + return (sliceOrigin < fence) + ? fence - Math.max(sliceOrigin, index) : 0; + } + + public int characteristics() { + return s.characteristics(); + } + + static final class OfRef + extends SliceSpliterator> + implements Spliterator { + + OfRef(Spliterator s, long sliceOrigin, long sliceFence) { + this(s, sliceOrigin, sliceFence, 0, Math.min(s.estimateSize(), sliceFence)); + } + + private OfRef(Spliterator s, + long sliceOrigin, long sliceFence, long origin, long fence) { + super(s, sliceOrigin, sliceFence, origin, fence); + } @Override - Spliterator.OfInt get() { - if (s == null) { - s = (Spliterator.OfInt) super.get(); + protected Spliterator makeSpliterator(Spliterator s, + long sliceOrigin, long sliceFence, + long origin, long fence) { + return new OfRef<>(s, sliceOrigin, sliceFence, origin, fence); + } + + @Override + public boolean tryAdvance(Consumer action) { + if (sliceOrigin >= fence) + return false; + + while (sliceOrigin > index) { + s.tryAdvance(e -> {}); + index++; } - return s; + + if (index >= fence) + return false; + + index++; + return s.tryAdvance(action); } @Override - public Spliterator.OfInt trySplit() { - return get().trySplit(); + public void forEachRemaining(Consumer action) { + if (sliceOrigin >= fence) + return; + + if (index >= fence) + return; + + if (index >= sliceOrigin && (index + s.estimateSize()) <= sliceFence) { + // The spliterator is contained within the slice + s.forEachRemaining(action); + index = fence; + } else { + // The spliterator intersects with the slice + while (sliceOrigin > index) { + s.tryAdvance(e -> {}); + index++; + } + // Traverse elements up to the fence + for (;index < fence; index++) { + s.tryAdvance(action); + } + } + } + } + + static abstract class OfPrimitive, + T_CONS> + extends SliceSpliterator + implements Spliterator.OfPrimitive { + + OfPrimitive(T_SPLITR s, long sliceOrigin, long sliceFence) { + this(s, sliceOrigin, sliceFence, 0, Math.min(s.estimateSize(), sliceFence)); + } + + private OfPrimitive(T_SPLITR s, + long sliceOrigin, long sliceFence, long origin, long fence) { + super(s, sliceOrigin, sliceFence, origin, fence); } @Override - public boolean tryAdvance(IntConsumer consumer) { - return get().tryAdvance(consumer); + public boolean tryAdvance(T_CONS action) { + if (sliceOrigin >= fence) + return false; + + while (sliceOrigin > index) { + s.tryAdvance(emptyConsumer()); + index++; + } + + if (index >= fence) + return false; + + index++; + return s.tryAdvance(action); } @Override - public void forEachRemaining(IntConsumer consumer) { - get().forEachRemaining(consumer); + public void forEachRemaining(T_CONS action) { + if (sliceOrigin >= fence) + return; + + if (index >= fence) + return; + + if (index >= sliceOrigin && (index + s.estimateSize()) <= sliceFence) { + // The spliterator is contained within the slice + s.forEachRemaining(action); + index = fence; + } else { + // The spliterator intersects with the slice + while (sliceOrigin > index) { + s.tryAdvance(emptyConsumer()); + index++; + } + // Traverse elements up to the fence + for (;index < fence; index++) { + s.tryAdvance(action); + } + } + } + + protected abstract T_CONS emptyConsumer(); + } + + static final class OfInt extends OfPrimitive + implements Spliterator.OfInt { + OfInt(Spliterator.OfInt s, long sliceOrigin, long sliceFence) { + super(s, sliceOrigin, sliceFence); + } + + OfInt(Spliterator.OfInt s, + long sliceOrigin, long sliceFence, long origin, long fence) { + super(s, sliceOrigin, sliceFence, origin, fence); + } + + @Override + protected Spliterator.OfInt makeSpliterator(Spliterator.OfInt s, + long sliceOrigin, long sliceFence, + long origin, long fence) { + return new SliceSpliterator.OfInt(s, sliceOrigin, sliceFence, origin, fence); + } + + @Override + protected IntConsumer emptyConsumer() { + return e -> {}; } } - static final class OfLong extends DelegatingSpliterator implements Spliterator.OfLong { - private Spliterator.OfLong s; + static final class OfLong extends OfPrimitive + implements Spliterator.OfLong { + OfLong(Spliterator.OfLong s, long sliceOrigin, long sliceFence) { + super(s, sliceOrigin, sliceFence); + } - OfLong(Supplier supplier) { - super(supplier); + OfLong(Spliterator.OfLong s, + long sliceOrigin, long sliceFence, long origin, long fence) { + super(s, sliceOrigin, sliceFence, origin, fence); + } + + @Override + protected Spliterator.OfLong makeSpliterator(Spliterator.OfLong s, + long sliceOrigin, long sliceFence, + long origin, long fence) { + return new SliceSpliterator.OfLong(s, sliceOrigin, sliceFence, origin, fence); + } + + @Override + protected LongConsumer emptyConsumer() { + return e -> {}; + } + } + + static final class OfDouble extends OfPrimitive + implements Spliterator.OfDouble { + OfDouble(Spliterator.OfDouble s, long sliceOrigin, long sliceFence) { + super(s, sliceOrigin, sliceFence); + } + + OfDouble(Spliterator.OfDouble s, + long sliceOrigin, long sliceFence, long origin, long fence) { + super(s, sliceOrigin, sliceFence, origin, fence); + } + + @Override + protected Spliterator.OfDouble makeSpliterator(Spliterator.OfDouble s, + long sliceOrigin, long sliceFence, + long origin, long fence) { + return new SliceSpliterator.OfDouble(s, sliceOrigin, sliceFence, origin, fence); + } + + @Override + protected DoubleConsumer emptyConsumer() { + return e -> {}; + } + } + } + + /** + * A slice Spliterator that does not preserve order, if any, of a source + * Spliterator. + * + * Note: The source spliterator may report {@code ORDERED} since that + * spliterator be the result of a previous pipeline stage that was + * collected to a {@code Node}. It is the order of the pipeline stage + * that governs whether the this slice spliterator is to be used or not. + */ + static abstract class UnorderedSliceSpliterator> { + static final int CHUNK_SIZE = 1 << 7; + + // The spliterator to slice + protected final T_SPLITR s; + protected final boolean unlimited; + private final long skipThreshold; + private final AtomicLong permits; + + UnorderedSliceSpliterator(T_SPLITR s, long skip, long limit) { + this.s = s; + this.unlimited = limit < 0; + this.skipThreshold = limit >= 0 ? limit : 0; + this.permits = new AtomicLong(limit >= 0 ? skip + limit : skip); + } + + UnorderedSliceSpliterator(T_SPLITR s, UnorderedSliceSpliterator parent) { + this.s = s; + this.unlimited = parent.unlimited; + this.permits = parent.permits; + this.skipThreshold = parent.skipThreshold; + } + + /** + * Acquire permission to skip or process elements. The caller must + * first acquire the elements, then consult this method for guidance + * as to what to do with the data. + * + *

        We use an {@code AtomicLong} to atomically maintain a counter, + * which is initialized as skip+limit if we are limiting, or skip only + * if we are not limiting. The user should consult the method + * {@code checkPermits()} before acquiring data elements. + * + * @param numElements the number of elements the caller has in hand + * @return the number of elements that should be processed; any + * remaining elements should be discarded. + */ + protected final long acquirePermits(long numElements) { + long remainingPermits; + long grabbing; + // permits never increase, and don't decrease below zero + assert numElements > 0; + do { + remainingPermits = permits.get(); + if (remainingPermits == 0) + return unlimited ? numElements : 0; + grabbing = Math.min(remainingPermits, numElements); + } while (grabbing > 0 && + !permits.compareAndSet(remainingPermits, remainingPermits - grabbing)); + + if (unlimited) + return Math.max(numElements - grabbing, 0); + else if (remainingPermits > skipThreshold) + return Math.max(grabbing - (remainingPermits - skipThreshold), 0); + else + return grabbing; + } + + enum PermitStatus { NO_MORE, MAYBE_MORE, UNLIMITED } + + /** Call to check if permits might be available before acquiring data */ + protected final PermitStatus permitStatus() { + if (permits.get() > 0) + return PermitStatus.MAYBE_MORE; + else + return unlimited ? PermitStatus.UNLIMITED : PermitStatus.NO_MORE; + } + + public final T_SPLITR trySplit() { + // Stop splitting when there are no more limit permits + if (permits.get() == 0) + return null; + T_SPLITR split = (T_SPLITR) s.trySplit(); + return split == null ? null : makeSpliterator(split); + } + + protected abstract T_SPLITR makeSpliterator(T_SPLITR s); + + public final long estimateSize() { + return s.estimateSize(); + } + + public final int characteristics() { + return s.characteristics() & + ~(Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED); + } + + static final class OfRef extends UnorderedSliceSpliterator> + implements Spliterator, Consumer { + T tmpSlot; + + OfRef(Spliterator s, long skip, long limit) { + super(s, skip, limit); + } + + OfRef(Spliterator s, OfRef parent) { + super(s, parent); + } + + @Override + public final void accept(T t) { + tmpSlot = t; } @Override - Spliterator.OfLong get() { - if (s == null) { - s = (Spliterator.OfLong) super.get(); + public boolean tryAdvance(Consumer action) { + while (permitStatus() != PermitStatus.NO_MORE) { + if (!s.tryAdvance(this)) + return false; + else if (acquirePermits(1) == 1) { + action.accept(tmpSlot); + tmpSlot = null; + return true; + } } - return s; + return false; + } + + @Override + public void forEachRemaining(Consumer action) { + ArrayBuffer.OfRef sb = null; + PermitStatus permitStatus; + while ((permitStatus = permitStatus()) != PermitStatus.NO_MORE) { + if (permitStatus == PermitStatus.MAYBE_MORE) { + // Optimistically traverse elements up to a threshold of CHUNK_SIZE + if (sb == null) + sb = new ArrayBuffer.OfRef<>(CHUNK_SIZE); + else + sb.reset(); + long permitsRequested = 0; + do { } while (s.tryAdvance(sb) && ++permitsRequested < CHUNK_SIZE); + if (permitsRequested == 0) + return; + sb.forEach(action, acquirePermits(permitsRequested)); + } + else { + // Must be UNLIMITED; let 'er rip + s.forEachRemaining(action); + return; + } + } + } + + @Override + protected Spliterator makeSpliterator(Spliterator s) { + return new UnorderedSliceSpliterator.OfRef<>(s, this); + } + } + + /** + * Concrete sub-types must also be an instance of type {@code T_CONS}. + * + * @param the type of the spined buffer. Must also be a type of + * {@code T_CONS}. + */ + static abstract class OfPrimitive< + T, + T_CONS, + T_BUFF extends ArrayBuffer.OfPrimitive, + T_SPLITR extends Spliterator.OfPrimitive> + extends UnorderedSliceSpliterator + implements Spliterator.OfPrimitive { + OfPrimitive(T_SPLITR s, long skip, long limit) { + super(s, skip, limit); + } + + OfPrimitive(T_SPLITR s, UnorderedSliceSpliterator.OfPrimitive parent) { + super(s, parent); + } + + @Override + public boolean tryAdvance(T_CONS action) { + while (permitStatus() != PermitStatus.NO_MORE) { + if (!s.tryAdvance((T_CONS) this)) + return false; + else if (acquirePermits(1) == 1) { + acceptConsumed(action); + return true; + } + } + return false; + } + + protected abstract void acceptConsumed(T_CONS action); + + @Override + public void forEachRemaining(T_CONS action) { + T_BUFF sb = null; + PermitStatus permitStatus; + while ((permitStatus = permitStatus()) != PermitStatus.NO_MORE) { + if (permitStatus == PermitStatus.MAYBE_MORE) { + // Optimistically traverse elements up to a threshold of CHUNK_SIZE + if (sb == null) + sb = bufferCreate(CHUNK_SIZE); + else + sb.reset(); + @SuppressWarnings("unchecked") + T_CONS sbc = (T_CONS) sb; + long permitsRequested = 0; + do { } while (s.tryAdvance(sbc) && ++permitsRequested < CHUNK_SIZE); + if (permitsRequested == 0) + return; + sb.forEach(action, acquirePermits(permitsRequested)); + } + else { + // Must be UNLIMITED; let 'er rip + s.forEachRemaining(action); + return; + } + } + } + + protected abstract T_BUFF bufferCreate(int initialCapacity); + } + + static final class OfInt + extends OfPrimitive + implements Spliterator.OfInt, IntConsumer { + + int tmpValue; + + OfInt(Spliterator.OfInt s, long skip, long limit) { + super(s, skip, limit); + } + + OfInt(Spliterator.OfInt s, UnorderedSliceSpliterator.OfInt parent) { + super(s, parent); + } + + @Override + public void accept(int value) { + tmpValue = value; + } + + @Override + protected void acceptConsumed(IntConsumer action) { + action.accept(tmpValue); + } + + @Override + protected ArrayBuffer.OfInt bufferCreate(int initialCapacity) { + return new ArrayBuffer.OfInt(initialCapacity); + } + + @Override + protected Spliterator.OfInt makeSpliterator(Spliterator.OfInt s) { + return new UnorderedSliceSpliterator.OfInt(s, this); + } + } + + static final class OfLong + extends OfPrimitive + implements Spliterator.OfLong, LongConsumer { + + long tmpValue; + + OfLong(Spliterator.OfLong s, long skip, long limit) { + super(s, skip, limit); + } + + OfLong(Spliterator.OfLong s, UnorderedSliceSpliterator.OfLong parent) { + super(s, parent); + } + + @Override + public void accept(long value) { + tmpValue = value; + } + + @Override + protected void acceptConsumed(LongConsumer action) { + action.accept(tmpValue); + } + + @Override + protected ArrayBuffer.OfLong bufferCreate(int initialCapacity) { + return new ArrayBuffer.OfLong(initialCapacity); + } + + @Override + protected Spliterator.OfLong makeSpliterator(Spliterator.OfLong s) { + return new UnorderedSliceSpliterator.OfLong(s, this); + } + } + + static final class OfDouble + extends OfPrimitive + implements Spliterator.OfDouble, DoubleConsumer { + + double tmpValue; + + OfDouble(Spliterator.OfDouble s, long skip, long limit) { + super(s, skip, limit); + } + + OfDouble(Spliterator.OfDouble s, UnorderedSliceSpliterator.OfDouble parent) { + super(s, parent); + } + + @Override + public void accept(double value) { + tmpValue = value; + } + + @Override + protected void acceptConsumed(DoubleConsumer action) { + action.accept(tmpValue); + } + + @Override + protected ArrayBuffer.OfDouble bufferCreate(int initialCapacity) { + return new ArrayBuffer.OfDouble(initialCapacity); + } + + @Override + protected Spliterator.OfDouble makeSpliterator(Spliterator.OfDouble s) { + return new UnorderedSliceSpliterator.OfDouble(s, this); + } + } + } + + /** + * A Spliterator that infinitely supplies elements in no particular order. + * + *

        Splitting divides the estimated size in two and stops when the + * estimate size is 0. + * + *

        The {@code forEachRemaining} method if invoked will never terminate. + * The {@coe tryAdvance} method always returns true. + * + */ + static abstract class InfiniteSupplyingSpliterator implements Spliterator { + long estimate; + + protected InfiniteSupplyingSpliterator(long estimate) { + this.estimate = estimate; + } + + @Override + public long estimateSize() { + return estimate; + } + + @Override + public int characteristics() { + return IMMUTABLE; + } + + static final class OfRef extends InfiniteSupplyingSpliterator { + final Supplier s; + + OfRef(long size, Supplier s) { + super(size); + this.s = s; + } + + @Override + public boolean tryAdvance(Consumer action) { + action.accept(s.get()); + return true; + } + + @Override + public Spliterator trySplit() { + if (estimate == 0) + return null; + return new InfiniteSupplyingSpliterator.OfRef<>(estimate >>>= 1, s); + } + } + + static final class OfInt extends InfiniteSupplyingSpliterator + implements Spliterator.OfInt { + final IntSupplier s; + + OfInt(long size, IntSupplier s) { + super(size); + this.s = s; + } + + @Override + public boolean tryAdvance(IntConsumer action) { + action.accept(s.getAsInt()); + return true; + } + + @Override + public Spliterator.OfInt trySplit() { + if (estimate == 0) + return null; + return new InfiniteSupplyingSpliterator.OfInt(estimate = estimate >>> 1, s); + } + } + + static final class OfLong extends InfiniteSupplyingSpliterator + implements Spliterator.OfLong { + final LongSupplier s; + + OfLong(long size, LongSupplier s) { + super(size); + this.s = s; + } + + @Override + public boolean tryAdvance(LongConsumer action) { + action.accept(s.getAsLong()); + return true; } @Override public Spliterator.OfLong trySplit() { - return get().trySplit(); + if (estimate == 0) + return null; + return new InfiniteSupplyingSpliterator.OfLong(estimate = estimate >>> 1, s); + } + } + + static final class OfDouble extends InfiniteSupplyingSpliterator + implements Spliterator.OfDouble { + final DoubleSupplier s; + + OfDouble(long size, DoubleSupplier s) { + super(size); + this.s = s; } @Override - public boolean tryAdvance(LongConsumer consumer) { - return get().tryAdvance(consumer); + public boolean tryAdvance(DoubleConsumer action) { + action.accept(s.getAsDouble()); + return true; } @Override - public void forEachRemaining(LongConsumer consumer) { - get().forEachRemaining(consumer); + public Spliterator.OfDouble trySplit() { + if (estimate == 0) + return null; + return new InfiniteSupplyingSpliterator.OfDouble(estimate = estimate >>> 1, s); } } + } - static final class OfDouble extends DelegatingSpliterator implements Spliterator.OfDouble { - private Spliterator.OfDouble s; + // @@@ Consolidate with Node.Builder + static abstract class ArrayBuffer { + int index; - OfDouble(Supplier supplier) { - super(supplier); + void reset() { + index = 0; + } + + static final class OfRef extends ArrayBuffer implements Consumer { + final Object[] array; + + OfRef(int size) { + this.array = new Object[size]; } @Override - Spliterator.OfDouble get() { - if (s == null) { - s = (Spliterator.OfDouble) super.get(); + public void accept(T t) { + array[index++] = t; + } + + public void forEach(Consumer action, long fence) { + for (int i = 0; i < fence; i++) { + @SuppressWarnings("unchecked") + T t = (T) array[i]; + action.accept(t); } - return s; } + } + + static abstract class OfPrimitive extends ArrayBuffer { + int index; @Override - public Spliterator.OfDouble trySplit() { - return get().trySplit(); + void reset() { + index = 0; + } + + abstract void forEach(T_CONS action, long fence); + } + + static final class OfInt extends OfPrimitive + implements IntConsumer { + final int[] array; + + OfInt(int size) { + this.array = new int[size]; } @Override - public boolean tryAdvance(DoubleConsumer consumer) { - return get().tryAdvance(consumer); + public void accept(int t) { + array[index++] = t; } @Override - public void forEachRemaining(DoubleConsumer consumer) { - get().forEachRemaining(consumer); + public void forEach(IntConsumer action, long fence) { + for (int i = 0; i < fence; i++) { + action.accept(array[i]); + } + } + } + + static final class OfLong extends OfPrimitive + implements LongConsumer { + final long[] array; + + OfLong(int size) { + this.array = new long[size]; + } + + @Override + public void accept(long t) { + array[index++] = t; + } + + @Override + public void forEach(LongConsumer action, long fence) { + for (int i = 0; i < fence; i++) { + action.accept(array[i]); + } + } + } + + static final class OfDouble extends OfPrimitive + implements DoubleConsumer { + final double[] array; + + OfDouble(int size) { + this.array = new double[size]; + } + + @Override + public void accept(double t) { + array[index++] = t; + } + + @Override + void forEach(DoubleConsumer action, long fence) { + for (int i = 0; i < fence; i++) { + action.accept(array[i]); + } } } } -} +} \ No newline at end of file diff --git a/src/share/classes/java/util/zip/Deflater.java b/src/share/classes/java/util/zip/Deflater.java index 227c06d1c147f0850f4e6230daa5cd01b72844fd..085287996bee207bf0cba5848ffb956dc1b70a13 100644 --- a/src/share/classes/java/util/zip/Deflater.java +++ b/src/share/classes/java/util/zip/Deflater.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -461,7 +461,7 @@ class Deflater { } /** - * Returns the total number of uncompressed bytes input so far.

        + * Returns the total number of uncompressed bytes input so far. * * @return the total (non-negative) number of uncompressed bytes input so far * @since 1.5 @@ -487,7 +487,7 @@ class Deflater { } /** - * Returns the total number of compressed bytes output so far.

        + * Returns the total number of compressed bytes output so far. * * @return the total (non-negative) number of compressed bytes output so far * @since 1.5 diff --git a/src/share/classes/java/util/zip/Inflater.java b/src/share/classes/java/util/zip/Inflater.java index 25f9d2dcd348d0c5ee501b0b5dc1aa1fb0d1f8b5..c1eefe122d846022a18d18701a5316e10ffcbb5d 100644 --- a/src/share/classes/java/util/zip/Inflater.java +++ b/src/share/classes/java/util/zip/Inflater.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -305,7 +305,7 @@ class Inflater { } /** - * Returns the total number of compressed bytes input so far.

        + * Returns the total number of compressed bytes input so far. * * @return the total (non-negative) number of compressed bytes input so far * @since 1.5 @@ -331,7 +331,7 @@ class Inflater { } /** - * Returns the total number of uncompressed bytes output so far.

        + * Returns the total number of uncompressed bytes output so far. * * @return the total (non-negative) number of uncompressed bytes output so far * @since 1.5 diff --git a/src/share/classes/javax/naming/CompositeName.java b/src/share/classes/javax/naming/CompositeName.java index fe9a09966c84e35d4564ff805061bf2752ce6c1a..ffa837d4a23b6e7a24962f6a8984b341b32f2452 100644 --- a/src/share/classes/javax/naming/CompositeName.java +++ b/src/share/classes/javax/naming/CompositeName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ import java.util.Properties; * The most significant component is at index 0. * An empty composite name has no components. *

        - *

        JNDI Composite Name Syntax

        + *

        JNDI Composite Name Syntax

        * JNDI defines a standard string representation for composite names. This * representation is the concatenation of the components of a composite name * from left to right using the component separator (a forward @@ -73,12 +73,12 @@ import java.util.Properties; * a separator) denotes a trailing empty component. * Adjacent component separators denote an empty component. *

        - *

        Composite Name Examples

        + *

        Composite Name Examples

        *This table shows examples of some composite names. Each row shows *the string form of a composite name and its corresponding structural form *(CompositeName). *

        - +
        @@ -137,14 +137,14 @@ import java.util.Properties;
        String Name
        *

        - *

        Composition Examples

        + *

        Composition Examples

        * Here are some composition examples. The right column shows composing * string composite names while the left column shows composing the * corresponding CompositeNames. Notice that composing the * string forms of two composite names simply involves concatenating * their string forms together. -

        +

        @@ -189,7 +189,7 @@ import java.util.Properties;
        String Names
        *

        - *

        Multithreaded Access

        + *

        Multithreaded Access

        * A CompositeName instance is not synchronized against concurrent * multithreaded access. Multiple threads trying to access and modify a * CompositeName should lock the object. diff --git a/src/share/classes/javax/naming/CompoundName.java b/src/share/classes/javax/naming/CompoundName.java index 76bd672cf0154498125acd02742f6e99d4434458..49269e6bc4a9d4ee037001d3b19566c74029ca3f 100644 --- a/src/share/classes/javax/naming/CompoundName.java +++ b/src/share/classes/javax/naming/CompoundName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,7 +39,7 @@ import java.util.Properties; * The most significant component is at index 0. * An empty compound name has no components. *

        - *

        Compound Name Syntax

        + *

        Compound Name Syntax

        * The syntax of a compound name is specified using a set of properties: *
        *
        jndi.syntax.direction @@ -136,7 +136,7 @@ import java.util.Properties; * so that when the same string is parsed, it will yield the same components * of the original compound name. *

        - *

        Multithreaded Access

        + *

        Multithreaded Access

        * A CompoundName instance is not synchronized against concurrent * multithreaded access. Multiple threads trying to access and modify a * CompoundName should lock the object. diff --git a/src/share/classes/javax/naming/Context.java b/src/share/classes/javax/naming/Context.java index 567c401bf8abbbdd7ec998ad639fdf60a50b99a8..36040e70fe30a7ac6068aa6410abd2ad5f5b2eeb 100644 --- a/src/share/classes/javax/naming/Context.java +++ b/src/share/classes/javax/naming/Context.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,7 @@ import java.util.Hashtable; * consists of a set of name-to-object bindings. * It contains methods for examining and updating these bindings. *

        - *

        Names

        + *

        Names

        * Each name passed as an argument to a Context method is relative * to that context. The empty name is used to name the context itself. * A name parameter may never be null. @@ -69,12 +69,12 @@ import java.util.Hashtable; * names in a composite namespace, at the discretion of the service * provider. *

        - *

        Exceptions

        + *

        Exceptions

        * All the methods in this interface can throw a NamingException or * any of its subclasses. See NamingException and their subclasses * for details on each exception. *

        - *

        Concurrent Access

        + *

        Concurrent Access

        * A Context instance is not guaranteed to be synchronized against * concurrent access by multiple threads. Threads that need to access * a single Context instance concurrently should synchronize amongst @@ -91,7 +91,7 @@ import java.util.Hashtable; * being followed. * *

        - *

        Parameters

        + *

        Parameters

        * A Name parameter passed to any method of the * Context interface or one of its subinterfaces * will not be modified by the service provider. @@ -103,7 +103,7 @@ import java.util.Hashtable; * The caller may subsequently modify it; the service provider may not. * *

        - *

        Environment Properties

        + *

        Environment Properties

        *

        * JNDI applications need a way to communicate various preferences * and properties that define the environment in which naming and @@ -138,7 +138,7 @@ import java.util.Hashtable; * *

        * - *

        Resource Files

        + *

        Resource Files

        *

        * To simplify the task of setting up the environment * required by a JNDI application, @@ -151,11 +151,11 @@ import java.util.Hashtable; * and the value is a string in the format defined * for that property. Here is an example of a JNDI resource file: * - *

        + * 
        {@code * java.naming.factory.object=com.sun.jndi.ldap.AttrsToCorba:com.wiz.from.Person * java.naming.factory.state=com.sun.jndi.ldap.CorbaToAttrs:com.wiz.from.Person * java.naming.factory.control=com.sun.jndi.ldap.ResponseControlFactory - *
        + * } * * The JNDI class library reads the resource files and makes the property * values freely available. Thus JNDI resource files should be considered @@ -165,7 +165,7 @@ import java.util.Hashtable; * There are two kinds of JNDI resource files: * provider and application. * - *
        Provider Resource Files
        + *

        Provider Resource Files

        * * Each service provider has an optional resource that lists properties * specific to that provider. The name of this resource is: @@ -200,7 +200,7 @@ import java.util.Hashtable; * The service provider's documentation should clearly state which * properties are allowed; other properties in the file will be ignored. * - *
        Application Resource Files
        + *

        Application Resource Files

        * * When an application is deployed, it will generally have several * codebase directories and JARs in its classpath. Similarly, when an @@ -232,7 +232,7 @@ import java.util.Hashtable; * collects and uses all of these export lists when searching for factory * classes. * - *
        Search Algorithm for Properties
        + *

        Search Algorithm for Properties

        * * When JNDI constructs an initial context, the context's environment * is initialized with properties defined in the environment parameter diff --git a/src/share/classes/javax/naming/InitialContext.java b/src/share/classes/javax/naming/InitialContext.java index 6dbc5be0518ae0f4326c92ee4eb635ae207e150e..6a10cf6ce72a91d57f2333f167586812c43fdae0 100644 --- a/src/share/classes/javax/naming/InitialContext.java +++ b/src/share/classes/javax/naming/InitialContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -258,6 +258,7 @@ public class InitialContext implements Context { * environment may be modified independently and it may be accessed * concurrently). * + * @param the type of the returned object * @param name * the name of the object to look up * @return the object bound to name @@ -276,11 +277,12 @@ public class InitialContext implements Context { /** * A static method to retrieve the named object. * See {@link #doLookup(Name)} for details. + * @param the type of the returned object * @param name * the name of the object to look up * @return the object bound to name * @throws NamingException if a naming exception is encountered - * @since 1.6 + * @since 1.6 */ @SuppressWarnings("unchecked") public static T doLookup(String name) diff --git a/src/share/classes/javax/naming/RefAddr.java b/src/share/classes/javax/naming/RefAddr.java index 72ca93334d66809f7e19d3eb0a0c9d6a24ef5177..92ac4320f5d90fd2195d855eba60768aaf0022c2 100644 --- a/src/share/classes/javax/naming/RefAddr.java +++ b/src/share/classes/javax/naming/RefAddr.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -91,7 +91,8 @@ public abstract class RefAddr implements java.io.Serializable { * Determines whether obj is equal to this RefAddr. *

        * obj is equal to this RefAddr all of these conditions are true - *

          non-null + *
            + *
          • non-null *
          • instance of RefAddr *
          • obj has the same address type as this RefAddr (using String.compareTo()) *
          • both obj and this RefAddr's contents are null or they are equal diff --git a/src/share/classes/javax/naming/ReferralException.java b/src/share/classes/javax/naming/ReferralException.java index 7c67429a4a9787fa9dc5d3cabc95e981b353fd0e..23d77cf3c65cedf06e3d8bbf2f45dd579623ca93 100644 --- a/src/share/classes/javax/naming/ReferralException.java +++ b/src/share/classes/javax/naming/ReferralException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,7 +38,7 @@ import java.util.Hashtable; * constructors and/or corresponding "set" methods). *

            * The following code sample shows how ReferralException can be used. - *

            + * 
            {@code * while (true) { * try { * bindings = ctx.listBindings(name); @@ -51,7 +51,7 @@ import java.util.Hashtable; * ctx = e.getReferralContext(); * } * } - *

            + * } *

            * ReferralException is an abstract class. Concrete implementations * determine its synchronization and serialization properties. diff --git a/src/share/classes/javax/naming/directory/DirContext.java b/src/share/classes/javax/naming/directory/DirContext.java index 4b9fc59d6b6056c1838643df97fa6034c735c808..e3728792c58c664959da575135a1366d6f3e658e 100644 --- a/src/share/classes/javax/naming/directory/DirContext.java +++ b/src/share/classes/javax/naming/directory/DirContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,7 @@ import javax.naming.*; * methods for examining and updating attributes * associated with objects, and for searching the directory. *

            - *

            Names

            + *

            Names

            * Each name passed as an argument to a DirContext method is relative * to that context. The empty name is used to name the context itself. * The name parameter may never be null. @@ -51,7 +51,7 @@ import javax.naming.*; * name argument to the Context methods. These same rules * apply to the name argument to the DirContext methods. *

            - *

            Attribute Models

            + *

            Attribute Models

            * There are two basic models of what attributes should be * associated with. First, attributes may be directly associated with a * DirContext object. @@ -81,7 +81,7 @@ import javax.naming.*; * whether an object's attributes are stored as part of the object, or stored * within the parent object and associated with the object's name. *

            - *

            Attribute Type Names

            + *

            Attribute Type Names

            * In the getAttributes() and search() methods, * you can supply the attributes to return by supplying a list of * attribute names (strings). @@ -113,7 +113,7 @@ import javax.naming.*; *
          * *

          - *

          Operational Attributes

          + *

          Operational Attributes

          *

          * Some directories have the notion of "operational attributes" which are * attributes associated with a directory object for administrative @@ -127,7 +127,7 @@ import javax.naming.*; * In order to retrieve operational attributes, you must name them explicitly. * *

          - *

          Named Context

          + *

          Named Context

          *

          * There are certain methods in which the name must resolve to a context * (for example, when searching a single level context). The documentation @@ -138,7 +138,7 @@ import javax.naming.*; * Aside from these methods, there is no requirement that the * named object be a DirContext. *

          - *

          Parameters

          + *

          Parameters

          *

          * An Attributes, SearchControls, or array object * passed as a parameter to any method will not be modified by the @@ -150,7 +150,7 @@ import javax.naming.*; * the caller. The caller may subsequently modify it; the service * provider will not. *

          - *

          Exceptions

          + *

          Exceptions

          *

          * All the methods in this interface can throw a NamingException or * any of its subclasses. See NamingException and their subclasses diff --git a/src/share/classes/javax/naming/event/EventContext.java b/src/share/classes/javax/naming/event/EventContext.java index f9ae24935a8d2cb4d2109f0a8bd1c930e44dbcff..fd44876475b98de27be2523cd3f458c1991bd4e1 100644 --- a/src/share/classes/javax/naming/event/EventContext.java +++ b/src/share/classes/javax/naming/event/EventContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,7 +34,7 @@ import javax.naming.NamingException; * Contains methods for registering/deregistering listeners to be notified of * events fired when objects named in a context changes. *

          - *

          Target

          + *

          Target

          * The name parameter in the addNamingListener() methods is referred * to as the target. The target, along with the scope, identify * the object(s) that the listener is interested in. @@ -59,7 +59,7 @@ import javax.naming.NamingException; * whether a EventContext supports registration * of nonexistent targets. *

          - *

          Event Source

          + *

          Event Source

          * The EventContext instance on which you invoke the * registration methods is the event source of the events that are * (potentially) generated. @@ -93,7 +93,7 @@ import javax.naming.NamingException; * it needs to keep a reference to the listener in order to remove it * later). It cannot expect to do a lookup() and get another instance of * a EventContext on which to perform the deregistration. - *

          Lifetime of Registration

          + *

          Lifetime of Registration

          * A registered listener becomes deregistered when: *
            *
          • It is removed using removeNamingListener(). @@ -105,7 +105,7 @@ import javax.naming.NamingException; * Until that point, a EventContext instance that has outstanding * listeners will continue to exist and be maintained by the service provider. * - *

            Listener Implementations

            + *

            Listener Implementations

            * The registration/deregistration methods accept an instance of * NamingListener. There are subinterfaces of NamingListener * for different of event types of NamingEvent. @@ -118,7 +118,7 @@ import javax.naming.NamingException; * of the listeners, this allows some service providers to optimize the * registration. * - *

            Threading Issues

            + *

            Threading Issues

            * * Like Context instances in general, instances of * EventContext are not guaranteed to be thread-safe. diff --git a/src/share/classes/javax/naming/ldap/ControlFactory.java b/src/share/classes/javax/naming/ldap/ControlFactory.java index cbd9b8ab853dd527849a996f9bdf5bfeba674d15..4ab5a347f66db95d18f45f8b55438d4d48b14508 100644 --- a/src/share/classes/javax/naming/ldap/ControlFactory.java +++ b/src/share/classes/javax/naming/ldap/ControlFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,7 +51,7 @@ import com.sun.naming.internal.ResourceManager; */ public abstract class ControlFactory { - /* + /** * Creates a new instance of a control factory. */ protected ControlFactory() { diff --git a/src/share/classes/javax/naming/ldap/InitialLdapContext.java b/src/share/classes/javax/naming/ldap/InitialLdapContext.java index df77164af5f2840224d4deca09fd5571877b8f01..8dde5cb7afce81bad594cc4a559e9ac5b809bbfd 100644 --- a/src/share/classes/javax/naming/ldap/InitialLdapContext.java +++ b/src/share/classes/javax/naming/ldap/InitialLdapContext.java @@ -38,7 +38,7 @@ import java.util.Hashtable; * javax.naming.InitialDirContext for details on synchronization, * and the policy for how an initial context is created. * - *

            Request Controls

            + *

            Request Controls

            * When you create an initial context (InitialLdapContext), * you can specify a list of request controls. * These controls will be used as the request controls for any diff --git a/src/share/classes/javax/naming/ldap/LdapContext.java b/src/share/classes/javax/naming/ldap/LdapContext.java index 93d60c4afca426549eee65ebef5d1e45bf8d61a1..8cb5fb0be012e217720ff94f955e888d74ada2ad 100644 --- a/src/share/classes/javax/naming/ldap/LdapContext.java +++ b/src/share/classes/javax/naming/ldap/LdapContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -78,10 +78,8 @@ import java.util.Hashtable; *

            Context Request Controls

            * There are two ways in which a context instance gets its request controls: *
              - * - *
            1. ldapContext.newInstance(reqCtls) - *
            2. ldapContext.setRequestControls(reqCtls) - * + *
            3. ldapContext.newInstance(reqCtls) + *
            4. ldapContext.setRequestControls(reqCtls) *
            * where ldapContext is an instance of LdapContext. * Specifying null or an empty array for reqCtls @@ -102,12 +100,10 @@ import java.util.Hashtable; *

            Connection Request Controls

            * There are three ways in which connection request controls are set: *
              - * - *
            1. - * new InitialLdapContext(env, connCtls) - *
            2. refException.getReferralContext(env, connCtls) - *
            3. ldapContext.reconnect(connCtls); - * + *
            4. + * new InitialLdapContext(env, connCtls) + *
            5. refException.getReferralContext(env, connCtls) + *
            6. ldapContext.reconnect(connCtls); *
            * where refException is an instance of * LdapReferralException, and ldapContext is an diff --git a/src/share/classes/javax/script/Invocable.java b/src/share/classes/javax/script/Invocable.java index e0b1bc78048cec50d4be37d8af1988b4356d09ea..81d363c01e9b960bd59875f6680ce27aa0195269 100644 --- a/src/share/classes/javax/script/Invocable.java +++ b/src/share/classes/javax/script/Invocable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -63,6 +63,7 @@ public interface Invocable { /** * Used to call top-level procedures and functions defined in scripts. * + * @param name of the procedure or function to call * @param args Arguments to pass to the procedure or function * @return The value returned by the procedure or function * @@ -79,6 +80,7 @@ public interface Invocable { * the interpreter. The methods of the interface * may be implemented using the invokeFunction method. * + * @param the type of the interface to return * @param clasz The Class object of the interface to return. * * @return An instance of requested interface - null if the requested interface is unavailable, @@ -95,6 +97,7 @@ public interface Invocable { * a scripting object compiled in the interpreter. The methods of the * interface may be implemented using the invokeMethod method. * + * @param the type of the interface to return * @param thiz The scripting object whose member functions are used to implement the methods of the interface. * @param clasz The Class object of the interface to return. * diff --git a/src/share/classes/javax/script/ScriptContext.java b/src/share/classes/javax/script/ScriptContext.java index 78247bb74367e65dcf99887384efdcd38c8729bf..8d1076b6d9f24e514466d64bbc360517acc7a594 100644 --- a/src/share/classes/javax/script/ScriptContext.java +++ b/src/share/classes/javax/script/ScriptContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -78,6 +78,7 @@ public interface ScriptContext { * @return The associated Bindings. Returns null if it has not * been set. * + * @param scope The scope * @throws IllegalArgumentException If no Bindings is defined for the * specified scope value in ScriptContext of this type. */ diff --git a/src/share/classes/javax/script/ScriptEngineFactory.java b/src/share/classes/javax/script/ScriptEngineFactory.java index ca22d16359052c02fafe7a3a012e27ecb8832994..298b4ad7b4130c9110248a425d8e4fae47ce5eee 100644 --- a/src/share/classes/javax/script/ScriptEngineFactory.java +++ b/src/share/classes/javax/script/ScriptEngineFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -80,6 +80,7 @@ public interface ScriptEngineFactory { * identify the ScriptEngine by the ScriptEngineManager. * For instance, an implementation based on the Mozilla Rhino Javascript engine might * return list containing {"javascript", "rhino"}. + * @return an immutable list of short names */ public List getNames(); diff --git a/src/share/classes/javax/script/SimpleScriptContext.java b/src/share/classes/javax/script/SimpleScriptContext.java index 98f8c81d5e36971553201f3f9a17896005fc0fc8..a5bf12f9a227c2530a6447bedf742806644dbdd1 100644 --- a/src/share/classes/javax/script/SimpleScriptContext.java +++ b/src/share/classes/javax/script/SimpleScriptContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -82,7 +82,9 @@ public class SimpleScriptContext implements ScriptContext { */ protected Bindings globalScope; - + /** + * Create a {@code SimpleScriptContext}. + */ public SimpleScriptContext() { engineScope = new SimpleBindings(); globalScope = null; diff --git a/src/share/classes/javax/sql/CommonDataSource.java b/src/share/classes/javax/sql/CommonDataSource.java index 25b40686d87bb785700e1527ca24d7c9a34d6e08..51f5ea03eb7e3ea0c163580517fdb148f183c524 100644 --- a/src/share/classes/javax/sql/CommonDataSource.java +++ b/src/share/classes/javax/sql/CommonDataSource.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -122,7 +122,8 @@ public interface CommonDataSource { * In the worst case, this may be the root Logger. * * @return the parent Logger for this data source - * @throws SQLFeatureNotSupportedException if the data source does not use java.util.logging. + * @throws SQLFeatureNotSupportedException if the data source does not use + * {@code java.util.logging} * @since 1.7 */ public Logger getParentLogger() throws SQLFeatureNotSupportedException; diff --git a/src/share/classes/javax/sql/ConnectionPoolDataSource.java b/src/share/classes/javax/sql/ConnectionPoolDataSource.java index 8bb34ed273b154157e0a1ae32a1a266297809961..6388735adc686e5e3f2a0f48bb7c83ec5379b94e 100644 --- a/src/share/classes/javax/sql/ConnectionPoolDataSource.java +++ b/src/share/classes/javax/sql/ConnectionPoolDataSource.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,7 @@ import java.sql.SQLException; * A factory for PooledConnection * objects. An object that implements this interface will typically be * registered with a naming service that is based on the - * JavaTM Naming and Directory Interface + * Java™ Naming and Directory Interface * (JNDI). * * @since 1.4 diff --git a/src/share/classes/javax/sql/DataSource.java b/src/share/classes/javax/sql/DataSource.java index 8235d2a27791bfba06ae8e7eac037cc282d57be3..71fa074e20446bf04303704787fb92f901cafee7 100644 --- a/src/share/classes/javax/sql/DataSource.java +++ b/src/share/classes/javax/sql/DataSource.java @@ -36,7 +36,7 @@ import java.sql.Wrapper; * is the preferred means of getting a connection. An object that implements * the {@code DataSource} interface will typically be * registered with a naming service based on the - * JavaTM Naming and Directory (JNDI) API. + * Java™ Naming and Directory (JNDI) API. *

            * The {@code DataSource} interface is implemented by a driver vendor. * There are three types of implementations: diff --git a/src/share/classes/javax/sql/RowSet.java b/src/share/classes/javax/sql/RowSet.java index fd33529667e17ff28f97b0b979dfe27fa56a3f79..38cd35a3c3c68a442e71f27566954cc018779ef1 100644 --- a/src/share/classes/javax/sql/RowSet.java +++ b/src/share/classes/javax/sql/RowSet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,7 @@ import java.util.*; /** * The interface that adds support to the JDBC API for the - * JavaBeansTM component model. + * JavaBeans™ component model. * A rowset, which can be used as a JavaBeans component in * a visual Bean development environment, can be created and * configured at design time and executed at run time. diff --git a/src/share/classes/javax/sql/XADataSource.java b/src/share/classes/javax/sql/XADataSource.java index 325f015f7336e6d46bcad4fa1c72f962898c2e80..b768601c7f353a3c374505cf7a0c6d94a3b42efa 100644 --- a/src/share/classes/javax/sql/XADataSource.java +++ b/src/share/classes/javax/sql/XADataSource.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,7 +31,7 @@ import java.sql.*; * A factory for {@code XAConnection} objects that is used internally. * An object that implements the {@code XADataSource} interface is * typically registered with a naming service that uses the - * Java Naming and Directory InterfaceTM + * Java Naming and Directory Interface™ * (JNDI). *

            * An implementation of {@code XADataSource} must include a public no-arg diff --git a/src/share/classes/javax/sql/rowset/BaseRowSet.java b/src/share/classes/javax/sql/rowset/BaseRowSet.java index a3b13fa0f5c1fe0b290377a4a6e8560a7bfe59a9..1ca60adbfa43f9c9da4da13985cdb5722d0b434e 100644 --- a/src/share/classes/javax/sql/rowset/BaseRowSet.java +++ b/src/share/classes/javax/sql/rowset/BaseRowSet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,7 +37,7 @@ import javax.sql.rowset.serial.*; /** * An abstract class providing a RowSet object with its basic functionality. * The basic functions include having properties and sending event notifications, - * which all JavaBeansTM components must implement. + * which all JavaBeans™ components must implement. *

            *

            1.0 Overview

            * The BaseRowSet class provides the core functionality @@ -93,7 +93,7 @@ import javax.sql.rowset.serial.*; * NOTE: In order to use a DataSource object for making a * connection, the DataSource object must have been registered * with a naming service that uses the Java Naming and Directory - * InterfaceTM (JNDI) API. This registration + * Interface™ (JNDI) API. This registration * is usually done by a person acting in the capacity of a system administrator. *

            *

            3.0 Setting the Command and Its Parameters

            @@ -106,7 +106,7 @@ import javax.sql.rowset.serial.*; * to null if required. *

            * The following code fragment illustrates how the - * CachedRowSetTM + * CachedRowSet™ * object crs might have its command property set. Note that if a * tool is used to set properties, this is the code that the tool would use. *

            {@code
            diff --git a/src/share/classes/javax/sql/rowset/CachedRowSet.java b/src/share/classes/javax/sql/rowset/CachedRowSet.java
            index 1a8517520a29bb647bbc0dbb5297780b1eadf698..26862715edfeffc8020f979137186c9cf47889dd 100644
            --- a/src/share/classes/javax/sql/rowset/CachedRowSet.java
            +++ b/src/share/classes/javax/sql/rowset/CachedRowSet.java
            @@ -1,5 +1,5 @@
             /*
            - * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
            + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
              * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
              *
              * This code is free software; you can redistribute it and/or modify it
            @@ -46,7 +46,7 @@ import javax.sql.rowset.spi.*;
              * A CachedRowSet object is a container for rows of data
              * that caches its rows in memory, which makes it possible to operate without always being
              * connected to its data source. Further, it is a
            - * JavaBeansTM component and is scrollable,
            + * JavaBeans™ component and is scrollable,
              * updatable, and serializable. A CachedRowSet object typically
              * contains rows from a result set, but it can also contain rows from any file
              * with a tabular format, such as a spread sheet.  The reference implementation
            @@ -410,7 +410,7 @@ import javax.sql.rowset.spi.*;
              * NOTE:  In order to use a DataSource object for making a
              * connection, the DataSource object must have been registered
              * with a naming service that uses the Java Naming and Directory
            - * InterfaceTM (JNDI) API.  This registration
            + * Interface™ (JNDI) API.  This registration
              * is usually done by a person acting in the capacity of a system
              * administrator.
              * 

            @@ -734,7 +734,6 @@ public interface CachedRowSet extends RowSet, Joinable { * source. Otherwise, the application must explicity call the * commit() or rollback() methods as appropriate. * - * @throws SQLException if the cursor is on the insert row * @throws SyncProviderException if the underlying * synchronization provider's writer fails to write the updates * back to the data source @@ -805,7 +804,6 @@ public interface CachedRowSet extends RowSet, Joinable { * commit or rollback methods as appropriate. * * @param con a standard JDBC Connection object - * @throws SQLException if the cursor is on the insert row * @throws SyncProviderException if the underlying * synchronization provider's writer fails to write the updates * back to the data source @@ -1371,7 +1369,7 @@ public interface CachedRowSet extends RowSet, Joinable { * Applications can form a WebRowSet object from the CachedRowSet * object returned by this method in order * to export the RowSet schema definition to XML for future use. - * + * @return An empty copy of this {@code CachedRowSet} object * @throws SQLException if an error occurs in cloning the structure of this * CachedRowSet object * @see #createShared @@ -1543,6 +1541,7 @@ public interface CachedRowSet extends RowSet, Joinable { * @param numRows when populating, the number of rows interval on which the * CachedRowSet populated should fire; the default value * is zero; cannot be less than fetchSize or zero + * @throws SQLException {@code numRows < 0 or numRows < getFetchSize() } */ public void rowSetPopulated(RowSetEvent event, int numRows) throws SQLException; diff --git a/src/share/classes/javax/sql/rowset/FilteredRowSet.java b/src/share/classes/javax/sql/rowset/FilteredRowSet.java index 15bfa42a8403a5c8c3cf5f9e3c06bab8f426ae01..754bc49159d1d58e4de4ec505a0721f18c5f8172 100644 --- a/src/share/classes/javax/sql/rowset/FilteredRowSet.java +++ b/src/share/classes/javax/sql/rowset/FilteredRowSet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,7 +51,7 @@ import java.math.*; *

            * A JDBC FilteredRowSet standard implementation implements the * RowSet interfaces and extends the - * CachedRowSetTM class. The + * CachedRowSet™ class. The * CachedRowSet class provides a set of protected cursor manipulation * methods, which a FilteredRowSet implementation can override * to supply filtering support. @@ -69,8 +69,8 @@ import java.math.*; * class JavaDoc), a FilteredRowSet could then be used as described * below. *

            - * *

            + * {@code
              *     FilteredRowSet frs = new FilteredRowSetImpl();
              *     frs.populate(rs);
              *
            @@ -78,8 +78,8 @@ import java.math.*;
              *     frs.setFilter(name);
              *
              *     frs.next() // only names from "Alpha" to "Bravo" will be returned
            + * }
              * 
            - * * In the example above, we initialize a Range object which * implements the Predicate interface. This object expresses * the following constraints: All rows outputted or modified from this diff --git a/src/share/classes/javax/sql/rowset/JdbcRowSet.java b/src/share/classes/javax/sql/rowset/JdbcRowSet.java index 448f4cd8ce4c8bc2367d7bc58425e6c2e26a98a0..bcb05d104dc6e4356789607ac99589b6e11a893a 100644 --- a/src/share/classes/javax/sql/rowset/JdbcRowSet.java +++ b/src/share/classes/javax/sql/rowset/JdbcRowSet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,7 +38,7 @@ import java.io.*; * *

            1.0 Overview

            * A wrapper around a ResultSet object that makes it possible - * to use the result set as a JavaBeansTM + * to use the result set as a JavaBeans™ * component. Thus, a JdbcRowSet object can be one of the Beans that * a tool makes available for composing an application. Because * a JdbcRowSet is a connected rowset, that is, it continually @@ -113,7 +113,7 @@ import java.io.*; *

            * The implementation of the RowSet method execute in the * JdbcRowSet reference implementation differs from that in the - * CachedRowSetTM + * CachedRowSet™ * reference implementation to account for the different * requirements of connected and disconnected RowSet objects. *

            @@ -238,6 +238,7 @@ public interface JdbcRowSet extends RowSet, Joinable { * call to either the method commit or the method rollback. By default, * new connections are in auto-commit mode. * + * @return {@code true} if auto-commit is enabled; {@code false} otherwise * @throws SQLException if a database access error occurs * @see java.sql.Connection#getAutoCommit() */ @@ -251,7 +252,8 @@ public interface JdbcRowSet extends RowSet, Joinable { * to allow an application to set the JdbcRowSet transaction behavior. *

            * Sets the current auto-commit mode for this Connection object. - * + * @param autoCommit {@code true} to enable auto-commit; {@code false} to + * disable auto-commit * @throws SQLException if a database access error occurs * @see java.sql.Connection#setAutoCommit(boolean) */ @@ -277,7 +279,7 @@ public interface JdbcRowSet extends RowSet, Joinable { * Undoes all changes made in the current transaction to the last set savepoint * and releases any database locks currently held by this Connection * object. This method should be used only when auto-commit mode has been disabled. - * + * @param s The {@code Savepoint} to rollback to * @throws SQLException if a database access error occurs or this Connection * object within this JdbcRowSet is in auto-commit mode. * @see #rollback diff --git a/src/share/classes/javax/sql/rowset/Joinable.java b/src/share/classes/javax/sql/rowset/Joinable.java index 7a789474b76d9193107a9d391391e703940d4277..c15f44de54ce44dda24adfba46c410e46665dfbf 100644 --- a/src/share/classes/javax/sql/rowset/Joinable.java +++ b/src/share/classes/javax/sql/rowset/Joinable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -137,7 +137,7 @@ public interface Joinable { * object. A JoinRowSet object can now add this RowSet * object based on the match column. *

            - * Sub-interfaces such as the CachedRowSetTM + * Sub-interfaces such as the CachedRowSet™ * interface define the method CachedRowSet.setKeyColumns, which allows * primary key semantics to be enforced on specific columns. * Implementations of the setMatchColumn(int columnIdx) method diff --git a/src/share/classes/javax/sql/rowset/Predicate.java b/src/share/classes/javax/sql/rowset/Predicate.java index eb747602eb0b2c9a07a20279c771e47d4e78ed7e..63d76fdca6b20864458299304581ea08de788156 100644 --- a/src/share/classes/javax/sql/rowset/Predicate.java +++ b/src/share/classes/javax/sql/rowset/Predicate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -111,7 +111,7 @@ public interface Predicate { * cursor moving from row to the next. In addition, if this internal method * moves the cursor onto a row that has been deleted, the internal method will * continue to ove the cursor until a valid row is found. - * + * @param rs The {@code RowSet} to be evaluated * @return true if there are more rows in the filter; * false otherwise */ diff --git a/src/share/classes/javax/sql/rowset/RowSetProvider.java b/src/share/classes/javax/sql/rowset/RowSetProvider.java index 1dd2d8315e7fd2bfbaa521c9b587f81b285d4824..654bb88ea24a654fe98f1cbaef24f8bbaa0392e1 100644 --- a/src/share/classes/javax/sql/rowset/RowSetProvider.java +++ b/src/share/classes/javax/sql/rowset/RowSetProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -71,7 +71,9 @@ public class RowSetProvider { debug = val != null && !"false".equals(val); } - + /** + * RowSetProvider constructor + */ protected RowSetProvider () { } diff --git a/src/share/classes/javax/sql/rowset/RowSetWarning.java b/src/share/classes/javax/sql/rowset/RowSetWarning.java index 57b9e4383991480be99954bcdd48bd657fffb11b..c110834c2cffcce372648ba515caa6584865b598 100644 --- a/src/share/classes/javax/sql/rowset/RowSetWarning.java +++ b/src/share/classes/javax/sql/rowset/RowSetWarning.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,7 +35,7 @@ import java.sql.SQLException; * This class complements the SQLWarning class. *

            * Rowset warnings may be retrieved from JdbcRowSet, - * CachedRowSetTM, + * CachedRowSet™, * WebRowSet, FilteredRowSet, or JoinRowSet * implementations. To retrieve the first warning reported on any * RowSet diff --git a/src/share/classes/javax/sql/rowset/WebRowSet.java b/src/share/classes/javax/sql/rowset/WebRowSet.java index abef62f1271f8175de65ac0a285e86c27fd07b34..3f0ba94b7390cae027b330e581d3d6e5b380decc 100644 --- a/src/share/classes/javax/sql/rowset/WebRowSet.java +++ b/src/share/classes/javax/sql/rowset/WebRowSet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,306 +33,310 @@ import java.math.*; import org.xml.sax.*; /** - * The standard interface that all implementations of a WebRowSet + * The standard interface that all implementations of a {@code WebRowSet} * must implement. *

            *

            1.0 Overview

            - * The WebRowSetImpl provides the standard + * The {@code WebRowSetImpl} provides the standard * reference implementation, which may be extended if required. *

            * The standard WebRowSet XML Schema definition is available at the following * URI: *

            * It describes the standard XML document format required when describing a - * RowSet object in XML and must be used be all standard implementations - * of the WebRowSet interface to ensure interoperability. In addition, - * the WebRowSet schema uses specific SQL/XML Schema annotations, + * {@code RowSet} object in XML and must be used be all standard implementations + * of the {@code WebRowSet} interface to ensure interoperability. In addition, + * the {@code WebRowSet} schema uses specific SQL/XML Schema annotations, * thus ensuring greater cross * platform inter-operability. This is an effort currently under way at the ISO * organization. The SQL/XML definition is available at the following URI: * - * The schema definition describes the internal data of a RowSet object + * The schema definition describes the internal data of a {@code RowSet} object * in three distinct areas: *
              - *
            • properties
            • - * These properties describe the standard synchronization provider properties in - * addition to the more general RowSet properties. - *

              - *

            • metadata
            • - * This describes the metadata associated with the tabular structure governed by a - * WebRowSet object. The metadata described is closely aligned with the - * metadata accessible in the underlying java.sql.ResultSet interface. - *

              - *

            • data
            • - * This describes the original data (the state of data since the last population - * or last synchronization of the WebRowSet object) and the current + *
            • properties - These properties describe the standard synchronization + * provider properties in addition to the more general {@code RowSet} properties. + *
            • + *
            • metadata - This describes the metadata associated with the tabular structure governed by a + * {@code WebRowSet} object. The metadata described is closely aligned with the + * metadata accessible in the underlying {@code java.sql.ResultSet} interface. + *
            • + *
            • data - This describes the original data (the state of data since the + * last population + * or last synchronization of the {@code WebRowSet} object) and the current * data. By keeping track of the delta between the original data and the current data, - * a WebRowSet maintains - * the ability to synchronize changes in its data back to the originating data source. + * a {@code WebRowSet} maintains the ability to synchronize changes + * in its data back to the originating data source. + *
            • *
            *

            *

            2.0 WebRowSet States

            - * The following sections demonstrates how a WebRowSet implementation + * The following sections demonstrates how a {@code WebRowSet} implementation * should use the XML Schema to describe update, insert, and delete operations - * and to describe the state of a WebRowSet object in XML. + * and to describe the state of a {@code WebRowSet} object in XML. *

            - *

            2.1 State 1 - Outputting a WebRowSet Object to XML

            - * In this example, a WebRowSet object is created and populated with a simple 2 column, - * 5 row table from a data source. Having the 5 rows in a WebRowSet object + *

            2.1 State 1 - Outputting a {@code WebRowSet} Object to XML

            + * In this example, a {@code WebRowSet} object is created and populated with a simple 2 column, + * 5 row table from a data source. Having the 5 rows in a {@code WebRowSet} object * makes it possible to describe them in XML. The * metadata describing the various standard JavaBeans properties as defined * in the RowSet interface plus the standard properties defined in - * the CachedRowSetTM interface + * the {@code CachedRowSet}™ interface * provide key details that describe WebRowSet * properties. Outputting the WebRowSet object to XML using the standard - * writeXml methods describes the internal properties as follows: + * {@code writeXml} methods describes the internal properties as follows: *
            - * <properties>
            - *       <command>select co1, col2 from test_table</command>
            - *      <concurrency>1</concurrency>
            - *      <datasource/>
            - *      <escape-processing>true</escape-processing>
            - *      <fetch-direction>0</fetch-direction>
            - *      <fetch-size>0</fetch-size>
            - *      <isolation-level>1</isolation-level>
            - *      <key-columns/>
            - *      <map/>
            - *      <max-field-size>0</max-field-size>
            - *      <max-rows>0</max-rows>
            - *      <query-timeout>0</query-timeout>
            - *      <read-only>false</read-only>
            - *      <rowset-type>TRANSACTION_READ_UNCOMMITED</rowset-type>
            - *      <show-deleted>false</show-deleted>
            - *      <table-name/>
            - *      <url>jdbc:thin:oracle</url>
            - *      <sync-provider>
            - *              <sync-provider-name>.com.rowset.provider.RIOptimisticProvider</sync-provider-name>
            - *              <sync-provider-vendor>Oracle Corporation</sync-provider-vendor>
            - *              <sync-provider-version>1.0</sync-provider-name>
            - *              <sync-provider-grade>LOW</sync-provider-grade>
            - *              <data-source-lock>NONE</data-source-lock>
            - *      </sync-provider>
            - * </properties>
            - * 
            + * {@code + * + * select co1, col2 from test_table + * 1 + * + * true + * 0 + * 0 + * 1 + * + * + * 0 + * 0 + * 0 + * false + * TRANSACTION_READ_UNCOMMITED + * false + * + * jdbc:thin:oracle + * + * .com.rowset.provider.RIOptimisticProvider + * Oracle Corporation + * 1.0 + * LOW + * NONE + * + * + * }
            * The meta-data describing the make up of the WebRowSet is described * in XML as detailed below. Note both columns are described between the - * column-definition tags. + * {@code column-definition} tags. *
            - * <metadata>
            - *      <column-count>2</column-count>
            - *      <column-definition>
            - *              <column-index>1</column-index>
            - *              <auto-increment>false</auto-increment>
            - *              <case-sensitive>true</case-sensitive>
            - *              <currency>false</currency>
            - *              <nullable>1</nullable>
            - *              <signed>false</signed>
            - *              <searchable>true</searchable>
            - *              <column-display-size>10</column-display-size>
            - *              <column-label>COL1</column-label>
            - *              <column-name>COL1</column-name>
            - *              <schema-name/>
            - *              <column-precision>10</column-precision>
            - *              <column-scale>0</column-scale>
            - *              <table-name/>
            - *              <catalog-name/>
            - *              <column-type>1</column-type>
            - *              <column-type-name>CHAR</column-type-name>
            - *      </column-definition>
            - *      <column-definition>
            - *              <column-index>2</column-index>
            - *              <auto-increment>false</auto-increment>
            - *              <case-sensitive>false</case-sensitive>
            - *              <currency>false</currency>
            - *              <nullable>1</nullable>
            - *              <signed>true</signed>
            - *              <searchable>true</searchable>
            - *              <column-display-size>39</column-display-size>
            - *              <column-label>COL2</column-label>
            - *              <column-name>COL2</column-name>
            - *              <schema-name/>
            - *              <column-precision>38</column-precision>
            - *              <column-scale>0</column-scale>
            - *              <table-name/>
            - *              <catalog-name/>
            - *              <column-type>3</column-type>
            - *              <column-type-name>NUMBER</column-type-name>
            - *      </column-definition>
            - * </metadata>
            - * 
            + * {@code + * + * 2 + * + * 1 + * false + * true + * false + * 1 + * false + * true + * 10 + * COL1 + * COL1 + * + * 10 + * 0 + * + * + * 1 + * CHAR + * + * + * 2 + * false + * false + * false + * 1 + * true + * true + * 39 + * COL2 + * COL2 + * + * 38 + * 0 + * + * + * 3 + * NUMBER + * + * + * }
        * Having detailed how the properties and metadata are described, the following details - * how the contents of a WebRowSet object is described in XML. Note, that - * this describes a WebRowSet object that has not undergone any + * how the contents of a {@code WebRowSet} object is described in XML. Note, that + * this describes a {@code WebRowSet} object that has not undergone any * modifications since its instantiation. - * A currentRow tag is mapped to each row of the table structure that the - * WebRowSet object provides. A columnValue tag may contain - * either the stringData or binaryData tag, according to + * A {@code currentRow} tag is mapped to each row of the table structure that the + * {@code WebRowSet} object provides. A {@code columnValue} tag may contain + * either the {@code stringData} or {@code binaryData} tag, according to * the SQL type that - * the XML value is mapping back to. The binaryData tag contains data in the - * Base64 encoding and is typically used for BLOB and CLOB type data. + * the XML value is mapping back to. The {@code binaryData} tag contains data in the + * Base64 encoding and is typically used for {@code BLOB} and {@code CLOB} type data. *
        - * <data>
        - *      <currentRow>
        - *              <columnValue>
        + * {@code
        + * 
        + *      
        + *              
          *                      firstrow
        - *              </columnValue>
        - *              <columnValue>
        + *              
        + *              
          *                      1
        - *              </columnValue>
        - *      </currentRow>
        - *      <currentRow>
        - *              <columnValue>
        + *              
        + *      
        + *      
        + *              
          *                      secondrow
        - *              </columnValue>
        - *              <columnValue>
        + *              
        + *              
          *                      2
        - *              </columnValue>
        - *      </currentRow>
        - *      <currentRow>
        - *              <columnValue>
        + *              
        + *      
        + *      
        + *              
          *                      thirdrow
        - *              </columnValue>
        - *              <columnValue>
        + *              
        + *              
          *                      3
        - *              </columnValue>
        - *      </currentRow>
        - *      <currentRow>
        - *              <columnValue>
        + *              
        + *      
        + *      
        + *              
          *                      fourthrow
        - *              </columnValue>
        - *              <columnValue>
        + *              
        + *              
          *                      4
        - *              </columnValue>
        - *      </currentRow>
        - * </data>
        - * 
        + * + * + * + * }
      *

      2.2 State 2 - Deleting a Row

      - * Deleting a row in a WebRowSet object involves simply moving to the row - * to be deleted and then calling the method deleteRow, as in any other - * RowSet object. The following - * two lines of code, in which wrs is a WebRowSet object, delete + * Deleting a row in a {@code WebRowSet} object involves simply moving to the row + * to be deleted and then calling the method {@code deleteRow}, as in any other + * {@code RowSet} object. The following + * two lines of code, in which wrs is a {@code WebRowSet} object, delete * the third row. *
        *     wrs.absolute(3);
        *     wrs.deleteRow();
        * 
      - * The XML description shows the third row is marked as a deleteRow, - * which eliminates the third row in the WebRowSet object. + * The XML description shows the third row is marked as a {@code deleteRow}, + * which eliminates the third row in the {@code WebRowSet} object. *
      - * <data>
      - *      <currentRow>
      - *              <columnValue>
      + * {@code
      + * 
      + *      
      + *              
        *                      firstrow
      - *              </columnValue>
      - *              <columnValue>
      + *              
      + *              
        *                      1
      - *              </columnValue>
      - *      </currentRow>
      - *      <currentRow>
      - *              <columnValue>
      + *              
      + *      
      + *      
      + *              
        *                      secondrow
      - *              </columnValue>
      - *              <columnValue>
      + *              
      + *              
        *                      2
      - *              </columnValue>
      - *      </currentRow>
      - *      <deleteRow>
      - *              <columnValue>
      + *              
      + *      
      + *      
      + *              
        *                      thirdrow
      - *              </columnValue>
      - *              <columnValue>
      + *              
      + *              
        *                      3
      - *              </columnValue>
      - *      </deleteRow>
      - *      <currentRow>
      - *              <columnValue>
      + *              
      + *      
      + *      
      + *              
        *                      fourthrow
      - *              </columnValue>
      - *              <columnValue>
      + *              
      + *              
        *                      4
      - *              </columnValue>
      - *      </currentRow>
      - * </data>
      - * 
      + * + * + * + *} *

      2.3 State 3 - Inserting a Row

      - * A WebRowSet object can insert a new row by moving to the insert row, + * A {@code WebRowSet} object can insert a new row by moving to the insert row, * calling the appropriate updater methods for each column in the row, and then - * calling the method insertRow. + * calling the method {@code insertRow}. *
      + * {@code
        * wrs.moveToInsertRow();
        * wrs.updateString(1, "fifththrow");
        * wrs.updateString(2, "5");
        * wrs.insertRow();
      - * 
      + * } * The following code fragment changes the second column value in the row just inserted. * Note that this code applies when new rows are inserted right after the current row, - * which is why the method next moves the cursor to the correct row. - * Calling the method acceptChanges writes the change to the data source. + * which is why the method {@code next} moves the cursor to the correct row. + * Calling the method {@code acceptChanges} writes the change to the data source. * *
      - * wrs.moveToCurrentRow();
      + * {@code wrs.moveToCurrentRow();
        * wrs.next();
        * wrs.updateString(2, "V");
        * wrs.acceptChanges();
      - * :
      - * 
      + * } * Describing this in XML demonstrates where the Java code inserts a new row and then * performs an update on the newly inserted row on an individual field. *
      - * <data>
      - *      <currentRow>
      - *              <columnValue>
      + * {@code
      + * 
      + *      
      + *              
        *                      firstrow
      - *              </columnValue>
      - *              <columnValue>
      + *              
      + *              
        *                      1
      - *              </columnValue>
      - *      </currentRow>
      - *      <currentRow>
      - *              <columnValue>
      + *              
      + *      
      + *      
      + *              
        *                      secondrow
      - *              </columnValue>
      - *              <columnValue>
      + *              
      + *              
        *                      2
      - *              </columnValue>
      - *      </currentRow>
      - *      <currentRow>
      - *              <columnValue>
      + *              
      + *      
      + *      
      + *              
        *                      newthirdrow
      - *              </columnValue>
      - *              <columnValue>
      + *              
      + *              
        *                      III
      - *              </columnValue>
      - *      </currentRow>
      - *      <insertRow>
      - *              <columnValue>
      + *              
      + *      
      + *      
      + *              
        *                      fifthrow
      - *              </columnValue>
      - *              <columnValue>
      + *              
      + *              
        *                      5
      - *              </columnValue>
      - *              <updateValue>
      + *              
      + *              
        *                      V
      - *              </updateValue>
      - *      </insertRow>
      - *      <currentRow>
      - *              <columnValue>
      + *              
      + *      
      + *      
      + *              
        *                      fourthrow
      - *              </columnValue>
      - *              <columnValue>
      + *              
      + *              
        *                      4
      - *              </columnValue>
      - *      </currentRow>
      - * </date>
      - * 
      + * + * + * + *} *

      2.4 State 4 - Modifying a Row

      * Modifying a row produces specific XML that records both the new value and the * value that was replaced. The value that was replaced becomes the original value, @@ -340,63 +344,65 @@ import org.xml.sax.*; * code moves the cursor to a specific row, performs some modifications, and updates * the row when complete. *
      + *{@code
        * wrs.absolute(5);
        * wrs.updateString(1, "new4thRow");
        * wrs.updateString(2, "IV");
        * wrs.updateRow();
      - * 
      - * In XML, this is described by the modifyRow tag. Both the original and new + * } + * In XML, this is described by the {@code modifyRow} tag. Both the original and new * values are contained within the tag for original row tracking purposes. *
      - * <data>
      - *      <currentRow>
      - *              <columnValue>
      + * {@code
      + * 
      + *      
      + *              
        *                      firstrow
      - *              </columnValue>
      - *              <columnValue>
      + *              
      + *              
        *                      1
      - *              </columnValue>
      - *      </currentRow>
      - *      <currentRow>
      - *              <columnValue>
      + *              
      + *      
      + *      
      + *              
        *                      secondrow
      - *              </columnValue>
      - *              <columnValue>
      + *              
      + *              
        *                      2
      - *              </columnValue>
      - *      </currentRow>
      - *      <currentRow>
      - *              <columnValue>
      + *              
      + *      
      + *      
      + *              
        *                      newthirdrow
      - *              </columnValue>
      - *              <columnValue>
      + *              
      + *              
        *                      III
      - *              </columnValue>
      - *      </currentRow>
      - *      <currentRow>
      - *              <columnValue>
      + *              
      + *      
      + *      
      + *              
        *                      fifthrow
      - *              </columnValue>
      - *              <columnValue>
      + *              
      + *              
        *                      5
      - *              </columnValue>
      - *      </currentRow>
      - *      <modifyRow>
      - *              <columnValue>
      + *              
      + *      
      + *      
      + *              
        *                      fourthrow
      - *              </columnValue>
      - *              <updateValue>
      + *              
      + *              
        *                      new4thRow
      - *              </updateValue>
      - *              <columnValue>
      + *              
      + *              
        *                      4
      - *              </columnValue>
      - *              <updateValue>
      + *              
      + *              
        *                      IV
      - *              </updateValue>
      - *      </modifyRow>
      - * </data>
      - * 
      + * + * + * + * } * * @see javax.sql.rowset.JdbcRowSet * @see javax.sql.rowset.CachedRowSet @@ -407,78 +413,78 @@ import org.xml.sax.*; public interface WebRowSet extends CachedRowSet { /** - * Reads a WebRowSet object in its XML format from the given - * Reader object. + * Reads a {@code WebRowSet} object in its XML format from the given + * {@code Reader} object. * - * @param reader the java.io.Reader stream from which this - * WebRowSet object will be populated + * @param reader the {@code java.io.Reader} stream from which this + * {@code WebRowSet} object will be populated * @throws SQLException if a database access error occurs */ public void readXml(java.io.Reader reader) throws SQLException; /** - * Reads a stream based XML input to populate this WebRowSet + * Reads a stream based XML input to populate this {@code WebRowSet} * object. * - * @param iStream the java.io.InputStream from which this - * WebRowSet object will be populated + * @param iStream the {@code java.io.InputStream} from which this + * {@code WebRowSet} object will be populated * @throws SQLException if a data source access error occurs * @throws IOException if an IO exception occurs */ public void readXml(java.io.InputStream iStream) throws SQLException, IOException; /** - * Populates this WebRowSet object with - * the contents of the given ResultSet object and writes its + * Populates this {@code WebRowSet} object with + * the contents of the given {@code ResultSet} object and writes its * data, properties, and metadata - * to the given Writer object in XML format. + * to the given {@code Writer} object in XML format. *

      - * NOTE: The WebRowSet cursor may be moved to write out the + * NOTE: The {@code WebRowSet} cursor may be moved to write out the * contents to the XML data source. If implemented in this way, the cursor must - * be returned to its position just prior to the writeXml() call. + * be returned to its position just prior to the {@code writeXml()} call. * - * @param rs the ResultSet object with which to populate this - * WebRowSet object - * @param writer the java.io.Writer object to write to. + * @param rs the {@code ResultSet} object with which to populate this + * {@code WebRowSet} object + * @param writer the {@code java.io.Writer} object to write to. * @throws SQLException if an error occurs writing out the rowset * contents in XML format */ public void writeXml(ResultSet rs, java.io.Writer writer) throws SQLException; /** - * Populates this WebRowSet object with - * the contents of the given ResultSet object and writes its + * Populates this {@code WebRowSet} object with + * the contents of the given {@code ResultSet} object and writes its * data, properties, and metadata - * to the given OutputStream object in XML format. + * to the given {@code OutputStream} object in XML format. *

      - * NOTE: The WebRowSet cursor may be moved to write out the + * NOTE: The {@code WebRowSet} cursor may be moved to write out the * contents to the XML data source. If implemented in this way, the cursor must - * be returned to its position just prior to the writeXml() call. + * be returned to its position just prior to the {@code writeXml()} call. * - * @param rs the ResultSet object with which to populate this - * WebRowSet object - * @param oStream the java.io.OutputStream to write to + * @param rs the {@code ResultSet} object with which to populate this + * {@code WebRowSet} object + * @param oStream the {@code java.io.OutputStream} to write to * @throws SQLException if a data source access error occurs * @throws IOException if a IO exception occurs */ public void writeXml(ResultSet rs, java.io.OutputStream oStream) throws SQLException, IOException; /** - * Writes the data, properties, and metadata for this WebRowSet object - * to the given Writer object in XML format. + * Writes the data, properties, and metadata for this {@code WebRowSet} object + * to the given {@code Writer} object in XML format. * - * @param writer the java.io.Writer stream to write to + * @param writer the {@code java.io.Writer} stream to write to * @throws SQLException if an error occurs writing out the rowset * contents to XML */ public void writeXml(java.io.Writer writer) throws SQLException; /** - * Writes the data, properties, and metadata for this WebRowSet object - * to the given OutputStream object in XML format. + * Writes the data, properties, and metadata for this {@code WebRowSet} object + * to the given {@code OutputStream} object in XML format. * - * @param oStream the java.io.OutputStream stream to write to + * @param oStream the {@code java.io.OutputStream} stream to write to * @throws SQLException if a data source access error occurs * @throws IOException if a IO exception occurs */ @@ -486,14 +492,14 @@ public interface WebRowSet extends CachedRowSet { /** * The public identifier for the XML Schema definition that defines the XML - * tags and their valid values for a WebRowSet implementation. + * tags and their valid values for a {@code WebRowSet} implementation. */ public static String PUBLIC_XML_SCHEMA = "--//Oracle Corporation//XSD Schema//EN"; /** * The URL for the XML Schema definition file that defines the XML tags and - * their valid values for a WebRowSet implementation. + * their valid values for a {@code WebRowSet} implementation. */ public static String SCHEMA_SYSTEM_ID = "http://java.sun.com/xml/ns/jdbc/webrowset.xsd"; } diff --git a/src/share/classes/javax/sql/rowset/package.html b/src/share/classes/javax/sql/rowset/package.html index 61073131eece5028022eccf091c98cd0ebc0ced4..e8b494ee744c839e939dc0a84557781198a0ef14 100644 --- a/src/share/classes/javax/sql/rowset/package.html +++ b/src/share/classes/javax/sql/rowset/package.html @@ -67,7 +67,7 @@ interfaces.

      • JdbcRowSet - A wrapper around a ResultSet object that makes it possible to use the result set as a -JavaBeansTM component. Thus, +JavaBeans™ component. Thus, a JdbcRowSet object can be a Bean that any tool makes available for assembling an application as part of a component based architecture . A JdbcRowSet object is a connected RowSet @@ -79,7 +79,7 @@ data structure as defined in the JDBC 3.0 specification.

      • CachedRowSet - - A CachedRowSet object is a JavaBeansTM + - A CachedRowSet object is a JavaBeans™ component that is scrollable, updatable, serializable, and generally disconnected from the source of its data. A CachedRowSet object typically contains rows from a result set, but it can also contain rows from any diff --git a/src/share/classes/javax/sql/rowset/serial/SerialArray.java b/src/share/classes/javax/sql/rowset/serial/SerialArray.java index 3d3926cb83cc64d37d26fcf9203a1a8b470b4de3..1e0e440bcef19a34332a09665a5dcee0cd2d1a0c 100644 --- a/src/share/classes/javax/sql/rowset/serial/SerialArray.java +++ b/src/share/classes/javax/sql/rowset/serial/SerialArray.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -50,7 +50,7 @@ import java.util.Arrays; * if necessary. At this time, logical pointers to the data in the data source, * such as locators, are not currently supported. * - *

        Thread safety

        + *

        Thread safety

        * * A SerialArray is not safe for use by multiple concurrent threads. If a * SerialArray is to be used by more than one thread then access to the diff --git a/src/share/classes/javax/sql/rowset/serial/SerialBlob.java b/src/share/classes/javax/sql/rowset/serial/SerialBlob.java index e7bdbcf87e0ca1cfabb484c94fdaab5ac542d6dd..4c5a6b867a98eb243e3acc0b0bd321f2963d4d7f 100644 --- a/src/share/classes/javax/sql/rowset/serial/SerialBlob.java +++ b/src/share/classes/javax/sql/rowset/serial/SerialBlob.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,7 +51,7 @@ import java.util.Arrays; * Blob object within a SerialBlob object * and to update or truncate a Blob object. * - *

        Thread safety

        + *

        Thread safety

        * *

        A SerialBlob is not safe for use by multiple concurrent threads. If a * SerialBlob is to be used by more than one thread then access to the SerialBlob diff --git a/src/share/classes/javax/sql/rowset/serial/SerialClob.java b/src/share/classes/javax/sql/rowset/serial/SerialClob.java index 5ea5fee14bc93ba26774f2e7d70501dffd8c1959..a2177b2c153cfb72af807d23c5c566484b2b61c0 100644 --- a/src/share/classes/javax/sql/rowset/serial/SerialClob.java +++ b/src/share/classes/javax/sql/rowset/serial/SerialClob.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,7 @@ import java.util.Arrays; * from a SerialClob object or to locate the start of * a pattern of characters. * - *

        Thread safety

        + *

        Thread safety

        * *

        A SerialClob is not safe for use by multiple concurrent threads. If a * SerialClob is to be used by more than one thread then access to the SerialClob diff --git a/src/share/classes/javax/sql/rowset/serial/SerialDatalink.java b/src/share/classes/javax/sql/rowset/serial/SerialDatalink.java index 4cfcfb1155a44f9d8d6cf9dae9bba9d4e52ff0db..ad053bcdec9258f4239af17a7f6db98275e5df6a 100644 --- a/src/share/classes/javax/sql/rowset/serial/SerialDatalink.java +++ b/src/share/classes/javax/sql/rowset/serial/SerialDatalink.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,7 +43,7 @@ import java.net.URL; * java.net.URL url = rowset.getURL(1); * * - *

        Thread safety

        + *

        Thread safety

        * * A SerialDatalink is not safe for use by multiple concurrent threads. If a * SerialDatalink is to be used by more than one thread then access to the @@ -77,6 +77,7 @@ public class SerialDatalink implements Serializable, Cloneable { * Constructs a new SerialDatalink object from the given * java.net.URL object. *

        + * @param url the {@code URL} to create the {@code SerialDataLink} from * @throws SerialException if url parameter is a null */ public SerialDatalink(URL url) throws SerialException { diff --git a/src/share/classes/javax/sql/rowset/serial/SerialJavaObject.java b/src/share/classes/javax/sql/rowset/serial/SerialJavaObject.java index 985ef4005915b1aa4be31cd1456c7cd9dc21636a..4a9ce17b4c8d3a2df86968d2ab77bb9210e6cf1d 100644 --- a/src/share/classes/javax/sql/rowset/serial/SerialJavaObject.java +++ b/src/share/classes/javax/sql/rowset/serial/SerialJavaObject.java @@ -47,7 +47,7 @@ import sun.reflect.misc.ReflectUtil; * Static or transient fields cannot be serialized; an attempt to serialize * them will result in a SerialException object being thrown. * - *

        Thread safety

        + *

        Thread safety

        * * A SerialJavaObject is not safe for use by multiple concurrent threads. If a * SerialJavaObject is to be used by more than one thread then access to the diff --git a/src/share/classes/javax/sql/rowset/serial/SerialRef.java b/src/share/classes/javax/sql/rowset/serial/SerialRef.java index 84009fac6cb2d76970cd38ef2cc3e24d74c95cf4..834fafe32b66cd8b2f7f353cc15ef70865de2074 100644 --- a/src/share/classes/javax/sql/rowset/serial/SerialRef.java +++ b/src/share/classes/javax/sql/rowset/serial/SerialRef.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,7 +37,7 @@ import java.util.*; * creating a SerialRef instance from a Ref * object and provides methods for getting and setting the Ref object. * - *

        Thread safety

        + *

        Thread safety

        * * A SerialRef is not safe for use by multiple concurrent threads. If a * SerialRef is to be used by more than one thread then access to the SerialRef diff --git a/src/share/classes/javax/sql/rowset/serial/SerialStruct.java b/src/share/classes/javax/sql/rowset/serial/SerialStruct.java index 2fe11996eb7ce172d0e315586ef2f111ed676c1e..6eef84f3ef9010b01d42504f18bf48e75698739e 100644 --- a/src/share/classes/javax/sql/rowset/serial/SerialStruct.java +++ b/src/share/classes/javax/sql/rowset/serial/SerialStruct.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,7 +51,7 @@ import javax.sql.rowset.*; * the SQL type name of the SQL structured type in the database, and methods * for retrieving its attribute values. * - *

        Thread safety

        + *

        Thread safety

        * * A SerialStruct is not safe for use by multiple concurrent threads. If a * SerialStruct is to be used by more than one thread then access to the diff --git a/src/share/classes/javax/sql/rowset/spi/SyncFactory.java b/src/share/classes/javax/sql/rowset/spi/SyncFactory.java index e9b10bdcbfb1cdb48b85def2598abc5ec1fe3b6d..6797dc0d397adf5ad54ccee16edb69bb8fb86d2d 100644 --- a/src/share/classes/javax/sql/rowset/spi/SyncFactory.java +++ b/src/share/classes/javax/sql/rowset/spi/SyncFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -260,13 +260,14 @@ public class SyncFactory { *

        * Synchronization providers bound to a JNDI context can be * registered by binding a SyncProvider instance to a JNDI namespace. - *

          + * *
          +     * {@code
                * SyncProvider p = new MySyncProvider();
                * InitialContext ic = new InitialContext();
                * ic.bind ("jdbc/rowset/MySyncProvider", p);
          -     * 
          - *
        + * } + * * Furthermore, an initial JNDI context should be set with the * SyncFactory using the setJNDIContext method. * The SyncFactory leverages this context to search for @@ -564,6 +565,8 @@ public class SyncFactory { * * @return Enumeration A enumeration of available synchronization * providers that are registered with this Factory + * @throws SyncFactoryException If an error occurs obtaining the registered + * providers */ public static Enumeration getRegisteredProviders() throws SyncFactoryException { @@ -648,7 +651,8 @@ public class SyncFactory { /** * Returns the logging object for applications to retrieve * synchronization events posted by SyncProvider implementations. - * + * @return The {@code Logger} that has been specified for use by + * {@code SyncProvider} implementations * @throws SyncFactoryException if no logging object has been set. */ public static Logger getLogger() throws SyncFactoryException { diff --git a/src/share/classes/javax/sql/rowset/spi/SyncResolver.java b/src/share/classes/javax/sql/rowset/spi/SyncResolver.java index c1180cf92510c8fc46b579867334da1e472a0f6d..71f463fef2f48d5d24189889d0688d972d592b77 100644 --- a/src/share/classes/javax/sql/rowset/spi/SyncResolver.java +++ b/src/share/classes/javax/sql/rowset/spi/SyncResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -81,10 +81,13 @@ import java.sql.SQLException; * SyncProviderException method getSyncResolver to get * the SyncResolver object resolver. *
        + * {@code
          *     } catch (SyncProviderException spe) {
          *         SyncResolver resolver = spe.getSyncResolver();
          *     ...
          *     }
        + *
        + * }
          * 
        *

        * With resolver in hand, an application can use it to get the information @@ -97,7 +100,7 @@ import java.sql.SQLException; * The following kinds of information can be obtained from a SyncResolver * object: *

        - *

      • What operation was being attempted when a conflict occurred
        + *

        What operation was being attempted when a conflict occurred

        * The SyncProvider interface defines four constants * describing states that may occur. Three * constants describe the type of operation (update, delete, or insert) that a @@ -106,10 +109,10 @@ import java.sql.SQLException; * These constants are the possible return values when a SyncResolver object * calls the method getStatus. *
        - *     int operation = resolver.getStatus();
        + *     {@code int operation = resolver.getStatus(); }
          * 
        *

        - *

      • The value in the data source that caused a conflict
        + *

        The value in the data source that caused a conflict

        * A conflict exists when a value that a RowSet object has changed * and is attempting to write to the data source * has also been changed in the data source since the last synchronization. An @@ -122,7 +125,6 @@ import java.sql.SQLException; * * Note that the column in resolver can be designated by the column number, * as is done in the preceding line of code, or by the column name. - *
      *

      * With the information retrieved from the methods getStatus and * getConflictValue, the application may make a determination as to @@ -193,7 +195,8 @@ import java.sql.SQLException; * code fragment, the value in crs is the one set as the resolved value, which means * that it will be used to overwrite the conflict value in the data source. * - *

      {@code
      + * 
      + * {@code
        *     try {
        *
        *         crs.acceptChanges(con);
      diff --git a/src/share/classes/javax/swing/JFileChooser.java b/src/share/classes/javax/swing/JFileChooser.java
      index 2e1655d6d706b1b958be8b6fa8056644b9ff0268..d30c69675ae4dbab34baebafc01ffb4bad3fa5d7 100644
      --- a/src/share/classes/javax/swing/JFileChooser.java
      +++ b/src/share/classes/javax/swing/JFileChooser.java
      @@ -1146,9 +1146,25 @@ public class JFileChooser extends JComponent implements Accessible {
            * @see #resetChoosableFileFilters
            */
           public boolean removeChoosableFileFilter(FileFilter f) {
      -        if(filters.contains(f)) {
      +        int index = filters.indexOf(f);
      +        if (index >= 0) {
                   if(getFileFilter() == f) {
      -                setFileFilter(null);
      +                if (isAcceptAllFileFilterUsed()) {
      +                    // choose default filter if it is used
      +                    setFileFilter(getAcceptAllFileFilter());
      +                }
      +                else if (index > 0) {
      +                    // choose the first filter, because it is not removed
      +                    setFileFilter(filters.get(0));
      +                }
      +                else if (filters.size() > 1) {
      +                    // choose the second filter, because the first one is removed
      +                    setFileFilter(filters.get(1));
      +                }
      +                else {
      +                    // no more filters
      +                    setFileFilter(null);
      +                }
                   }
                   FileFilter[] oldValue = getChoosableFileFilters();
                   filters.removeElement(f);
      diff --git a/src/share/classes/javax/swing/JTree.java b/src/share/classes/javax/swing/JTree.java
      index f4d89e0042438260bfd0693afbc01a1956935627..09b31da9f28a9ea861ccd9fd87dd2fb08bbe859e 100644
      --- a/src/share/classes/javax/swing/JTree.java
      +++ b/src/share/classes/javax/swing/JTree.java
      @@ -3751,7 +3751,7 @@ public class JTree extends JComponent implements Scrollable, Accessible
            * the nodes identified by in e.
            */
           void removeDescendantSelectedPaths(TreeModelEvent e) {
      -        TreePath            pPath = e.getTreePath();
      +        TreePath            pPath = SwingUtilities2.getTreePath(e, getModel());
               Object[]            oldChildren = e.getChildren();
               TreeSelectionModel  sm = getSelectionModel();
       
      @@ -3785,7 +3785,7 @@ public class JTree extends JComponent implements Scrollable, Accessible
                   // and update BasicTreeUIs treeStructureChanged method
                   // to update descendants in response to a treeStructureChanged
                   // event, all the children of the event won't collapse!
      -            TreePath            parent = e.getTreePath();
      +            TreePath            parent = SwingUtilities2.getTreePath(e, getModel());
       
                   if(parent == null)
                       return;
      @@ -3822,7 +3822,7 @@ public class JTree extends JComponent implements Scrollable, Accessible
                   if(e == null)
                       return;
       
      -            TreePath            parent = e.getTreePath();
      +            TreePath            parent = SwingUtilities2.getTreePath(e, getModel());
                   Object[]            children = e.getChildren();
       
                   if(children == null)
      diff --git a/src/share/classes/javax/swing/event/TreeModelEvent.java b/src/share/classes/javax/swing/event/TreeModelEvent.java
      index 62389469839d591d0eeeddf1da0a2090878c0c36..3c92dc16377a43835e4ccf8ca2d66936573993d9 100644
      --- a/src/share/classes/javax/swing/event/TreeModelEvent.java
      +++ b/src/share/classes/javax/swing/event/TreeModelEvent.java
      @@ -128,7 +128,7 @@ public class TreeModelEvent extends EventObject {
           public TreeModelEvent(Object source, Object[] path, int[] childIndices,
                                 Object[] children)
           {
      -        this(source, new TreePath(path), childIndices, children);
      +        this(source, (path == null) ? null : new TreePath(path), childIndices, children);
           }
       
           /**
      @@ -183,7 +183,7 @@ public class TreeModelEvent extends EventObject {
            */
           public TreeModelEvent(Object source, Object[] path)
           {
      -        this(source, new TreePath(path));
      +        this(source, (path == null) ? null : new TreePath(path));
           }
       
           /**
      diff --git a/src/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java b/src/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java
      index 1b741db47f653e8a7fa0e68503c44152b8688d47..c902252f4dc84bc8e39c08b4275cfc479bd9fb22 100644
      --- a/src/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java
      +++ b/src/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java
      @@ -73,6 +73,9 @@ public class BasicComboBoxEditor implements ComboBoxEditor,FocusListener {
       
               if ( anObject != null )  {
                   text = anObject.toString();
      +            if (text == null) {
      +                text = "";
      +            }
                   oldValue = anObject;
               } else {
                   text = "";
      diff --git a/src/share/classes/javax/swing/plaf/basic/BasicTreeUI.java b/src/share/classes/javax/swing/plaf/basic/BasicTreeUI.java
      index 3d39cf6a876c6f834d1149c4492d3e886615a255..0e7cd1768e753fafb5024d69bd0d46ef6f1f4fcb 100644
      --- a/src/share/classes/javax/swing/plaf/basic/BasicTreeUI.java
      +++ b/src/share/classes/javax/swing/plaf/basic/BasicTreeUI.java
      @@ -3827,7 +3827,7 @@ public class BasicTreeUI extends TreeUI
               //
               public void treeNodesChanged(TreeModelEvent e) {
                   if(treeState != null && e != null) {
      -                TreePath parentPath = e.getTreePath();
      +                TreePath parentPath = SwingUtilities2.getTreePath(e, getModel());
                       int[] indices = e.getChildIndices();
                       if (indices == null || indices.length == 0) {
                           // The root has changed
      @@ -3882,7 +3882,7 @@ public class BasicTreeUI extends TreeUI
       
                       updateLeadSelectionRow();
       
      -                TreePath       path = e.getTreePath();
      +                TreePath       path = SwingUtilities2.getTreePath(e, getModel());
       
                       if(treeState.isExpanded(path)) {
                           updateSize();
      @@ -3907,7 +3907,7 @@ public class BasicTreeUI extends TreeUI
       
                       updateLeadSelectionRow();
       
      -                TreePath       path = e.getTreePath();
      +                TreePath       path = SwingUtilities2.getTreePath(e, getModel());
       
                       if(treeState.isExpanded(path) ||
                          treeModel.getChildCount(path.getLastPathComponent()) == 0)
      @@ -3921,7 +3921,7 @@ public class BasicTreeUI extends TreeUI
       
                       updateLeadSelectionRow();
       
      -                TreePath       pPath = e.getTreePath();
      +                TreePath       pPath = SwingUtilities2.getTreePath(e, getModel());
       
                       if (pPath != null) {
                           pPath = pPath.getParentPath();
      diff --git a/src/share/classes/javax/swing/text/View.java b/src/share/classes/javax/swing/text/View.java
      index 097e6c33313a775814f5dfd760c2c00c3b4a70ba..c2e1e023d5a6e9ee7a94fe88ee96a608ad62282c 100644
      --- a/src/share/classes/javax/swing/text/View.java
      +++ b/src/share/classes/javax/swing/text/View.java
      @@ -1174,7 +1174,7 @@ public abstract class View implements SwingConstants {
               // formed by added elements (i.e. they will be updated
               // by initialization.
               index0 = Math.max(index0, 0);
      -        index1 = getViewIndex(elem.getDocument().getLength(), Position.Bias.Forward);
      +        index1 = Math.max((getViewCount() - 1), 0);
               for (int i = index0; i <= index1; i++) {
                   if (! ((i >= hole0) && (i <= hole1))) {
                       v = getView(i);
      diff --git a/src/share/classes/javax/swing/tree/FixedHeightLayoutCache.java b/src/share/classes/javax/swing/tree/FixedHeightLayoutCache.java
      index fffea8b0b5b1dd6322df15ee4cce64fc99223b7f..4f61aff73041e2e15808163025cfc51ff1791683 100644
      --- a/src/share/classes/javax/swing/tree/FixedHeightLayoutCache.java
      +++ b/src/share/classes/javax/swing/tree/FixedHeightLayoutCache.java
      @@ -26,13 +26,14 @@
       package javax.swing.tree;
       
       import javax.swing.event.TreeModelEvent;
      -import java.awt.Dimension;
       import java.awt.Rectangle;
       import java.util.Enumeration;
       import java.util.Hashtable;
       import java.util.NoSuchElementException;
       import java.util.Stack;
       
      +import sun.swing.SwingUtilities2;
      +
       /**
        * NOTE: This will become more open in a future release.
        * 

      @@ -346,7 +347,7 @@ public class FixedHeightLayoutCache extends AbstractLayoutCache { if(e != null) { int changedIndexs[]; FHTreeStateNode changedParent = getNodeForPath - (e.getTreePath(), false, false); + (SwingUtilities2.getTreePath(e, getModel()), false, false); int maxCounter; changedIndexs = e.getChildIndices(); @@ -390,7 +391,7 @@ public class FixedHeightLayoutCache extends AbstractLayoutCache { if(e != null) { int changedIndexs[]; FHTreeStateNode changedParent = getNodeForPath - (e.getTreePath(), false, false); + (SwingUtilities2.getTreePath(e, getModel()), false, false); int maxCounter; changedIndexs = e.getChildIndices(); @@ -429,7 +430,7 @@ public class FixedHeightLayoutCache extends AbstractLayoutCache { if(e != null) { int changedIndexs[]; int maxCounter; - TreePath parentPath = e.getTreePath(); + TreePath parentPath = SwingUtilities2.getTreePath(e, getModel()); FHTreeStateNode changedParentNode = getNodeForPath (parentPath, false, false); @@ -475,7 +476,7 @@ public class FixedHeightLayoutCache extends AbstractLayoutCache { */ public void treeStructureChanged(TreeModelEvent e) { if(e != null) { - TreePath changedPath = e.getTreePath(); + TreePath changedPath = SwingUtilities2.getTreePath(e, getModel()); FHTreeStateNode changedNode = getNodeForPath (changedPath, false, false); diff --git a/src/share/classes/javax/swing/tree/VariableHeightLayoutCache.java b/src/share/classes/javax/swing/tree/VariableHeightLayoutCache.java index ad91d1c84c2afbaaa28a6c2bbec6f099e446e485..5185194ed3be5b35bf37073cea49da7ac89c1fc5 100644 --- a/src/share/classes/javax/swing/tree/VariableHeightLayoutCache.java +++ b/src/share/classes/javax/swing/tree/VariableHeightLayoutCache.java @@ -26,7 +26,6 @@ package javax.swing.tree; import javax.swing.event.TreeModelEvent; -import java.awt.Dimension; import java.awt.Rectangle; import java.util.Enumeration; import java.util.Hashtable; @@ -34,6 +33,8 @@ import java.util.NoSuchElementException; import java.util.Stack; import java.util.Vector; +import sun.swing.SwingUtilities2; + /** * NOTE: This will become more open in a future release. *

      @@ -413,7 +414,7 @@ public class VariableHeightLayoutCache extends AbstractLayoutCache { TreeStateNode changedNode; changedIndexs = e.getChildIndices(); - changedNode = getNodeForPath(e.getTreePath(), false, false); + changedNode = getNodeForPath(SwingUtilities2.getTreePath(e, getModel()), false, false); if(changedNode != null) { Object changedValue = changedNode.getValue(); @@ -466,7 +467,7 @@ public class VariableHeightLayoutCache extends AbstractLayoutCache { TreeStateNode changedParentNode; changedIndexs = e.getChildIndices(); - changedParentNode = getNodeForPath(e.getTreePath(), false, false); + changedParentNode = getNodeForPath(SwingUtilities2.getTreePath(e, getModel()), false, false); /* Only need to update the children if the node has been expanded once. */ // PENDING(scott): make sure childIndexs is sorted! @@ -540,7 +541,7 @@ public class VariableHeightLayoutCache extends AbstractLayoutCache { TreeStateNode changedParentNode; changedIndexs = e.getChildIndices(); - changedParentNode = getNodeForPath(e.getTreePath(), false, false); + changedParentNode = getNodeForPath(SwingUtilities2.getTreePath(e, getModel()), false, false); // PENDING(scott): make sure that changedIndexs are sorted in // ascending order. if(changedParentNode != null && changedIndexs != null && @@ -628,7 +629,7 @@ public class VariableHeightLayoutCache extends AbstractLayoutCache { public void treeStructureChanged(TreeModelEvent e) { if(e != null) { - TreePath changedPath = e.getTreePath(); + TreePath changedPath = SwingUtilities2.getTreePath(e, getModel()); TreeStateNode changedNode; changedNode = getNodeForPath(changedPath, false, false); diff --git a/src/share/classes/javax/xml/crypto/dsig/dom/DOMValidateContext.java b/src/share/classes/javax/xml/crypto/dsig/dom/DOMValidateContext.java index 70e6d4598086e87eb743f430dd5408527151aab1..2ed14003ff92e9cb813184b8c7b80c321387cc00 100644 --- a/src/share/classes/javax/xml/crypto/dsig/dom/DOMValidateContext.java +++ b/src/share/classes/javax/xml/crypto/dsig/dom/DOMValidateContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2013 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/src/share/classes/sun/java2d/cmm/ProfileDataVerifier.java b/src/share/classes/sun/java2d/cmm/ProfileDataVerifier.java new file mode 100644 index 0000000000000000000000000000000000000000..e6100bbefd41153bf62223d91925d14610112be4 --- /dev/null +++ b/src/share/classes/sun/java2d/cmm/ProfileDataVerifier.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.java2d.cmm; + +public class ProfileDataVerifier { + /** + * Throws an IllegalArgumentException if the data does not correspond + * to a valid ICC Profile. + * + * @param data the specified profile data. + */ + public static void verify(byte[] data) { + if (data == null) { + throw new IllegalArgumentException("Invalid ICC Profile Data"); + } + + if (data.length < TOC_OFFSET) { + // not enough data for profile header + throw new IllegalArgumentException("Invalid ICC Profile Data"); + } + + // check profile size + final int size = readInt32(data, 0); + final int tagCount = readInt32(data, HEADER_SIZE); + + if (tagCount < 0 || tagCount > MAX_TAG_COUNT) { + throw new IllegalArgumentException("Invalid ICC Profile Data"); + } + + if (size < (TOC_OFFSET + (tagCount * TOC_RECORD_SIZE)) || + size > data.length) + { + throw new IllegalArgumentException("Invalid ICC Profile Data"); + } + + final int sig = readInt32(data, 36); + + if (PROFILE_FILE_SIGNATURE != sig) { + throw new IllegalArgumentException("Invalid ICC Profile Data"); + } + + // verify table of content + for (int i = 0; i < tagCount; i++) { + final int tag_offset = getTagOffset(i, data); + final int tag_size = getTagSize(i, data); + + if (tag_offset < TOC_OFFSET || tag_offset > size) { + throw new IllegalArgumentException("Invalid ICC Profile Data"); + } + + if (tag_size < 0 || + tag_size > (Integer.MAX_VALUE - tag_offset) || + tag_size + tag_offset > size) + { + throw new IllegalArgumentException("Invalid ICC Profile Data"); + } + } + } + + private static int getTagOffset(int idx, byte[] data) { + final int pos = TOC_OFFSET + idx * TOC_RECORD_SIZE + 4; + return readInt32(data, pos); + } + + private static int getTagSize(int idx, byte[] data) { + final int pos = TOC_OFFSET + idx * TOC_RECORD_SIZE + 8; + return readInt32(data, pos); + } + + private static int readInt32(byte[] data, int off) { + int res = 0; + for (int i = 0; i < 4; i++) { + res = res << 8; + + res |= (0xff & data[off++]); + } + return res; + } + + /** + * Lcms limit for the number of tags: 100 + * Kcms limit for the number of tags: N/A + */ + private static final int MAX_TAG_COUNT = 100; + + private static final int HEADER_SIZE = 128; + private static final int TOC_OFFSET = HEADER_SIZE + 4; + private static final int TOC_RECORD_SIZE = 12; + + private static final int PROFILE_FILE_SIGNATURE = 0x61637370; +} diff --git a/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java b/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java index 201e236210c42c617ea2b2e67d6e1823d60816b3..1efb3e1657d299eb76fe8981bc6c4c093e2b2fbc 100644 --- a/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java +++ b/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java @@ -2806,9 +2806,10 @@ public class HttpURLConnection extends java.net.HttpURLConnection { if (SET_COOKIE.equalsIgnoreCase(name) || SET_COOKIE2.equalsIgnoreCase(name)) { + // Filtering only if there is a cookie handler. [Assumption: the // cookie handler will store/retrieve the HttpOnly cookies] - if (cookieHandler == null) + if (cookieHandler == null || value.length() == 0) return value; sun.misc.JavaNetHttpCookieAccess access = diff --git a/src/share/classes/sun/rmi/transport/proxy/CGIHandler.java b/src/share/classes/sun/rmi/transport/proxy/CGIHandler.java index a60b23864af368b459bff875fec04139da4c67b1..657683cd6f84f077aee5e4cff69a2acb46d6309e 100644 --- a/src/share/classes/sun/rmi/transport/proxy/CGIHandler.java +++ b/src/share/classes/sun/rmi/transport/proxy/CGIHandler.java @@ -38,6 +38,10 @@ class CGIClientException extends Exception { public CGIClientException(String s) { super(s); } + + public CGIClientException(String s, Throwable cause) { + super(s, cause); + } } /** @@ -50,6 +54,10 @@ class CGIServerException extends Exception { public CGIServerException(String s) { super(s); } + + public CGIServerException(String s, Throwable cause) { + super(s, cause); + } } /** @@ -148,13 +156,16 @@ public final class CGIHandler { try { handler.execute(param); } catch (CGIClientException e) { + e.printStackTrace(); returnClientError(e.getMessage()); } catch (CGIServerException e) { + e.printStackTrace(); returnServerError(e.getMessage()); } else returnClientError("invalid command."); } catch (Exception e) { + e.printStackTrace(); returnServerError("internal error: " + e.getMessage()); } System.exit(0); @@ -225,7 +236,7 @@ final class CGIForwardCommand implements CGICommandHandler { try { port = Integer.parseInt(param); } catch (NumberFormatException e) { - throw new CGIClientException("invalid port number."); + throw new CGIClientException("invalid port number.", e); } if (port <= 0 || port > 0xFFFF) throw new CGIClientException("invalid port: " + port); @@ -238,7 +249,7 @@ final class CGIForwardCommand implements CGICommandHandler { try { socket = new Socket(InetAddress.getLocalHost(), port); } catch (IOException e) { - throw new CGIServerException("could not connect to local port"); + throw new CGIServerException("could not connect to local port", e); } /* @@ -249,9 +260,9 @@ final class CGIForwardCommand implements CGICommandHandler { try { clientIn.readFully(buffer); } catch (EOFException e) { - throw new CGIClientException("unexpected EOF reading request body"); + throw new CGIClientException("unexpected EOF reading request body", e); } catch (IOException e) { - throw new CGIClientException("error reading request body"); + throw new CGIClientException("error reading request body", e); } /* @@ -266,7 +277,7 @@ final class CGIForwardCommand implements CGICommandHandler { socketOut.write(buffer); socketOut.flush(); } catch (IOException e) { - throw new CGIServerException("error writing to server"); + throw new CGIServerException("error writing to server", e); } /* @@ -276,7 +287,7 @@ final class CGIForwardCommand implements CGICommandHandler { try { socketIn = new DataInputStream(socket.getInputStream()); } catch (IOException e) { - throw new CGIServerException("error reading from server"); + throw new CGIServerException("error reading from server", e); } String key = "Content-length:".toLowerCase(); boolean contentLengthFound = false; @@ -286,7 +297,7 @@ final class CGIForwardCommand implements CGICommandHandler { try { line = getLine(socketIn); } catch (IOException e) { - throw new CGIServerException("error reading from server"); + throw new CGIServerException("error reading from server", e); } if (line == null) throw new CGIServerException( @@ -313,9 +324,9 @@ final class CGIForwardCommand implements CGICommandHandler { socketIn.readFully(buffer); } catch (EOFException e) { throw new CGIServerException( - "unexpected EOF reading server response"); + "unexpected EOF reading server response", e); } catch (IOException e) { - throw new CGIServerException("error reading from server"); + throw new CGIServerException("error reading from server", e); } /* @@ -327,7 +338,7 @@ final class CGIForwardCommand implements CGICommandHandler { try { System.out.write(buffer); } catch (IOException e) { - throw new CGIServerException("error writing response"); + throw new CGIServerException("error writing response", e); } System.out.flush(); } diff --git a/src/share/classes/sun/security/krb5/KdcComm.java b/src/share/classes/sun/security/krb5/KdcComm.java index c3048aaf64a8d66b61e98083d1d7a59bd3b7f6c2..ae3b0f098b7b92dff077240e37478c3ff1760567 100644 --- a/src/share/classes/sun/security/krb5/KdcComm.java +++ b/src/share/classes/sun/security/krb5/KdcComm.java @@ -46,6 +46,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.HashSet; +import java.util.Iterator; import sun.security.krb5.internal.KRBError; /** @@ -203,7 +204,6 @@ public final class KdcComm { if (obuf == null) return null; - Exception savedException = null; Config cfg = Config.getInstance(); if (realm == null) { @@ -218,48 +218,61 @@ public final class KdcComm { if (kdcList == null) { throw new KrbException("Cannot get kdc for realm " + realm); } - String tempKdc = null; // may include the port number also + // tempKdc may include the port number also + Iterator tempKdc = KdcAccessibility.list(kdcList).iterator(); + if (!tempKdc.hasNext()) { + throw new KrbException("Cannot get kdc for realm " + realm); + } byte[] ibuf = null; - for (String tmp: KdcAccessibility.list(kdcList)) { - tempKdc = tmp; - try { - ibuf = send(obuf,tempKdc,useTCP); - KRBError ke = null; + try { + ibuf = sendIfPossible(obuf, tempKdc.next(), useTCP); + } catch(Exception first) { + while(tempKdc.hasNext()) { try { - ke = new KRBError(ibuf); - } catch (Exception e) { - // OK - } - if (ke != null && ke.getErrorCode() == - Krb5.KRB_ERR_RESPONSE_TOO_BIG) { - ibuf = send(obuf, tempKdc, true); - } - KdcAccessibility.removeBad(tempKdc); - break; - } catch (Exception e) { - if (DEBUG) { - System.out.println(">>> KrbKdcReq send: error trying " + - tempKdc); - e.printStackTrace(System.out); - } - KdcAccessibility.addBad(tempKdc); - savedException = e; + ibuf = sendIfPossible(obuf, tempKdc.next(), useTCP); + if (ibuf != null) { + return ibuf; + } + } catch(Exception ignore) {} } + throw first; } if (ibuf == null) { - if (savedException != null) { - if (savedException instanceof IOException) { - throw (IOException) savedException; - } else { - throw (KrbException) savedException; - } - } else { - throw new IOException("Cannot get a KDC reply"); - } + throw new IOException("Cannot get a KDC reply"); } return ibuf; } + // send the AS Request to the specified KDC + // failover to using TCP if useTCP is not set and response is too big + private byte[] sendIfPossible(byte[] obuf, String tempKdc, boolean useTCP) + throws IOException, KrbException { + + try { + byte[] ibuf = send(obuf, tempKdc, useTCP); + KRBError ke = null; + try { + ke = new KRBError(ibuf); + } catch (Exception e) { + // OK + } + if (ke != null && ke.getErrorCode() == + Krb5.KRB_ERR_RESPONSE_TOO_BIG) { + ibuf = send(obuf, tempKdc, true); + } + KdcAccessibility.removeBad(tempKdc); + return ibuf; + } catch(Exception e) { + if (DEBUG) { + System.out.println(">>> KrbKdcReq send: error trying " + + tempKdc); + e.printStackTrace(System.out); + } + KdcAccessibility.addBad(tempKdc); + throw e; + } + } + // send the AS Request to the specified KDC private byte[] send(byte[] obuf, String tempKdc, boolean useTCP) @@ -500,7 +513,7 @@ public final class KdcComm { } // Returns a preferred KDC list by putting the bad ones at the end - private static synchronized String[] list(String kdcList) { + private static synchronized List list(String kdcList) { StringTokenizer st = new StringTokenizer(kdcList); List list = new ArrayList<>(); if (badPolicy == BpType.TRY_LAST) { @@ -519,7 +532,7 @@ public final class KdcComm { list.add(st.nextToken()); } } - return list.toArray(new String[list.size()]); + return list; } } } diff --git a/src/share/classes/sun/security/provider/certpath/RevocationChecker.java b/src/share/classes/sun/security/provider/certpath/RevocationChecker.java index 98d8a9d227237650e8fdcdeb7e454d502373c76d..05b517892feb9f6128b6e979333656366d3fd780 100644 --- a/src/share/classes/sun/security/provider/certpath/RevocationChecker.java +++ b/src/share/classes/sun/security/provider/certpath/RevocationChecker.java @@ -675,8 +675,12 @@ class RevocationChecker extends PKIXRevocationChecker { responderURI, respCert, params.date(), ocspExtensions); } - } catch (IOException e) { - throw new CertPathValidatorException(e); + } catch (Exception e) { + if (e instanceof CertPathValidatorException) { + throw (CertPathValidatorException) e; + } else { + throw new CertPathValidatorException(e); + } } RevocationStatus rs = diff --git a/src/share/classes/sun/security/ssl/Handshaker.java b/src/share/classes/sun/security/ssl/Handshaker.java index 8314c379d330b4fd1df9a50e221e1c6435732868..17b1f92ac74c7a3f06e7e12db69da87ac0b4f8b7 100644 --- a/src/share/classes/sun/security/ssl/Handshaker.java +++ b/src/share/classes/sun/security/ssl/Handshaker.java @@ -187,14 +187,14 @@ abstract class Handshaker { "sun.security.ssl.allowLegacyHelloMessages", true); // To prevent the TLS renegotiation issues, by setting system property - // "jdk.tls.rejectClientInitializedRenego" to true, applications in server - // side can disable all client initiated SSL renegotiations regardless - // of the support of TLS protocols. + // "jdk.tls.rejectClientInitiatedRenegotiation" to true, applications in + // server side can disable all client initiated SSL renegotiations + // regardless of the support of TLS protocols. // // By default, allow client initiated renegotiations. static final boolean rejectClientInitiatedRenego = Debug.getBooleanProperty( - "jdk.tls.rejectClientInitializedRenego", false); + "jdk.tls.rejectClientInitiatedRenegotiation", false); // need to dispose the object when it is invalidated boolean invalidated; diff --git a/src/share/classes/sun/security/ssl/ServerHandshaker.java b/src/share/classes/sun/security/ssl/ServerHandshaker.java index 69c78324775da0e5ccdadd4fa045ed733451d755..e317e1f18c568c6c3e10d9fb167cb54188636a0e 100644 --- a/src/share/classes/sun/security/ssl/ServerHandshaker.java +++ b/src/share/classes/sun/security/ssl/ServerHandshaker.java @@ -281,7 +281,15 @@ final class ServerHandshaker extends Handshaker { // Reject client initiated renegotiation? // - // Should not have any impact on server initiated renegotiation. + // If server side should reject client-initiated renegotiation, + // send an alert_handshake_failure fatal alert, not a no_renegotiation + // warning alert (no_renegotiation must be a warning: RFC 2246). + // no_renegotiation might seem more natural at first, but warnings + // are not appropriate because the sending party does not know how + // the receiving party will behave. This state must be treated as + // a fatal server condition. + // + // This will not have any impact on server initiated renegotiation. if (rejectClientInitiatedRenego && !isInitialHandshake && state != HandshakeMessage.ht_hello_request) { fatalSE(Alerts.alert_handshake_failure, diff --git a/src/share/classes/sun/swing/SwingUtilities2.java b/src/share/classes/sun/swing/SwingUtilities2.java index 57f7bb39cdccee5f9ce4673f907921da0d6daec2..beee3c481eed22acf6ab9a55a8be3c3b1fdc4304 100644 --- a/src/share/classes/sun/swing/SwingUtilities2.java +++ b/src/share/classes/sun/swing/SwingUtilities2.java @@ -33,18 +33,19 @@ import java.awt.event.*; import java.awt.font.*; import java.awt.geom.*; import java.awt.print.PrinterGraphics; -import java.text.Bidi; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import javax.swing.*; -import javax.swing.plaf.*; +import javax.swing.event.TreeModelEvent; import javax.swing.text.Highlighter; import javax.swing.text.JTextComponent; import javax.swing.text.DefaultHighlighter; import javax.swing.text.DefaultCaret; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumnModel; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreePath; import sun.swing.PrintColorUIResource; import sun.swing.ImageIconUIResource; @@ -1900,4 +1901,22 @@ public class SwingUtilities2 { } return InputEvent.ALT_MASK; } + + /** + * Returns the {@link TreePath} that identifies the changed nodes. + * + * @param event changes in a tree model + * @param model corresponing tree model + * @return the path to the changed nodes + */ + public static TreePath getTreePath(TreeModelEvent event, TreeModel model) { + TreePath path = event.getTreePath(); + if ((path == null) && (model != null)) { + Object root = model.getRoot(); + if (root != null) { + path = new TreePath(root); + } + } + return path; + } } diff --git a/src/share/classes/sun/util/resources/pt/CalendarData_pt_BR.properties b/src/share/classes/sun/util/resources/pt/CalendarData_pt_BR.properties new file mode 100644 index 0000000000000000000000000000000000000000..ea543b258e898e0721293d86c96c26a8f4329288 --- /dev/null +++ b/src/share/classes/sun/util/resources/pt/CalendarData_pt_BR.properties @@ -0,0 +1,40 @@ +# +# Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. 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. +# + +# (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved +# (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved +# +# The original version of this source code and documentation +# is copyrighted and owned by Taligent, Inc., a wholly-owned +# subsidiary of IBM. These materials are provided under terms +# of a License Agreement between Taligent and Sun. This technology +# is protected by multiple US and International patents. +# +# This notice and attribution to Taligent may not be removed. +# Taligent is a registered trademark of Taligent, Inc. + + +firstDayOfWeek=1 +minimalDaysInFirstWeek=1 diff --git a/src/share/native/sun/font/layout/GlyphIterator.cpp b/src/share/native/sun/font/layout/GlyphIterator.cpp index d0cd46732ed9251789d94e3d91fb579ce41e6c83..3ccf66fdc601297f266ea648d5870828a2744893 100644 --- a/src/share/native/sun/font/layout/GlyphIterator.cpp +++ b/src/share/native/sun/font/layout/GlyphIterator.cpp @@ -66,6 +66,7 @@ GlyphIterator::GlyphIterator(LEGlyphStorage &theGlyphStorage, GlyphPositionAdjus nextLimit = -1; prevLimit = glyphCount; } + filterResetCache(); } GlyphIterator::GlyphIterator(GlyphIterator &that) @@ -84,6 +85,7 @@ GlyphIterator::GlyphIterator(GlyphIterator &that) glyphGroup = that.glyphGroup; glyphClassDefinitionTable = that.glyphClassDefinitionTable; markAttachClassDefinitionTable = that.markAttachClassDefinitionTable; + filterResetCache(); } GlyphIterator::GlyphIterator(GlyphIterator &that, FeatureMask newFeatureMask) @@ -102,6 +104,7 @@ GlyphIterator::GlyphIterator(GlyphIterator &that, FeatureMask newFeatureMask) glyphGroup = 0; glyphClassDefinitionTable = that.glyphClassDefinitionTable; markAttachClassDefinitionTable = that.markAttachClassDefinitionTable; + filterResetCache(); } GlyphIterator::GlyphIterator(GlyphIterator &that, le_uint16 newLookupFlags) @@ -120,6 +123,7 @@ GlyphIterator::GlyphIterator(GlyphIterator &that, le_uint16 newLookupFlags) glyphGroup = that.glyphGroup; glyphClassDefinitionTable = that.glyphClassDefinitionTable; markAttachClassDefinitionTable = that.markAttachClassDefinitionTable; + filterResetCache(); } GlyphIterator::~GlyphIterator() @@ -133,6 +137,7 @@ void GlyphIterator::reset(le_uint16 newLookupFlags, FeatureMask newFeatureMask) featureMask = newFeatureMask; glyphGroup = 0; lookupFlags = newLookupFlags; + filterResetCache(); } LEGlyphID *GlyphIterator::insertGlyphs(le_int32 count, LEErrorCode& success) @@ -381,53 +386,68 @@ void GlyphIterator::setCursiveGlyph() glyphPositionAdjustments->setCursiveGlyph(position, baselineIsLogicalEnd()); } -le_bool GlyphIterator::filterGlyph(le_uint32 index) const +void GlyphIterator::filterResetCache(void) { + filterCacheValid = FALSE; + } + +le_bool GlyphIterator::filterGlyph(le_uint32 index) { - LEErrorCode success = LE_NO_ERROR; LEGlyphID glyphID = glyphStorage[index]; - le_int32 glyphClass = gcdNoGlyphClass; - if (LE_GET_GLYPH(glyphID) >= 0xFFFE) { - return TRUE; - } + if (!filterCacheValid || filterCache.id != glyphID) { + filterCache.id = glyphID; + le_bool &filterResult = filterCache.result; // NB: Making this a reference to accept the updated value, in case + // we want more fancy cacheing in the future. + if (LE_GET_GLYPH(glyphID) >= 0xFFFE) { + filterResult = TRUE; + } else { + LEErrorCode success = LE_NO_ERROR; + le_int32 glyphClass = gcdNoGlyphClass; if (glyphClassDefinitionTable.isValid()) { glyphClass = glyphClassDefinitionTable->getGlyphClass(glyphClassDefinitionTable, glyphID, success); } - - switch (glyphClass) - { + switch (glyphClass) { case gcdNoGlyphClass: - return FALSE; + filterResult = FALSE; + break; case gcdSimpleGlyph: - return (lookupFlags & lfIgnoreBaseGlyphs) != 0; + filterResult = (lookupFlags & lfIgnoreBaseGlyphs) != 0; + break; case gcdLigatureGlyph: - return (lookupFlags & lfIgnoreLigatures) != 0; + filterResult = (lookupFlags & lfIgnoreLigatures) != 0; + break; case gcdMarkGlyph: - { if ((lookupFlags & lfIgnoreMarks) != 0) { - return TRUE; - } - + filterResult = TRUE; + } else { le_uint16 markAttachType = (lookupFlags & lfMarkAttachTypeMask) >> lfMarkAttachTypeShift; if ((markAttachType != 0) && (markAttachClassDefinitionTable.isValid())) { - return markAttachClassDefinitionTable - -> getGlyphClass(markAttachClassDefinitionTable, glyphID, success) != markAttachType; + filterResult = (markAttachClassDefinitionTable + -> getGlyphClass(markAttachClassDefinitionTable, glyphID, success) != markAttachType); + } else { + filterResult = FALSE; } - - return FALSE; } + break; case gcdComponentGlyph: - return (lookupFlags & lfIgnoreBaseGlyphs) != 0; + filterResult = ((lookupFlags & lfIgnoreBaseGlyphs) != 0); + break; default: - return FALSE; + filterResult = FALSE; + break; } + } + filterCacheValid = TRUE; + } + + return filterCache.result; } le_bool GlyphIterator::hasFeatureTag(le_bool matchGroup) const diff --git a/src/share/native/sun/font/layout/GlyphIterator.h b/src/share/native/sun/font/layout/GlyphIterator.h index d8db62a12986012a405b188964d03a95192defa5..666b94dbcf3d56053944ec9ad747b3207e1de4ea 100644 --- a/src/share/native/sun/font/layout/GlyphIterator.h +++ b/src/share/native/sun/font/layout/GlyphIterator.h @@ -98,7 +98,7 @@ public: le_int32 applyInsertions(); private: - le_bool filterGlyph(le_uint32 index) const; + le_bool filterGlyph(le_uint32 index); le_bool hasFeatureTag(le_bool matchGroup) const; le_bool nextInternal(le_uint32 delta = 1); le_bool prevInternal(le_uint32 delta = 1); @@ -121,6 +121,14 @@ private: LEReferenceTo markAttachClassDefinitionTable; GlyphIterator &operator=(const GlyphIterator &other); // forbid copying of this class + + struct { + LEGlyphID id; + le_bool result; + } filterCache; + le_bool filterCacheValid; + + void filterResetCache(void); }; U_NAMESPACE_END diff --git a/src/share/native/sun/font/layout/KernTable.cpp b/src/share/native/sun/font/layout/KernTable.cpp index 13ddd0f3b32ab8416588d6e0d4ae56feabbb7b60..2d946513fb824d7c3c9e9be6baaf7ed69a4d5fe3 100644 --- a/src/share/native/sun/font/layout/KernTable.cpp +++ b/src/share/native/sun/font/layout/KernTable.cpp @@ -96,7 +96,7 @@ LE_CORRECT_SIZE(KernTableHeader, KERN_TABLE_HEADER_SIZE) * TODO: respect header flags */ KernTable::KernTable(const LETableReference& base, LEErrorCode &success) - : pairs(), pairsSwapped(NULL), fTable(base) + : pairsSwapped(NULL), fTable(base) { if(LE_FAILURE(success) || (fTable.isEmpty())) { #if DEBUG @@ -143,32 +143,36 @@ KernTable::KernTable(const LETableReference& base, LEErrorCode &success) #endif if(LE_SUCCESS(success) && nPairs>0) { - // pairs is an instance member, and table is on the stack. - // set 'pairs' based on table.getAlias(). This will range check it. - - pairs = LEReferenceToArrayOf(fTable, // based on overall table - success, - (const PairInfo*)table.getAlias(), // subtable 0 + .. - KERN_SUBTABLE_0_HEADER_SIZE, // .. offset of header size - nPairs); // count - } - if (LE_SUCCESS(success) && pairs.isValid()) { - pairsSwapped = (PairInfo*)(malloc(nPairs*sizeof(PairInfo))); - PairInfo *p = (PairInfo*)pairsSwapped; - for (int i = 0; LE_SUCCESS(success) && i < nPairs; i++, p++) { - memcpy(p, pairs.getAlias(i,success), KERN_PAIRINFO_SIZE); - p->key = SWAPL(p->key); + // pairsSwapped is an instance member, and table is on the stack. + // set 'pairsSwapped' based on table.getAlias(). This will range check it. + + pairsSwapped = (PairInfo*)(fTable.getFont()->getKernPairs()); + if (pairsSwapped == NULL) { + LEReferenceToArrayOfpairs = + LEReferenceToArrayOf(fTable, // based on overall table + success, + (const PairInfo*)table.getAlias(), // subtable 0 + .. + KERN_SUBTABLE_0_HEADER_SIZE, // .. offset of header size + nPairs); // count + if (LE_SUCCESS(success) && pairs.isValid()) { + pairsSwapped = (PairInfo*)(malloc(nPairs*sizeof(PairInfo))); + PairInfo *p = (PairInfo*)pairsSwapped; + for (int i = 0; LE_SUCCESS(success) && i < nPairs; i++, p++) { + memcpy(p, pairs.getAlias(i,success), KERN_PAIRINFO_SIZE); + p->key = SWAPL(p->key); + } + fTable.getFont()->setKernPairs((void*)pairsSwapped); // store it } - fTable.getFont()->setKernPairs((void*)pairsSwapped); // store it + } } #if 0 - fprintf(stderr, "coverage: %0.4x nPairs: %d pairs %p\n", coverage, nPairs, pairs.getAlias()); + fprintf(stderr, "coverage: %0.4x nPairs: %d pairs %p\n", coverage, nPairs, pairsSwapped); fprintf(stderr, " searchRange: %d entrySelector: %d rangeShift: %d\n", searchRange, entrySelector, rangeShift); fprintf(stderr, "[[ ignored font table entries: range %d selector %d shift %d ]]\n", SWAPW(table->searchRange), SWAPW(table->entrySelector), SWAPW(table->rangeShift)); #endif #if DEBUG - fprintf(stderr, "coverage: %0.4x nPairs: %d pairs 0x%x\n", coverage, nPairs, pairs); + fprintf(stderr, "coverage: %0.4x nPairs: %d pairs 0x%x\n", coverage, nPairs, pairsSwapped); fprintf(stderr, " searchRange(pairs): %d entrySelector: %d rangeShift(pairs): %d\n", searchRange, entrySelector, rangeShift); @@ -182,7 +186,7 @@ KernTable::KernTable(const LETableReference& base, LEErrorCode &success) ids[id] = (char)i; } } - PairInfo *p = pairs; + PairInfo *p = pairsSwapped; for (int i = 0; i < nPairs; ++i, p++) { le_uint32 k = p->key; le_uint16 left = (k >> 16) & 0xffff; diff --git a/src/share/native/sun/font/layout/KernTable.h b/src/share/native/sun/font/layout/KernTable.h index 1cc4f872d3be54b72e4a50daed116376bdbfee44..c667a18c05649293b43b183019f32722e621f22b 100644 --- a/src/share/native/sun/font/layout/KernTable.h +++ b/src/share/native/sun/font/layout/KernTable.h @@ -57,7 +57,6 @@ class U_LAYOUT_API KernTable private: le_uint16 coverage; le_uint16 nPairs; - LEReferenceToArrayOf pairs; PairInfo *pairsSwapped; const LETableReference &fTable; le_uint16 searchRange; diff --git a/src/share/native/sun/font/layout/LETableReference.h b/src/share/native/sun/font/layout/LETableReference.h index dab52b664a88b6ecc7a95fd208f405e33cb9205f..dbee61fba7fedee4090cc4f4830bc34d9fa4fd3b 100644 --- a/src/share/native/sun/font/layout/LETableReference.h +++ b/src/share/native/sun/font/layout/LETableReference.h @@ -376,7 +376,7 @@ public: * @param success error status * @param atPtr location of reference - if NULL, will be at offset zero (i.e. downcast of parent). Otherwise must be a pointer within parent's bounds. */ - LEReferenceTo(const LETableReference &parent, LEErrorCode &success, const void* atPtr) + inline LEReferenceTo(const LETableReference &parent, LEErrorCode &success, const void* atPtr) : LETableReference(parent, parent.ptrToOffset(atPtr, success), LE_UINTPTR_MAX, success) { verifyLength(0, LETableVarSizer::getSize(), success); if(LE_FAILURE(success)) clear(); @@ -384,31 +384,31 @@ public: /** * ptr plus offset */ - LEReferenceTo(const LETableReference &parent, LEErrorCode &success, const void* atPtr, size_t offset) + inline LEReferenceTo(const LETableReference &parent, LEErrorCode &success, const void* atPtr, size_t offset) : LETableReference(parent, parent.ptrToOffset(atPtr, success)+offset, LE_UINTPTR_MAX, success) { verifyLength(0, LETableVarSizer::getSize(), success); if(LE_FAILURE(success)) clear(); } - LEReferenceTo(const LETableReference &parent, LEErrorCode &success, size_t offset) + inline LEReferenceTo(const LETableReference &parent, LEErrorCode &success, size_t offset) : LETableReference(parent, offset, LE_UINTPTR_MAX, success) { verifyLength(0, LETableVarSizer::getSize(), success); if(LE_FAILURE(success)) clear(); } - LEReferenceTo(const LETableReference &parent, LEErrorCode &success) + inline LEReferenceTo(const LETableReference &parent, LEErrorCode &success) : LETableReference(parent, 0, LE_UINTPTR_MAX, success) { verifyLength(0, LETableVarSizer::getSize(), success); if(LE_FAILURE(success)) clear(); } - LEReferenceTo(const LEFontInstance *font, LETag tableTag, LEErrorCode &success) + inline LEReferenceTo(const LEFontInstance *font, LETag tableTag, LEErrorCode &success) : LETableReference(font, tableTag, success) { verifyLength(0, LETableVarSizer::getSize(), success); if(LE_FAILURE(success)) clear(); } - LEReferenceTo(const le_uint8 *data, size_t length = LE_UINTPTR_MAX) : LETableReference(data, length) {} - LEReferenceTo(const T *data, size_t length = LE_UINTPTR_MAX) : LETableReference((const le_uint8*)data, length) {} - LEReferenceTo() : LETableReference(NULL) {} + inline LEReferenceTo(const le_uint8 *data, size_t length = LE_UINTPTR_MAX) : LETableReference(data, length) {} + inline LEReferenceTo(const T *data, size_t length = LE_UINTPTR_MAX) : LETableReference((const le_uint8*)data, length) {} + inline LEReferenceTo() : LETableReference(NULL) {} - LEReferenceTo& operator=(const T* other) { + inline LEReferenceTo& operator=(const T* other) { setRaw(other); return *this; } diff --git a/src/share/native/sun/font/layout/LayoutEngine.cpp b/src/share/native/sun/font/layout/LayoutEngine.cpp index 6690316f32d2495946efe2c438187e2860b3c8f7..30fb0bbede59bf1297d061f8cc9fe7d1a1145de7 100644 --- a/src/share/native/sun/font/layout/LayoutEngine.cpp +++ b/src/share/native/sun/font/layout/LayoutEngine.cpp @@ -569,7 +569,6 @@ void LayoutEngine::reset() { if(fGlyphStorage!=NULL) { fGlyphStorage->reset(); - fGlyphStorage = NULL; } } diff --git a/src/share/native/sun/font/layout/OpenTypeUtilities.cpp b/src/share/native/sun/font/layout/OpenTypeUtilities.cpp index f234e9484e2bec2e226f9d9dfa523e616646b520..4d810df69f87bf9e2debd0402434dc5d59644661 100644 --- a/src/share/native/sun/font/layout/OpenTypeUtilities.cpp +++ b/src/share/native/sun/font/layout/OpenTypeUtilities.cpp @@ -79,6 +79,7 @@ le_int8 OpenTypeUtilities::highBit(le_int32 value) Offset OpenTypeUtilities::getTagOffset(LETag tag, const LEReferenceToArrayOf &records, LEErrorCode &success) { + const TagAndOffsetRecord *r0 = (const TagAndOffsetRecord*)records.getAlias(); if(LE_FAILURE(success)) return 0; le_uint32 recordCount = records.getCount(); @@ -89,17 +90,17 @@ Offset OpenTypeUtilities::getTagOffset(LETag tag, const LEReferenceToArrayOftag; + const ATag &aTag = (r0+extra)->tag; if (SWAPT(aTag) <= tag) { index = extra; } } - while (probe > (1 << 0) && LE_SUCCESS(success)) { + while (probe > (1 << 0)) { probe >>= 1; { - const ATag &aTag = records.getAlias(index+probe,success)->tag; + const ATag &aTag = (r0+index+probe)->tag; if (SWAPT(aTag) <= tag) { index += probe; } @@ -107,9 +108,9 @@ Offset OpenTypeUtilities::getTagOffset(LETag tag, const LEReferenceToArrayOftag; + const ATag &aTag = (r0+index)->tag; if (SWAPT(aTag) == tag) { - return SWAPW(records.getAlias(index,success)->offset); + return SWAPW((r0+index)->offset); } } diff --git a/src/share/native/sun/java2d/opengl/OGLContext.c b/src/share/native/sun/java2d/opengl/OGLContext.c index b9c60046070544fbc180a469adb91314efdb29ea..d1484f73e37d69a4f7e46ebbdaddf5c19df8a5f1 100644 --- a/src/share/native/sun/java2d/opengl/OGLContext.c +++ b/src/share/native/sun/java2d/opengl/OGLContext.c @@ -662,6 +662,13 @@ OGLContext_IsFBObjectExtensionAvailable(JNIEnv *env, return JNI_FALSE; } + // next see if the depth texture extension is available + if (!OGLContext_IsExtensionAvailable(extString, + "GL_ARB_depth_texture")) + { + return JNI_FALSE; + } + // next see if the fbobject system property has been enabled isFBObjectEnabled = JNU_GetStaticFieldByName(env, NULL, diff --git a/src/share/native/sun/management/DiagnosticCommandImpl.c b/src/share/native/sun/management/DiagnosticCommandImpl.c index 4f601ed55a772ffabec4ea0e3d7a4c34472cc376..4ca0315abc3eef5a61054e5d7fdc9365bb0eaaec 100644 --- a/src/share/native/sun/management/DiagnosticCommandImpl.c +++ b/src/share/native/sun/management/DiagnosticCommandImpl.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/src/solaris/classes/sun/awt/X11/XBaseMenuWindow.java b/src/solaris/classes/sun/awt/X11/XBaseMenuWindow.java index 036c650324e1d31240893211ed9b36c6e3edac69..783f4acb935448b4baea5882955f7cd3a8b14a9a 100644 --- a/src/solaris/classes/sun/awt/X11/XBaseMenuWindow.java +++ b/src/solaris/classes/sun/awt/X11/XBaseMenuWindow.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -904,11 +904,12 @@ abstract public class XBaseMenuWindow extends XWindow { */ public void dispose() { setDisposed(true); - EventQueue.invokeLater(new Runnable() { + InvocationEvent ev = new InvocationEvent(target, new Runnable() { public void run() { doDispose(); } }); + super.postEvent(ev); } /** @@ -933,11 +934,12 @@ abstract public class XBaseMenuWindow extends XWindow { * so events can not be processed using standart means */ void postEvent(final AWTEvent event) { - EventQueue.invokeLater(new Runnable() { - public void run() { - handleEvent(event); - } - }); + InvocationEvent ev = new InvocationEvent(event.getSource(), new Runnable() { + public void run() { + handleEvent(event); + } + }); + super.postEvent(ev); } /** diff --git a/src/solaris/classes/sun/awt/X11/XChoicePeer.java b/src/solaris/classes/sun/awt/X11/XChoicePeer.java index 855ce05977d02668adb12feffd957c530e4a491d..561d9a6a1c460f18f9cacd843bee0bda2d37035f 100644 --- a/src/solaris/classes/sun/awt/X11/XChoicePeer.java +++ b/src/solaris/classes/sun/awt/X11/XChoicePeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1033,15 +1033,17 @@ public class XChoicePeer extends XComponentPeer implements ChoicePeer, ToplevelS //fix 6252982: PIT: Keyboard FocusTraversal not working when choice's drop-down is visible, on XToolkit if (e instanceof KeyEvent){ // notify XWindow that this event had been already handled and no need to post it again - EventQueue.invokeLater(new Runnable() { - public void run() { - if(target.isFocusable() && - getParentTopLevel().isFocusableWindow() ) - { - handleJavaKeyEvent((KeyEvent)e); - } + InvocationEvent ev = new InvocationEvent(target, new Runnable() { + public void run() { + if(target.isFocusable() && + getParentTopLevel().isFocusableWindow() ) + { + handleJavaKeyEvent((KeyEvent)e); } - }); + } + }); + postEvent(ev); + return true; } else { if (e instanceof MouseEvent){ @@ -1083,11 +1085,13 @@ public class XChoicePeer extends XComponentPeer implements ChoicePeer, ToplevelS //convenient method //do not generate this kind of Events public boolean handleMouseEventByChoice(final MouseEvent me){ - EventQueue.invokeLater(new Runnable() { - public void run() { - handleJavaMouseEvent(me); - } - }); + InvocationEvent ev = new InvocationEvent(target, new Runnable() { + public void run() { + handleJavaMouseEvent(me); + } + }); + postEvent(ev); + return true; } diff --git a/src/solaris/classes/sun/awt/X11/XKeyboardFocusManagerPeer.java b/src/solaris/classes/sun/awt/X11/XKeyboardFocusManagerPeer.java index 463a58da8f85a332beafa06bd47bc3a690a9389f..31548f90a811accb8b507b08c27b2028607cf6a5 100644 --- a/src/solaris/classes/sun/awt/X11/XKeyboardFocusManagerPeer.java +++ b/src/solaris/classes/sun/awt/X11/XKeyboardFocusManagerPeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,9 +26,11 @@ package sun.awt.X11; import java.awt.Component; import java.awt.Window; -import sun.util.logging.PlatformLogger; + +import sun.awt.AWTAccessor; import sun.awt.CausedFocusEvent; import sun.awt.KeyboardFocusManagerPeerImpl; +import sun.util.logging.PlatformLogger; public class XKeyboardFocusManagerPeer extends KeyboardFocusManagerPeerImpl { private static final PlatformLogger focusLog = PlatformLogger.getLogger("sun.awt.X11.focus.XKeyboardFocusManagerPeer"); @@ -68,13 +70,13 @@ public class XKeyboardFocusManagerPeer extends KeyboardFocusManagerPeerImpl { synchronized(this) { if (currentFocusedWindow != null) { - from = (XWindowPeer)currentFocusedWindow.getPeer(); + from = (XWindowPeer)AWTAccessor.getComponentAccessor().getPeer(currentFocusedWindow); } currentFocusedWindow = win; if (currentFocusedWindow != null) { - to = (XWindowPeer)currentFocusedWindow.getPeer(); + to = (XWindowPeer)AWTAccessor.getComponentAccessor().getPeer(currentFocusedWindow); } } diff --git a/src/solaris/classes/sun/awt/X11/XListPeer.java b/src/solaris/classes/sun/awt/X11/XListPeer.java index 00c45ad8b7b454f645823d320198cec0b2e88bc2..25cf66d83efc110f86c33852773bf4d1d510f074 100644 --- a/src/solaris/classes/sun/awt/X11/XListPeer.java +++ b/src/solaris/classes/sun/awt/X11/XListPeer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1669,11 +1669,12 @@ class XListPeer extends XComponentPeer implements ListPeer, XScrollbarClient { * Do handleJavaMouseEvent on EDT */ void handleJavaMouseEventOnEDT(final MouseEvent me){ - EventQueue.invokeLater(new Runnable() { - public void run() { - handleJavaMouseEvent(me); - } - }); + InvocationEvent ev = new InvocationEvent(target, new Runnable() { + public void run() { + handleJavaMouseEvent(me); + } + }); + postEvent(ev); } /* diff --git a/src/solaris/classes/sun/print/UnixPrintServiceLookup.java b/src/solaris/classes/sun/print/UnixPrintServiceLookup.java index 9fcbb86c75677daa46d7450bc03426734121ba3e..c682634b7b66579219808601d9425d8ce3570fc1 100644 --- a/src/solaris/classes/sun/print/UnixPrintServiceLookup.java +++ b/src/solaris/classes/sun/print/UnixPrintServiceLookup.java @@ -362,10 +362,33 @@ public class UnixPrintServiceLookup extends PrintServiceLookup */ private PrintService getServiceByName(PrinterName nameAttr) { String name = nameAttr.getValue(); - PrintService printer = null; if (name == null || name.equals("") || !checkPrinterName(name)) { return null; } + /* check is all printers are already available */ + if (printServices != null) { + for (PrintService printService : printServices) { + if (printService.getName().equals(name)) { + return printService; + } + } + } + /* take CUPS into account first */ + if (CUPSPrinter.isCupsRunning()) { + try { + return new IPPPrintService(name, + new URL("http://"+ + CUPSPrinter.getServer()+":"+ + CUPSPrinter.getPort()+"/"+ + name)); + } catch (Exception e) { + IPPPrintService.debug_println(debugPrefix+ + " getServiceByName Exception "+ + e); + } + } + /* fallback if nothing not having a printer at this point */ + PrintService printer = null; if (isMac() || isSysV()) { printer = getNamedPrinterNameSysV(name); } else { diff --git a/src/solaris/native/sun/awt/awt_GraphicsEnv.c b/src/solaris/native/sun/awt/awt_GraphicsEnv.c index 7282d22a94acba5ea23c405d08ab1e1f6cee2eeb..cb0b7274bd9abbbaabf1d6b9c9ccff1af1e91dc8 100644 --- a/src/solaris/native/sun/awt/awt_GraphicsEnv.c +++ b/src/solaris/native/sun/awt/awt_GraphicsEnv.c @@ -1369,12 +1369,18 @@ Java_sun_awt_X11GraphicsConfig_pGetBounds(JNIEnv *env, jobject this, jint screen mid = (*env)->GetMethodID(env, clazz, "", "(IIII)V"); if (mid != NULL) { if (usingXinerama) { - bounds = (*env)->NewObject(env, clazz, mid, fbrects[screen].x, - fbrects[screen].y, - fbrects[screen].width, - fbrects[screen].height); - } - else { + if (0 <= screen && screen < awt_numScreens) { + bounds = (*env)->NewObject(env, clazz, mid, fbrects[screen].x, + fbrects[screen].y, + fbrects[screen].width, + fbrects[screen].height); + } else { + jclass exceptionClass = (*env)->FindClass(env, "java/lang/IllegalArgumentException"); + if (exceptionClass != NULL) { + (*env)->ThrowNew(env, exceptionClass, "Illegal screen index"); + } + } + } else { XWindowAttributes xwa; memset(&xwa, 0, sizeof(xwa)); diff --git a/src/solaris/native/sun/awt/awt_InputMethod.c b/src/solaris/native/sun/awt/awt_InputMethod.c index faa76460213de7c069d0402217151fe0245837a4..dd9fb952da727b74ece948d606b2ffa275bcad9f 100644 --- a/src/solaris/native/sun/awt/awt_InputMethod.c +++ b/src/solaris/native/sun/awt/awt_InputMethod.c @@ -447,7 +447,7 @@ setXICWindowFocus(XIC ic, Window w) */ #define INITIAL_LOOKUP_BUF_SIZE 512 -Bool +Boolean awt_x11inputmethod_lookupString(XKeyPressedEvent *event, KeySym *keysymp) { JNIEnv *env = GetJNIEnv(); @@ -457,8 +457,8 @@ awt_x11inputmethod_lookupString(XKeyPressedEvent *event, KeySym *keysymp) int mblen; jstring javastr; XIC ic; - Bool result = True; - static Bool composing = False; + Boolean result = True; + static Boolean composing = False; /* printf("lookupString: entering...\n"); diff --git a/src/solaris/native/sun/xawt/XToolkit.c b/src/solaris/native/sun/xawt/XToolkit.c index 6dfb80d368a825e658532825f3cf9eff6fc5ef10..9abacadcb355f0236a1891d445675dbaee579c5b 100644 --- a/src/solaris/native/sun/xawt/XToolkit.c +++ b/src/solaris/native/sun/xawt/XToolkit.c @@ -685,8 +685,7 @@ performPoll(JNIEnv *env, jlong nextTaskTime) { if (result == 0) { /* poll() timed out -- update timeout value */ update_poll_timeout(TIMEOUT_TIMEDOUT); - PRINT2("%s(): TIMEOUT_TIMEDOUT curPollTimeout = %d \n", - performPoll, curPollTimeout); + PRINT2("performPoll(): TIMEOUT_TIMEDOUT curPollTimeout = %d \n", curPollTimeout); } if (pollFds[1].revents) { int count; @@ -695,14 +694,12 @@ performPoll(JNIEnv *env, jlong nextTaskTime) { do { count = read(AWT_READPIPE, read_buf, AWT_POLL_BUFSIZE ); } while (count == AWT_POLL_BUFSIZE ); - PRINT2("%s(): data on the AWT pipe: curPollTimeout = %d \n", - performPoll, curPollTimeout); + PRINT2("performPoll(): data on the AWT pipe: curPollTimeout = %d \n", curPollTimeout); } if (pollFds[0].revents) { // Events in X pipe update_poll_timeout(TIMEOUT_EVENTS); - PRINT2("%s(): TIMEOUT_EVENTS curPollTimeout = %ld \n", - performPoll, curPollTimeout); + PRINT2("performPoll(): TIMEOUT_EVENTS curPollTimeout = %ld \n", curPollTimeout); } return; diff --git a/src/windows/classes/sun/awt/windows/WPrinterJob.java b/src/windows/classes/sun/awt/windows/WPrinterJob.java index 250d8c722034ec872a36ce61d5a6a290497aedcd..897e8f1baf1eaf2278811e0d112cd1ca46349b71 100644 --- a/src/windows/classes/sun/awt/windows/WPrinterJob.java +++ b/src/windows/classes/sun/awt/windows/WPrinterJob.java @@ -1269,11 +1269,13 @@ public class WPrinterJob extends RasterPrinterJob implements DisposerTarget { mLastFontFamily = null; } + private boolean defaultCopies = true; /** * Set the number of copies to be printed. */ public void setCopies(int copies) { super.setCopies(copies); + defaultCopies = false; mAttCopies = copies; setNativeCopies(copies); } @@ -1529,8 +1531,9 @@ public class WPrinterJob extends RasterPrinterJob implements DisposerTarget { } /* SheetCollate */ - private final boolean getCollateAttrib() { - return (mAttCollate == 1); + private final int getCollateAttrib() { + // -1 means unset, 0 uncollated, 1 collated. + return mAttCollate; } private void setCollateAttrib(Attribute attr) { @@ -1553,6 +1556,10 @@ public class WPrinterJob extends RasterPrinterJob implements DisposerTarget { int orient = PageFormat.PORTRAIT; OrientationRequested orientReq = (attributes == null) ? null : (OrientationRequested)attributes.get(OrientationRequested.class); + if (orientReq == null) { + orientReq = (OrientationRequested) + myService.getDefaultAttributeValue(OrientationRequested.class); + } if (orientReq != null) { if (orientReq == OrientationRequested.REVERSE_LANDSCAPE) { orient = PageFormat.REVERSE_LANDSCAPE; @@ -1573,7 +1580,11 @@ public class WPrinterJob extends RasterPrinterJob implements DisposerTarget { /* Copies and Page Range. */ private final int getCopiesAttrib() { - return getCopiesInt(); + if (defaultCopies) { + return 0; + } else { + return getCopiesInt(); + } } private final void setRangeCopiesAttribute(int from, int to, @@ -1584,6 +1595,7 @@ public class WPrinterJob extends RasterPrinterJob implements DisposerTarget { attributes.add(new PageRanges(from, to)); setPageRange(from, to); } + defaultCopies = false; attributes.add(new Copies(copies)); /* Since this is called from native to tell Java to sync * up with native, we don't call this class's own setCopies() diff --git a/src/windows/classes/sun/print/Win32PrintService.java b/src/windows/classes/sun/print/Win32PrintService.java index bef2213e66492870ee6991e0d483679fbb0a4e60..829eaaa313143840178cdf0ef09452d3aea5c98c 100644 --- a/src/windows/classes/sun/print/Win32PrintService.java +++ b/src/windows/classes/sun/print/Win32PrintService.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,11 +28,8 @@ package sun.print; import java.io.File; import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; - -import java.util.Vector; +import java.util.ArrayList; import java.util.HashMap; - import javax.print.DocFlavor; import javax.print.DocPrintJob; import javax.print.PrintService; @@ -69,22 +66,14 @@ import javax.print.attribute.standard.Severity; import javax.print.attribute.standard.Sides; import javax.print.attribute.standard.ColorSupported; import javax.print.attribute.standard.PrintQuality; -import javax.print.attribute.ResolutionSyntax; import javax.print.attribute.standard.PrinterResolution; import javax.print.attribute.standard.SheetCollate; import javax.print.event.PrintServiceAttributeListener; -import java.util.ArrayList; - -import sun.print.SunPrinterJobService; public class Win32PrintService implements PrintService, AttributeUpdater, SunPrinterJobService { - public static MediaSize[] predefMedia; - - static { - Class c = Win32MediaSize.class; - } + public static MediaSize[] predefMedia = Win32MediaSize.getPredefMedia(); private static final DocFlavor[] supportedFlavors = { DocFlavor.BYTE_ARRAY.GIF, @@ -180,6 +169,9 @@ public class Win32PrintService implements PrintService, AttributeUpdater, private static final int DMDUP_VERTICAL = 2; private static final int DMDUP_HORIZONTAL = 3; private static final int DMCOLLATE_TRUE = 1; + private static final int DMCOLOR_MONOCHROME = 1; + private static final int DMCOLOR_COLOR = 2; + // media sizes with indices above dmPaperToPrintService' length private static final int DMPAPER_A2 = 66; @@ -310,7 +302,9 @@ public class Win32PrintService implements PrintService, AttributeUpdater, public MediaSizeName findWin32Media(int dmIndex) { if (dmIndex >= 1 && dmIndex <= dmPaperToPrintService.length) { - switch(dmIndex) { + return dmPaperToPrintService[dmIndex - 1]; + } + switch(dmIndex) { /* matching media sizes with indices beyond dmPaperToPrintService's length */ case DMPAPER_A2: @@ -320,11 +314,8 @@ public class Win32PrintService implements PrintService, AttributeUpdater, case DMPAPER_B6_JIS: return MediaSizeName.JIS_B6; default: - return dmPaperToPrintService[dmIndex - 1]; - } + return null; } - - return null; } private boolean addToUniqueList(ArrayList msnList, MediaSizeName mediaName) { @@ -350,6 +341,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, } ArrayList msnList = new ArrayList(); + ArrayList trailingWmsList = new ArrayList(); ArrayList printableList = new ArrayList(); MediaSizeName mediaName; boolean added; @@ -368,7 +360,8 @@ public class Win32PrintService implements PrintService, AttributeUpdater, idList.add(Integer.valueOf(media[i])); } - mediaSizes = getMediaSizes(idList, media); + ArrayList dmPaperNameList = new ArrayList(); + mediaSizes = getMediaSizes(idList, media, dmPaperNameList); for (int i = 0; i < idList.size(); i++) { // match Win ID with our predefined ID using table @@ -387,6 +380,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, mediaName = null; } } + boolean dmPaperIDMatched = (mediaName != null); // No match found, then we get the MediaSizeName out of the MediaSize // This requires 1-1 correspondence, lengths must be checked. @@ -395,9 +389,32 @@ public class Win32PrintService implements PrintService, AttributeUpdater, } // Add mediaName to the msnList + added = false; if (mediaName != null) { added = addToUniqueList(msnList, mediaName); } + if ((!dmPaperIDMatched || !added) && (idList.size() == dmPaperNameList.size())) { + /* The following block allows to add such media names to the list, whose sizes + * matched with media sizes predefined in JDK, while whose paper IDs did not, + * or whose sizes and paper IDs both did not match with any predefined in JDK. + */ + Win32MediaSize wms = Win32MediaSize.findMediaName(dmPaperNameList.get(i)); + if ((wms == null) && (idList.size() == mediaSizes.length)) { + wms = new Win32MediaSize(dmPaperNameList.get(i), (Integer)idList.get(i)); + mediaSizes[i] = new MediaSize(mediaSizes[i].getX(MediaSize.MM), + mediaSizes[i].getY(MediaSize.MM), MediaSize.MM, wms); + } + if ((wms != null) && (wms != mediaName)) { + if (!added) { + added = addToUniqueList(msnList, mediaName = wms); + } else { + trailingWmsList.add(wms); + } + } + } + } + for (Win32MediaSize wms : trailingWmsList) { + added = addToUniqueList(msnList, wms); } // init mediaSizeNames @@ -588,7 +605,11 @@ public class Win32PrintService implements PrintService, AttributeUpdater, } - private MediaSize[] getMediaSizes(ArrayList idList, int[] media) { + private MediaSize[] getMediaSizes(ArrayList idList, int[] media, ArrayList dmPaperNameList) { + if (dmPaperNameList == null) { + dmPaperNameList = new ArrayList(); + } + String prnPort = getPort(); int[] mediaSz = getAllMediaSizes(printer, prnPort); String[] winMediaNames = getAllMediaNames(printer, prnPort); @@ -607,40 +628,43 @@ public class Win32PrintService implements PrintService, AttributeUpdater, wid = mediaSz[i*2]/10f; ht = mediaSz[i*2+1]/10f; - // Make sure to validate wid & ht. - // HP LJ 4050 (german) causes IAE in Sonderformat paper, wid & ht - // returned is not constant. - if ((wid <= 0) || (ht <= 0)) { - //Remove corresponding ID from list - if (nMedia == media.length) { - Integer remObj = Integer.valueOf(media[i]); - idList.remove(idList.indexOf(remObj)); + // Make sure to validate wid & ht. + // HP LJ 4050 (german) causes IAE in Sonderformat paper, wid & ht + // returned is not constant. + if ((wid <= 0) || (ht <= 0)) { + //Remove corresponding ID from list + if (nMedia == media.length) { + Integer remObj = Integer.valueOf(media[i]); + idList.remove(idList.indexOf(remObj)); + } + continue; } - continue; - } - // Find matching media using dimensions. - // This call matches only with our own predefined sizes. - msn = findMatchingMediaSizeNameMM(wid, ht); - if (msn != null) { - ms = MediaSize.getMediaSizeForName(msn); - } - - if (ms != null) { - msList.add(ms); - } else { - Win32MediaSize wms = - new Win32MediaSize(winMediaNames[i], media[i]); - try { - ms = new MediaSize(wid, ht, MediaSize.MM, wms); - msList.add(ms); - } catch(IllegalArgumentException e) { - if (nMedia == media.length) { - Integer remObj = Integer.valueOf(media[i]); - idList.remove(idList.indexOf(remObj)); - } + // Find matching media using dimensions. + // This call matches only with our own predefined sizes. + msn = findMatchingMediaSizeNameMM(wid, ht); + if (msn != null) { + ms = MediaSize.getMediaSizeForName(msn); } - } + if (ms != null) { + msList.add(ms); + dmPaperNameList.add(winMediaNames[i]); + } else { + Win32MediaSize wms = Win32MediaSize.findMediaName(winMediaNames[i]); + if (wms == null) { + wms = new Win32MediaSize(winMediaNames[i], media[i]); + } + try { + ms = new MediaSize(wid, ht, MediaSize.MM, wms); + msList.add(ms); + dmPaperNameList.add(winMediaNames[i]); + } catch(IllegalArgumentException e) { + if (nMedia == media.length) { + Integer remObj = Integer.valueOf(media[i]); + idList.remove(idList.indexOf(remObj)); + } + } + } } MediaSize[] arr2 = new MediaSize[msList.size()]; @@ -1041,6 +1065,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, int defOrient = defaults[5]; int defSides = defaults[6]; int defCollate = defaults[7]; + int defColor = defaults[8]; if (category == Copies.class) { if (defCopies > 0) { @@ -1049,11 +1074,10 @@ public class Win32PrintService implements PrintService, AttributeUpdater, return new Copies(1); } } else if (category == Chromaticity.class) { - int caps = getPrinterCapabilities(); - if ((caps & DEVCAP_COLOR) == 0) { - return Chromaticity.MONOCHROME; - } else { + if (defColor == DMCOLOR_COLOR) { return Chromaticity.COLOR; + } else { + return Chromaticity.MONOCHROME; } } else if (category == JobName.class) { return new JobName("Java Printing", null); @@ -1614,6 +1638,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, class Win32MediaSize extends MediaSizeName { private static ArrayList winStringTable = new ArrayList(); private static ArrayList winEnumTable = new ArrayList(); + private static MediaSize[] predefMedia; private int dmPaperID; // driver ID for this paper. @@ -1627,6 +1652,18 @@ class Win32MediaSize extends MediaSizeName { return (winStringTable.size()-1); } + public static synchronized Win32MediaSize findMediaName(String name) { + int nameIndex = winStringTable.indexOf(name); + if (nameIndex != -1) { + return (Win32MediaSize)winEnumTable.get(nameIndex); + } + return null; + } + + public static MediaSize[] getPredefMedia() { + return predefMedia; + } + public Win32MediaSize(String name, int dmPaper) { super(nextValue(name)); dmPaperID = dmPaper; @@ -1638,18 +1675,17 @@ class Win32MediaSize extends MediaSizeName { } static { - /* initialize Win32PrintService.predefMedia */ + /* initialize predefMedia */ { Win32MediaSize winMedia = new Win32MediaSize(-1); // cannot call getSuperEnumTable directly because of static context MediaSizeName[] enumMedia = winMedia.getSuperEnumTable(); if (enumMedia != null) { - Win32PrintService.predefMedia = new MediaSize[enumMedia.length]; + predefMedia = new MediaSize[enumMedia.length]; for (int i=0; idmCollate; } + if (pDevMode->dmFields & DM_COLOR) { + defIndices[8] = pDevMode->dmColor; + } + + GlobalFree(pDevMode); ::ClosePrinter(hPrinter); diff --git a/src/windows/native/sun/windows/awt_Frame.cpp b/src/windows/native/sun/windows/awt_Frame.cpp index 5d344e71474fe01e8082fa4dc85841552f3ab72e..1195491069fa546f0d947c9afce2b120f34e1a68 100644 --- a/src/windows/native/sun/windows/awt_Frame.cpp +++ b/src/windows/native/sun/windows/awt_Frame.cpp @@ -380,9 +380,11 @@ LRESULT AwtFrame::ProxyWindowProc(UINT message, WPARAM wParam, LPARAM lParam, Ms if (!sm_suppressFocusAndActivation) { if (IsLightweightFrame() || IsEmbeddedFrame()) { - AwtWindow::SynthesizeWmActivate(FALSE, GetHWnd(), NULL); + HWND oppositeToplevelHWnd = AwtComponent::GetTopLevelParentForWindow((HWND)wParam); + if (oppositeToplevelHWnd != AwtComponent::GetFocusedWindow()) { + AwtWindow::SynthesizeWmActivate(FALSE, GetHWnd(), NULL); + } } - } else if (sm_restoreFocusAndActivation) { if (AwtComponent::GetFocusedWindow() != NULL) { AwtWindow *focusedWindow = (AwtWindow*)GetComponent(AwtComponent::GetFocusedWindow()); diff --git a/src/windows/native/sun/windows/awt_PrintControl.cpp b/src/windows/native/sun/windows/awt_PrintControl.cpp index 400583599900f4cbb5375d9aa5c15ded19c72641..71a08d3df330f05f14823e0fd3e6222514a07341 100644 --- a/src/windows/native/sun/windows/awt_PrintControl.cpp +++ b/src/windows/native/sun/windows/awt_PrintControl.cpp @@ -252,7 +252,7 @@ void AwtPrintControl::initIDs(JNIEnv *env, jclass cls) AwtPrintControl::getCopiesID = env->GetMethodID(cls, "getCopiesAttrib", "()I"); AwtPrintControl::getCollateID = - env->GetMethodID(cls, "getCollateAttrib","()Z"); + env->GetMethodID(cls, "getCollateAttrib","()I"); AwtPrintControl::getOrientID = env->GetMethodID(cls, "getOrientAttrib", "()I"); AwtPrintControl::getFromPageID = @@ -690,12 +690,6 @@ BOOL AwtPrintControl::InitPrintDialog(JNIEnv *env, pd.Flags = PD_ENABLEPRINTHOOK | PD_RETURNDC | PD_USEDEVMODECOPIESANDCOLLATE; pd.lpfnPrintHook = (LPPRINTHOOKPROC)PrintDlgHook; - if (env->CallBooleanMethod(printCtrl, AwtPrintControl::getCollateID)) { - pd.Flags |= PD_COLLATE; - } - - pd.nCopies = (WORD)env->CallIntMethod(printCtrl, - AwtPrintControl::getCopiesID); pd.nFromPage = (WORD)env->CallIntMethod(printCtrl, AwtPrintControl::getFromPageID); pd.nToPage = (WORD)env->CallIntMethod(printCtrl, @@ -729,37 +723,52 @@ BOOL AwtPrintControl::InitPrintDialog(JNIEnv *env, DEVMODE *devmode = (DEVMODE *)::GlobalLock(pd.hDevMode); DASSERT(!IsBadWritePtr(devmode, sizeof(DEVMODE))); - devmode->dmFields |= DM_COPIES | DM_COLLATE | DM_ORIENTATION | - DM_PAPERSIZE | DM_PRINTQUALITY | DM_COLOR | DM_DUPLEX; - - devmode->dmCopies = pd.nCopies; + WORD copies = (WORD)env->CallIntMethod(printCtrl, + AwtPrintControl::getCopiesID); + if (copies > 0) { + devmode->dmFields |= DM_COPIES; + devmode->dmCopies = copies; + } jint orient = env->CallIntMethod(printCtrl, AwtPrintControl::getOrientID); - if (orient == 0) { + if (orient == 0) { // PageFormat.LANDSCAPE == 0 + devmode->dmFields |= DM_ORIENTATION; devmode->dmOrientation = DMORIENT_LANDSCAPE; - } else if (orient == 1) { + } else if (orient == 1) { // PageFormat.PORTRAIT == 1 + devmode->dmFields |= DM_ORIENTATION; devmode->dmOrientation = DMORIENT_PORTRAIT; } - devmode->dmCollate = (pd.Flags & PD_COLLATE) ? DMCOLLATE_TRUE - : DMCOLLATE_FALSE; + // -1 means unset, so we'll accept the printer default. + int collate = env->CallIntMethod(printCtrl, + AwtPrintControl::getCollateID); + if (collate == 1) { + devmode->dmFields |= DM_COLLATE; + devmode->dmCollate = DMCOLLATE_TRUE; + } else if (collate == 0) { + devmode->dmFields |= DM_COLLATE; + devmode->dmCollate = DMCOLLATE_FALSE; + } int quality = env->CallIntMethod(printCtrl, AwtPrintControl::getQualityID); if (quality) { + devmode->dmFields |= DM_PRINTQUALITY; devmode->dmPrintQuality = quality; } int color = env->CallIntMethod(printCtrl, AwtPrintControl::getColorID); if (color) { + devmode->dmFields |= DM_COLOR; devmode->dmColor = color; } int sides = env->CallIntMethod(printCtrl, AwtPrintControl::getSidesID); if (sides) { + devmode->dmFields |= DM_DUPLEX; devmode->dmDuplex = (int)sides; } @@ -771,6 +780,7 @@ BOOL AwtPrintControl::InitPrintDialog(JNIEnv *env, double newWid = 0.0, newHt = 0.0; if (wid_ht != NULL && wid_ht[0] != 0 && wid_ht[1] != 0) { + devmode->dmFields |= DM_PAPERSIZE; devmode->dmPaperSize = AwtPrintControl::getNearestMatchingPaper( printName, portName, diff --git a/test/ProblemList.txt b/test/ProblemList.txt index 8c98dbda37afd1aa6984829b37488afef7061b29..8a6931cf1102d0e17ae54a9e77f1f866590b9c61 100644 --- a/test/ProblemList.txt +++ b/test/ProblemList.txt @@ -137,6 +137,10 @@ java/lang/Class/asSubclass/BasicUnit.java generic-all # 8015780 java/lang/reflect/Method/GenericStringTest.java generic-all +# 8019500 +java/lang/management/MemoryMXBean/MemoryTestAllGC.sh generic-all +java/lang/management/MemoryMXBean/MemoryTest.java generic-all + ############################################################################ # jdk_management diff --git a/test/TEST.ROOT b/test/TEST.ROOT index 1645f6b26da995616e75a03dba9bd8b89b567a68..6bf72964f6619f6c5f71f701ef74b3ead4d3f7b8 100644 --- a/test/TEST.ROOT +++ b/test/TEST.ROOT @@ -1,6 +1,5 @@ # This file identifies the root of the test-suite hierarchy. # It also contains test-suite configuration information. -# DO NOT EDIT without first contacting jdk-regtest@sun.com. # The list of keywords supported in the entire test suite keys=2d dnd i18n @@ -9,4 +8,4 @@ keys=2d dnd i18n othervm.dirs=java/awt java/beans java/rmi javax/accessibility javax/imageio javax/sound javax/print javax/management com/sun/awt sun/awt sun/java2d sun/pisces sun/rmi # Tests that cannot run concurrently -exclusiveAccess.dirs=java/rmi/Naming java/util/prefs sun/management/jmxremote sun/tools/jstatd sun/security/mscapi +exclusiveAccess.dirs=java/rmi/Naming java/util/Currency java/util/prefs sun/management/jmxremote sun/tools/jstatd sun/security/mscapi diff --git a/test/com/sun/java/swing/plaf/gtk/4928019/bug4928019.java b/test/com/sun/java/swing/plaf/gtk/4928019/bug4928019.java new file mode 100644 index 0000000000000000000000000000000000000000..60761c00ea78f9ced3e60b4638d211a9bbd2d3d7 --- /dev/null +++ b/test/com/sun/java/swing/plaf/gtk/4928019/bug4928019.java @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4928019 + * @summary Makes sure all the basic classes can be created with GTK. + * @author Scott Violet + */ + +import javax.swing.*; +import javax.swing.plaf.basic.*; + +public class bug4928019 { + public static void main(String[] args) throws Throwable { + try { + UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); + } catch (UnsupportedLookAndFeelException ex) { + System.err.println("GTKLookAndFeel is not supported on this platform." + + " Test is considered passed."); + return; + } catch (ClassNotFoundException ex) { + System.err.println("GTKLookAndFeel class is not found." + + " Test is considered passed."); + return; + } + new JButton() { + public void updateUI() { + setUI(new BasicButtonUI()); + } + }; + new JCheckBox() { + public void updateUI() { + setUI(new BasicCheckBoxUI()); + } + }; + new JCheckBoxMenuItem() { + public void updateUI() { + setUI(new BasicCheckBoxMenuItemUI()); + } + }; + new JColorChooser() { + public void updateUI() { + setUI(new BasicColorChooserUI()); + } + }; + new JComboBox() { + public void updateUI() { + setUI(new BasicComboBoxUI()); + } + }; + new JDesktopPane() { + public void updateUI() { + setUI(new BasicDesktopPaneUI()); + } + }; + new JEditorPane() { + public void updateUI() { + setUI(new BasicEditorPaneUI()); + } + }; + new JFileChooser() { + public void updateUI() { + setUI(new BasicFileChooserUI(null)); + } + }; + new JFormattedTextField() { + public void updateUI() { + setUI(new BasicFormattedTextFieldUI()); + } + }; + new JInternalFrame() { + public void updateUI() { + setUI(new BasicInternalFrameUI(null)); + } + }; + new JLabel() { + public void updateUI() { + setUI(new BasicLabelUI()); + } + }; + new JList() { + public void updateUI() { + setUI(new BasicListUI()); + } + }; + new JMenuBar() { + public void updateUI() { + setUI(new BasicMenuBarUI()); + } + }; + new JMenuItem() { + public void updateUI() { + setUI(new BasicMenuItemUI()); + } + }; + new JMenu() { + public void updateUI() { + setUI(new BasicMenuUI()); + } + }; + new JOptionPane() { + public void updateUI() { + setUI(new BasicOptionPaneUI()); + } + }; + new JPanel() { + public void updateUI() { + setUI(new BasicPanelUI()); + } + }; + new JPasswordField() { + public void updateUI() { + setUI(new BasicPasswordFieldUI()); + } + }; + new JPopupMenu() { + public void updateUI() { + setUI(new BasicPopupMenuUI()); + } + }; + new JProgressBar() { + public void updateUI() { + setUI(new BasicProgressBarUI()); + } + }; + new JRadioButton() { + public void updateUI() { + setUI(new BasicRadioButtonUI()); + } + }; + new JRadioButtonMenuItem() { + public void updateUI() { + setUI(new BasicRadioButtonMenuItemUI()); + } + }; + new JRootPane() { + public void updateUI() { + setUI(new BasicRootPaneUI()); + } + }; + new JScrollBar() { + public void updateUI() { + setUI(new BasicScrollBarUI()); + } + }; + new JScrollPane() { + public void updateUI() { + setUI(new BasicScrollPaneUI()); + } + }; + new JSeparator() { + public void updateUI() { + setUI(new BasicSeparatorUI()); + } + }; + new JSlider() { + public void updateUI() { + setUI(new BasicSliderUI(null)); + } + }; + new JSpinner() { + public void updateUI() { + setUI(new BasicSpinnerUI()); + } + }; + new JSplitPane() { + public void updateUI() { + setUI(new BasicSplitPaneUI()); + } + }; + new JTabbedPane() { + public void updateUI() { + setUI(new BasicTabbedPaneUI()); + } + }; + new JTable() { + public void updateUI() { + setUI(new BasicTableUI()); + } + }; + new JTextArea() { + public void updateUI() { + setUI(new BasicTextAreaUI()); + } + }; + new JTextField() { + public void updateUI() { + setUI(new BasicTextFieldUI()); + } + }; + new JTextPane() { + public void updateUI() { + setUI(new BasicTextPaneUI()); + } + }; + new JToggleButton() { + public void updateUI() { + setUI(new BasicToggleButtonUI()); + } + }; + new JToolBar() { + public void updateUI() { + setUI(new BasicToolBarUI()); + } + }; + new JToolTip() { + public void updateUI() { + setUI(new BasicToolTipUI()); + } + }; + new JTree() { + public void updateUI() { + setUI(new BasicTreeUI()); + } + }; + new JViewport() { + public void updateUI() { + setUI(new BasicViewportUI()); + } + }; + System.out.println("DONE"); + } +} diff --git a/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.html b/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.html index 03f470d2dec7120cd01544dac3ac428b6f1020b5..21396353d7c50f5aed05899163c76d4ada6959f2 100644 --- a/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.html +++ b/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.html @@ -1,6 +1,5 @@ + Java 7 on mac os x only provides text clipboard formats diff --git a/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.java b/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.java index 765457e7ddd6a823cc40d1cd371a934109adc2f0..598426f61f0bfdc853230a643da47cee4a378baf 100644 --- a/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.java +++ b/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.java @@ -22,7 +22,6 @@ */ /* - @test @bug 8005932 @summary Java 7 on mac os x only provides text clipboard formats @author mikhail.cherkasov@oracle.com @@ -30,10 +29,9 @@ @library ../../regtesthelpers/process @build Util @build ProcessResults ProcessCommunicator - - @run applet/othervm MissedHtmlAndRtfBug.html */ + import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.event.*; diff --git a/test/java/awt/Focus/TypeAhead/TestFocusFreeze.java b/test/java/awt/Focus/TypeAhead/TestFocusFreeze.java index a22551bec2c77ef3ca9fb991597f8e78fcf4953c..2edcf9db98aaa0422609704b8e722f148c66eb8b 100644 --- a/test/java/awt/Focus/TypeAhead/TestFocusFreeze.java +++ b/test/java/awt/Focus/TypeAhead/TestFocusFreeze.java @@ -132,6 +132,7 @@ class TestKFM extends DefaultKeyboardFocusManager { } protected synchronized void enqueueKeyEvents(long after, Component untilFocused) { super.enqueueKeyEvents(after, untilFocused); + robot.delay(1); robot.keyPress(KeyEvent.VK_SPACE); robot.delay(50); robot.keyRelease(KeyEvent.VK_SPACE); diff --git a/test/java/awt/GraphicsDevice/CheckDisplayModes.java b/test/java/awt/GraphicsDevice/CheckDisplayModes.java index bc8d8a50be6597d4219024a18776931b4df5dba2..719ee9b43a7d785aed465cdba7f7976b99942ea5 100644 --- a/test/java/awt/GraphicsDevice/CheckDisplayModes.java +++ b/test/java/awt/GraphicsDevice/CheckDisplayModes.java @@ -37,6 +37,10 @@ public class CheckDisplayModes { public static void main(String[] args) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice graphicDevice = ge.getDefaultScreenDevice(); + if (!graphicDevice.isDisplayChangeSupported()) { + System.err.println("Display mode change is not supported on this host. Test is considered passed."); + return; + } DisplayMode defaultDisplayMode = graphicDevice.getDisplayMode(); checkDisplayMode(defaultDisplayMode); graphicDevice.setDisplayMode(defaultDisplayMode); diff --git a/test/java/awt/Mixing/MixingInHwPanel.java b/test/java/awt/Mixing/MixingInHwPanel.java index 7aceebd0b38de5f350c850a6c857d4f9665ad8ef..27b2d96715ea29417949397af7b1514351e1cd6d 100644 --- a/test/java/awt/Mixing/MixingInHwPanel.java +++ b/test/java/awt/Mixing/MixingInHwPanel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,7 +22,7 @@ */ /* - @test %W% %E% + @test @bug 6829858 @summary Mixing should work inside heavyweight containers @author anthony.petrov@sun.com: area=awt.mixing @@ -104,7 +104,7 @@ public class MixingInHwPanel // And click the part of the button that has been previously hidden Point bLoc = button.getLocationOnScreen(); - robot.mouseMove(bLoc.x + button.getWidth() - 6, bLoc.y + button.getHeight() / 2); + robot.mouseMove(bLoc.x + button.getWidth() - 15, bLoc.y + button.getHeight() / 2); Util.waitForIdle(robot); diff --git a/test/java/awt/Mouse/EnterExitEvents/FullscreenEnterEventTest.java b/test/java/awt/Mouse/EnterExitEvents/FullscreenEnterEventTest.java new file mode 100644 index 0000000000000000000000000000000000000000..a018b27e3f5a6452ab00b0a5997b5904b102a5f3 --- /dev/null +++ b/test/java/awt/Mouse/EnterExitEvents/FullscreenEnterEventTest.java @@ -0,0 +1,166 @@ +/* +* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. +* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +* +* This code is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License version 2 only, as +* published by the Free Software Foundation. +* +* This code is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +* version 2 for more details (a copy is included in the LICENSE file that +* accompanied this code). +* +* You should have received a copy of the GNU General Public License version +* 2 along with this work; if not, write to the Free Software Foundation, +* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +* +* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +* or visit www.oracle.com if you need additional information or have any +* questions. +*/ + +import sun.misc.OSEnvironment; +import test.java.awt.regtesthelpers.Util; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.InputEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +/* + * @test + * @bug 8013468 + * @summary Cursor does not update properly when in fullscreen mode on Mac + * The core reason of the issue was the lack of a mouse entered event in fullscreen + * @library ../../regtesthelpers + * @build Util + * @author Petr Pchelko area=awt.event + * @run main FullscreenEnterEventTest + */ +public class FullscreenEnterEventTest { + + private static String OS = System.getProperty("os.name").toLowerCase(); + + private static JFrame frame; + + private static volatile int mouseEnterCount = 0; + + private static volatile boolean windowEnteringFullScreen = false; + private static volatile boolean windowEnteredFullScreen = false; + + public static void main(String[] args) throws Exception { + + if (!OS.contains("mac")) { + System.out.println("The test is applicable only to Mac OS X. Passed"); + return; + } + + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + createAndShowGUI(); + } + }); + + //Move the mouse away from the frame and check the View-base full screen mode + Robot r = Util.createRobot(); + Util.waitForIdle(r); + r.mouseMove(500, 500); + Util.waitForIdle(r); + mouseEnterCount = 0; + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(frame); + } + }); + Util.waitForIdle(r); + if (mouseEnterCount != 1) { + throw new RuntimeException("No MouseEntered event for view-base full screen. Failed."); + } + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(null); + } + }); + + //Test native full screen support + Point fullScreenButtonPos = frame.getLocation(); + fullScreenButtonPos.translate(frame.getWidth() - 10, 10); + r.mouseMove(fullScreenButtonPos.x, fullScreenButtonPos.y); + mouseEnterCount = 0; + + //Cant use waitForIdle for full screen transition. + int waitCount = 0; + while (!windowEnteringFullScreen) { + r.mousePress(InputEvent.BUTTON1_MASK); + r.mouseRelease(InputEvent.BUTTON1_MASK); + Thread.sleep(100); + if (waitCount++ > 10) throw new RuntimeException("Can't enter full screen mode. Failed"); + } + + waitCount = 0; + while (!windowEnteredFullScreen) { + Thread.sleep(200); + if (waitCount++ > 10) throw new RuntimeException("Can't enter full screen mode. Failed"); + } + + if (mouseEnterCount != 1) { + throw new RuntimeException("No MouseEntered event for native full screen. Failed."); + } + } + + private static void createAndShowGUI() { + frame = new JFrame(" Fullscreen OSX Bug "); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + enableFullScreen(frame); + frame.addMouseListener(new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent e) { + mouseEnterCount++; + } + }); + frame.setBounds(100, 100, 100, 100); + frame.pack(); + frame.setVisible(true); + + } + + /* + * Use reflection to make a test compilable on not Mac OS X + */ + private static void enableFullScreen(Window window) { + try { + Class fullScreenUtilities = Class.forName("com.apple.eawt.FullScreenUtilities"); + Method setWindowCanFullScreen = fullScreenUtilities.getMethod("setWindowCanFullScreen", Window.class, boolean.class); + setWindowCanFullScreen.invoke(fullScreenUtilities, window, true); + Class fullScreenListener = Class.forName("com.apple.eawt.FullScreenListener"); + Object listenerObject = Proxy.newProxyInstance(fullScreenListener.getClassLoader(), new Class[]{fullScreenListener}, new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + switch (method.getName()) { + case "windowEnteringFullScreen": + windowEnteringFullScreen = true; + break; + case "windowEnteredFullScreen": + windowEnteredFullScreen = true; + break; + } + return null; + } + }); + Method addFullScreenListener = fullScreenUtilities.getMethod("addFullScreenListenerTo", Window.class, fullScreenListener); + addFullScreenListener.invoke(fullScreenUtilities, window, listenerObject); + } catch (Exception e) { + throw new RuntimeException("FullScreen utilities not available", e); + } + } + +} diff --git a/test/java/awt/event/KeyEvent/KeyReleasedInAppletTest/KeyReleasedInAppletTest.java b/test/java/awt/event/KeyEvent/KeyReleasedInAppletTest/KeyReleasedInAppletTest.java index 71e8994e347bc0c5833fb224cc13ac0b677a43b5..34bcbb531bf891bdf72722a343738a2193cd710a 100644 --- a/test/java/awt/event/KeyEvent/KeyReleasedInAppletTest/KeyReleasedInAppletTest.java +++ b/test/java/awt/event/KeyEvent/KeyReleasedInAppletTest/KeyReleasedInAppletTest.java @@ -39,7 +39,6 @@ import java.lang.Throwable; import java.util.Hashtable; /* -@test @bug 8010009 @summary [macosx] Unable type into online word games on MacOSX @author petr.pchelko : area=awt.keyboard diff --git a/test/java/awt/font/TextLayout/KerningLeak.java b/test/java/awt/font/TextLayout/KerningLeak.java new file mode 100644 index 0000000000000000000000000000000000000000..fb8448c3a4eb648669a196f9d70a1e330c5cde25 --- /dev/null +++ b/test/java/awt/font/TextLayout/KerningLeak.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @bug 8015334 + * @summary Memory leak with kerning. + */ + +import java.awt.EventQueue; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.font.TextAttribute; +import java.util.HashMap; +import java.util.Map; +import javax.swing.JLabel; +import javax.swing.SwingUtilities; + +public class KerningLeak { + + public static void main(String[] args) { + EventQueue.invokeLater(new Runnable() { + @Override + public void run() { + leak(); + } + }); + } + + private static void leak() { + Map textAttributes = new HashMap<>(); + textAttributes.put(TextAttribute.FAMILY, "Sans Serif"); + textAttributes.put(TextAttribute.SIZE, 12); + textAttributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON); + Font font = Font.getFont(textAttributes); + JLabel label = new JLabel(); + int dummy = 0; + for (int i = 0; i < 500; i++) { + if (i % 10 == 0) System.out.println("Starting iter " + (i+1)); + for (int j = 0; j <1000; j++) { + FontMetrics fm = label.getFontMetrics(font); + dummy += SwingUtilities.computeStringWidth(fm, Integer.toString(j)); + } + } + System.out.println("done " + dummy); + } +} diff --git a/test/java/beans/XMLEncoder/Test8016545.java b/test/java/beans/XMLEncoder/Test8016545.java new file mode 100644 index 0000000000000000000000000000000000000000..466d8eb01fa03f7558e01d8ca93e57c6427defd2 --- /dev/null +++ b/test/java/beans/XMLEncoder/Test8016545.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8016545 + * @summary Tests beans with predefined fields + * @author Sergey Malenkov + */ + +public class Test8016545 extends AbstractTest { + public static void main(String[] args) { + new Test8016545().test(true); + } + + @Override + protected Object getObject() { + Bean bean = new Bean(); + bean.setUndefined(Boolean.FALSE); + Info info = new Info(); + info.setEnabled(Boolean.TRUE); + info.setID(1); + bean.setInfo(info); + return bean; + } + + @Override + protected Object getAnotherObject() { + Bean bean = new Bean(); + bean.setUndefined(Boolean.TRUE); + bean.getInfo().setEnabled(Boolean.FALSE); + bean.getInfo().setID(2); + return bean; + } + + public static class Bean { + private Info info = new Info(); // predefined + private Boolean defined = Boolean.TRUE; + private Boolean undefined; + + public Info getInfo() { + return this.info; + } + + public void setInfo(Info info) { + this.info = info; + } + + public Boolean getDefined() { + return this.defined; + } + + public void setDefined(Boolean defined) { + this.defined = defined; + } + + public Boolean getUndefined() { + return this.undefined; + } + + public void setUndefined(Boolean undefined) { + this.undefined = undefined; + } + } + + public static class Info { + private Integer id; + private Boolean enabled; + + public Integer getID() { + return this.id; + } + + public void setID(Integer id) { + this.id = id; + } + + public Boolean getEnabled() { + return this.enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + } +} diff --git a/test/java/lang/ThreadGroup/Suspend.java b/test/java/lang/ThreadGroup/Suspend.java index b66d835da1536c455d2f453dd4ccd30692c55a4e..e527d26b39f429b89d6d6cd2719b3707ff0a6438 100644 --- a/test/java/lang/ThreadGroup/Suspend.java +++ b/test/java/lang/ThreadGroup/Suspend.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/java/lang/invoke/lambda/LambdaConstructorMethodHandleUnbox.java b/test/java/lang/invoke/lambda/LambdaConstructorMethodHandleUnbox.java new file mode 100644 index 0000000000000000000000000000000000000000..5d77da88828d5c376d058d368f5b1d73926e3a98 --- /dev/null +++ b/test/java/lang/invoke/lambda/LambdaConstructorMethodHandleUnbox.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8016761 + * @summary Lambda metafactory: incorrect type conversion of constructor method handle + */ + +public class LambdaConstructorMethodHandleUnbox { + interface IntFunction { + int m(X x); + } + + public static void main(String[] args) { + IntFunction s = Integer::new; + if (s.m("2000") + s.m("13") != 2013) { + throw new RuntimeException("Lambda conversion failure"); + } + } +} diff --git a/test/java/lang/management/MXBean/MXBeanBehavior.java b/test/java/lang/management/MXBean/MXBeanBehavior.java index ccffecabebd671642b2bbb71bf00950bdba4da53..12403164abab8b44dc0366c75fba947e8d409816 100644 --- a/test/java/lang/management/MXBean/MXBeanBehavior.java +++ b/test/java/lang/management/MXBean/MXBeanBehavior.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2013 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/java/lang/management/ManagementFactory/MBeanServerMXBeanUnsupportedTest.java b/test/java/lang/management/ManagementFactory/MBeanServerMXBeanUnsupportedTest.java index 00f3768efe622a8d638841ed63ce36bbf8decb71..195fb573ec8ed279611dae9e88fa41fb022cca23 100644 --- a/test/java/lang/management/ManagementFactory/MBeanServerMXBeanUnsupportedTest.java +++ b/test/java/lang/management/ManagementFactory/MBeanServerMXBeanUnsupportedTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2013 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/java/lang/management/PlatformLoggingMXBean/LoggingMXBeanTest.java b/test/java/lang/management/PlatformLoggingMXBean/LoggingMXBeanTest.java index 26b3b6615310f3a72b64b167ed7915c0ffce462f..b88710c81a6f3f358e836fe3baa54b60316dfa28 100644 --- a/test/java/lang/management/PlatformLoggingMXBean/LoggingMXBeanTest.java +++ b/test/java/lang/management/PlatformLoggingMXBean/LoggingMXBeanTest.java @@ -36,12 +36,14 @@ import javax.management.MBeanServer; import java.util.logging.*; import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.HashMap; public class LoggingMXBeanTest { - static String LOGGER_NAME_1 = "com.sun.management.Logger"; - static String LOGGER_NAME_2 = "com.sun.management.Logger.Logger2"; - static String UNKNOWN_LOGGER_NAME = "com.sun.management.Unknown"; + static final String LOGGER_NAME_1 = "com.sun.management.Logger"; + static final String LOGGER_NAME_2 = "com.sun.management.Logger.Logger2"; + static final String UNKNOWN_LOGGER_NAME = "com.sun.management.Unknown"; // These instance variables prevent premature logger garbage collection // See getLogger() weak reference warnings. @@ -213,23 +215,35 @@ public class LoggingMXBeanTest PlatformLoggingMXBean mxbean2) { // verify logger names List loggers1 = mxbean1.getLoggerNames(); + System.out.println("Loggers: " + loggers1); + + // Retrieve the named loggers to prevent them from being + // spontaneously gc'ed. + Map loggersMap = new HashMap<>(); + for (String n : loggers1) { + loggersMap.put(n, Logger.getLogger(n)); + } + List loggers2 = mxbean2.getLoggerNames(); + // loggers1 and loggers2 should be identical - no new logger should + // have been created in between (at least no new logger name) + // if (loggers1.size() != loggers2.size()) throw new RuntimeException("LoggerNames: unmatched number of entries"); - List loggers3 = new ArrayList<>(loggers1); - loggers3.removeAll(loggers2); - if (loggers3.size() != 0) + if (!loggers2.containsAll(loggersMap.keySet())) throw new RuntimeException("LoggerNames: unmatched loggers"); + // verify logger's level and parent for (String logger : loggers1) { - if (!mxbean1.getLoggerLevel(logger) - .equals(mxbean2.getLoggerLevel(logger))) + String level1 = mxbean1.getLoggerLevel(logger); + String level2 = mxbean2.getLoggerLevel(logger); + if (!java.util.Objects.equals(level1, level2)) { throw new RuntimeException( - "LoggerLevel: unmatched level for " + logger - + ", " + mxbean1.getLoggerLevel(logger) - + ", " + mxbean2.getLoggerLevel(logger)); + "LoggerLevel: unmatched level for " + logger + + ", " + level1 + ", " + level2); + } if (!mxbean1.getParentLoggerName(logger) .equals(mxbean2.getParentLoggerName(logger))) diff --git a/test/java/math/BigInteger/BigIntegerTest.java b/test/java/math/BigInteger/BigIntegerTest.java index 4522d4440bfac9748ce114a689dc3121f72422a8..17c58bce98122e874a1c3aefa3765cc494b36e58 100644 --- a/test/java/math/BigInteger/BigIntegerTest.java +++ b/test/java/math/BigInteger/BigIntegerTest.java @@ -61,10 +61,13 @@ public class BigIntegerTest { // KARATSUBA_SQUARE_THRESHOLD = 90 ints = 2880 bits // TOOM_COOK_SQUARE_THRESHOLD = 140 ints = 4480 bits // + // SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 8 ints = 256 bits + // static final int BITS_KARATSUBA = 1600; static final int BITS_TOOM_COOK = 2400; static final int BITS_KARATSUBA_SQUARE = 2880; static final int BITS_TOOM_COOK_SQUARE = 4480; + static final int BITS_SCHOENHAGE_BASE = 256; static final int ORDER_SMALL = 60; static final int ORDER_MEDIUM = 100; @@ -467,12 +470,13 @@ public class BigIntegerTest { public static void stringConv() { int failCount = 0; + // Generic string conversion. for (int i=0; i<100; i++) { byte xBytes[] = new byte[Math.abs(rnd.nextInt())%100+1]; rnd.nextBytes(xBytes); BigInteger x = new BigInteger(xBytes); - for (int radix=2; radix < 37; radix++) { + for (int radix=Character.MIN_RADIX; radix < Character.MAX_RADIX; radix++) { String result = x.toString(radix); BigInteger test = new BigInteger(result, radix); if (!test.equals(x)) { @@ -483,6 +487,32 @@ public class BigIntegerTest { } } } + + // String conversion straddling the Schoenhage algorithm crossover + // threshold, and at twice and four times the threshold. + for (int k = 0; k <= 2; k++) { + int factor = 1 << k; + int upper = factor * BITS_SCHOENHAGE_BASE + 33; + int lower = upper - 35; + + for (int bits = upper; bits >= lower; bits--) { + for (int i = 0; i < 50; i++) { + BigInteger x = BigInteger.ONE.shiftLeft(bits - 1).or(new BigInteger(bits - 2, rnd)); + + for (int radix = Character.MIN_RADIX; radix < Character.MAX_RADIX; radix++) { + String result = x.toString(radix); + BigInteger test = new BigInteger(result, radix); + if (!test.equals(x)) { + failCount++; + System.err.println("BigInteger toString: " + x); + System.err.println("Test: " + test); + System.err.println(radix); + } + } + } + } + } + report("String Conversion", failCount); } diff --git a/test/java/net/CookieHandler/EmptyCookieHeader.java b/test/java/net/CookieHandler/EmptyCookieHeader.java new file mode 100644 index 0000000000000000000000000000000000000000..f35631741a66105d86bb1eb4c73e5b47f96c74ce --- /dev/null +++ b/test/java/net/CookieHandler/EmptyCookieHeader.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8015799 + * @summary HttpURLConnection.getHeaderFields() throws IllegalArgumentException + */ + +import com.sun.net.httpserver.*; +import java.io.IOException; +import java.io.OutputStream; +import java.net.*; +import java.util.*; + +public class EmptyCookieHeader { + + public static void main(String[] args) throws Exception { + new EmptyCookieHeader().runTest(); + } + + public void runTest() throws Exception { + final CookieHandler oldHandler = CookieHandler.getDefault(); + CookieHandler.setDefault(new TestCookieHandler()); + HttpServer s = HttpServer.create(new InetSocketAddress(0), 0); + try { + startServer(s); + URL url = new URL("http://localhost:" + s.getAddress().getPort() + "/"); + HttpURLConnection c = (HttpURLConnection)url.openConnection(); + c.getHeaderFields(); + } finally { + CookieHandler.setDefault(oldHandler); + s.stop(0); + } + } + + static void startServer(HttpServer server) throws IOException { + server.createContext("/", new EmptyCookieHandler()); + server.start(); + } + + static class EmptyCookieHandler implements HttpHandler { + + @Override + public void handle(HttpExchange exchange) throws IOException { + String requestMethod = exchange.getRequestMethod(); + if (requestMethod.equalsIgnoreCase("GET")) { + Headers responseHeaders = exchange.getResponseHeaders(); + responseHeaders.set("Content-Type", "text/plain"); + responseHeaders.set("Date", "June 13th 2012"); + + // No domain value set + responseHeaders.set("Set-Cookie2", "name=value"); + responseHeaders.set("Set-Cookie2", ""); + exchange.sendResponseHeaders(200, 0); + try (OutputStream os = exchange.getResponseBody()) { + String str = "This is what the server sent!"; + os.write(str.getBytes()); + } + } + } + } + + class TestCookieHandler extends CookieHandler { + @Override + public Map> get(URI uri, + Map> respH) { + return new HashMap<>(); + } + + @Override + public void put(URI uri, Map> respH) { } + } +} diff --git a/test/java/nio/file/Files/StreamTest.java b/test/java/nio/file/Files/StreamTest.java index 0033dd31f3890ac687d7f2fbf6f4d89d5b57ff14..b5ff2977257d0aa7c9fd9a21d46d1a10ad27a8af 100644 --- a/test/java/nio/file/Files/StreamTest.java +++ b/test/java/nio/file/Files/StreamTest.java @@ -43,7 +43,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.Arrays; -import java.util.Comparators; +import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Objects; @@ -139,7 +139,7 @@ public class StreamTest { public void testBasic() { try (CloseableStream s = Files.list(testFolder)) { - Object[] actual = s.sorted(Comparators.naturalOrder()).toArray(); + Object[] actual = s.sorted(Comparator.naturalOrder()).toArray(); assertEquals(actual, level1); } catch (IOException ioe) { fail("Unexpected IOException"); @@ -155,7 +155,7 @@ public class StreamTest { public void testWalk() { try (CloseableStream s = Files.walk(testFolder)) { - Object[] actual = s.sorted(Comparators.naturalOrder()).toArray(); + Object[] actual = s.sorted(Comparator.naturalOrder()).toArray(); assertEquals(actual, all); } catch (IOException ioe) { fail("Unexpected IOException"); @@ -165,7 +165,7 @@ public class StreamTest { public void testWalkOneLevel() { try (CloseableStream s = Files.walk(testFolder, 1)) { Object[] actual = s.filter(path -> ! path.equals(testFolder)) - .sorted(Comparators.naturalOrder()) + .sorted(Comparator.naturalOrder()) .toArray(); assertEquals(actual, level1); } catch (IOException ioe) { @@ -177,7 +177,7 @@ public class StreamTest { // If link is not supported, the directory structure won't have link. // We still want to test the behavior with FOLLOW_LINKS option. try (CloseableStream s = Files.walk(testFolder, FileVisitOption.FOLLOW_LINKS)) { - Object[] actual = s.sorted(Comparators.naturalOrder()).toArray(); + Object[] actual = s.sorted(Comparator.naturalOrder()).toArray(); assertEquals(actual, all_folowLinks); } catch (IOException ioe) { fail("Unexpected IOException"); @@ -637,13 +637,13 @@ public class StreamTest { public void testClosedStream() throws IOException { try (CloseableStream s = Files.list(testFolder)) { s.close(); - Object[] actual = s.sorted(Comparators.naturalOrder()).toArray(); + Object[] actual = s.sorted(Comparator.naturalOrder()).toArray(); assertTrue(actual.length <= level1.length); } try (CloseableStream s = Files.walk(testFolder)) { s.close(); - Object[] actual = s.sorted(Comparators.naturalOrder()).toArray(); + Object[] actual = s.sorted(Comparator.naturalOrder()).toArray(); fail("Operate on closed stream should throw IllegalStateException"); } catch (IllegalStateException ex) { // expected @@ -652,7 +652,7 @@ public class StreamTest { try (CloseableStream s = Files.find(testFolder, Integer.MAX_VALUE, (p, attr) -> true)) { s.close(); - Object[] actual = s.sorted(Comparators.naturalOrder()).toArray(); + Object[] actual = s.sorted(Comparator.naturalOrder()).toArray(); fail("Operate on closed stream should throw IllegalStateException"); } catch (IllegalStateException ex) { // expected diff --git a/test/java/security/cert/CertPathValidator/OCSP/FailoverToCRL.java b/test/java/security/cert/CertPathValidator/OCSP/FailoverToCRL.java index df69edc7f2254199319f7c87b15f2c97accea723..25eaab56eea0737a5db6ba832f66257a253a2524 100644 --- a/test/java/security/cert/CertPathValidator/OCSP/FailoverToCRL.java +++ b/test/java/security/cert/CertPathValidator/OCSP/FailoverToCRL.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ /** * @test - * @bug 6383095 + * @bug 6383095 8019259 * @summary CRL revoked certificate failures masked by OCSP failures * * Note that the certificate validity is from Mar 16 14:55:35 2009 GMT to @@ -254,12 +254,32 @@ public class FailoverToCRL { CertPathValidator validator = CertPathValidator.getInstance("PKIX"); try { + System.out.println("Validating cert via OCSP: no responder URL"); validator.validate(path, params); } catch (CertPathValidatorException cpve) { if (cpve.getReason() != BasicReason.REVOKED) { throw new Exception( - "unexpect exception, should be a REVOKED CPVE", cpve); + "unexpected exception, should be a REVOKED CPVE", cpve); } + System.out.println(" successful failover to using CRLs"); + } + + java.security.cert.PKIXRevocationChecker revocationChecker = + (java.security.cert.PKIXRevocationChecker) + validator.getRevocationChecker(); + revocationChecker.setOCSPResponder( + new java.net.URI("bad_ocsp_responder_url")); + params.addCertPathChecker(revocationChecker); + + try { + System.out.println("Validating cert via OCSP: bad responder URL"); + validator.validate(path, params); + } catch (CertPathValidatorException cpve) { + if (cpve.getReason() != BasicReason.REVOKED) { + throw new Exception( + "unexpected exception, should be a REVOKED CPVE", cpve); + } + System.out.println(" successful failover to using CRLs"); } } } diff --git a/test/java/util/Arrays/ParallelPrefix.java b/test/java/util/Arrays/ParallelPrefix.java new file mode 100644 index 0000000000000000000000000000000000000000..072de79c42c55372072df2c5e956b035214746c1 --- /dev/null +++ b/test/java/util/Arrays/ParallelPrefix.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @summary unit test for Arrays.ParallelPrefix(). + * @author Tristan Yan + * @run testng ParallelPrefix + */ + +import java.util.Arrays; +import java.util.function.BinaryOperator; +import java.util.function.DoubleBinaryOperator; +import java.util.function.Function; +import java.util.function.IntBinaryOperator; +import java.util.function.LongBinaryOperator; +import java.util.stream.IntStream; +import java.util.stream.LongStream; +import static org.testng.Assert.*; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class ParallelPrefix { + //Array size less than MIN_PARTITION + private final static int SMALL_ARRAY_SIZE = 1 << 3; + + //Array size equals MIN_PARTITION + private final static int THRESHOLD_ARRAY_SIZE = 1 << 4; + + //Array size greater than MIN_PARTITION + private final static int MEDIUM_ARRAY_SIZE = 1 << 8; + + //Array size much greater than MIN_PARTITION + private final static int LARGE_ARRAY_SIZE = 1 << 12; + + private final static int[] ARRAY_SIZE_COLLECTION = new int[]{ + SMALL_ARRAY_SIZE, THRESHOLD_ARRAY_SIZE,MEDIUM_ARRAY_SIZE, LARGE_ARRAY_SIZE}; + + @DataProvider + public static Object[][] intSet(){ + return genericData(size -> IntStream.range(0, size).toArray(), new IntBinaryOperator[]{Integer::sum, Integer::min}); + } + + @DataProvider + public static Object[][] longSet(){ + return genericData(size -> LongStream.range(0, size).toArray(), new LongBinaryOperator[]{Long::sum, Long::min}); + } + + @DataProvider + public static Object[][] doubleSet(){ + return genericData(size -> IntStream.range(0, size).mapToDouble(i -> (double)i).toArray(), + new DoubleBinaryOperator[]{Double::sum, Double::min}); + } + + @DataProvider + public static Object[][] stringSet(){ + Function stringsFunc = size -> + IntStream.range(0, size).mapToObj(Integer::toString).toArray(String[]::new); + BinaryOperator cancatBop = String::concat; + return genericData(stringsFunc, new BinaryOperator[]{cancatBop}); + } + + private static Object[][] genericData(Function generateFunc, OPS[] ops) { + //test arrays which size is equals n-1, n, n+1, test random data + Object[][] data = new Object[ARRAY_SIZE_COLLECTION.length * 3 * ops.length][4]; + for(int n = 0; n < ARRAY_SIZE_COLLECTION.length; n++ ) { + for(int testValue = -1 ; testValue <= 1; testValue++) { + int array_size = ARRAY_SIZE_COLLECTION[n] + testValue; + for(int opsN = 0; opsN < ops.length; opsN++) { + int index = n * 3 * ops.length + (testValue + 1) * ops.length + opsN; + data[index][0] = generateFunc.apply(array_size); + data[index][1] = array_size / 3; + data[index][2] = 2 * array_size / 3; + data[index][3] = ops[opsN]; + } + } + } + return data; + } + + @Test(dataProvider="intSet") + public void testParallelPrefixForInt(int[] data, int fromIndex, int toIndex, IntBinaryOperator op) { + int[] sequentialResult = data.clone(); + for (int index = fromIndex + 1; index < toIndex; index++) { + sequentialResult[index ] = op.applyAsInt(sequentialResult[index - 1], sequentialResult[index]); + } + + int[] parallelResult = data.clone(); + Arrays.parallelPrefix(parallelResult, fromIndex, toIndex, op); + assertEquals(parallelResult, sequentialResult); + + int[] parallelRangeResult = Arrays.copyOfRange(data, fromIndex, toIndex); + Arrays.parallelPrefix(parallelRangeResult, op); + assertEquals(parallelRangeResult, Arrays.copyOfRange(sequentialResult, fromIndex, toIndex)); + } + + @Test(dataProvider="longSet") + public void testParallelPrefixForLong(long[] data, int fromIndex, int toIndex, LongBinaryOperator op) { + long[] sequentialResult = data.clone(); + for (int index = fromIndex + 1; index < toIndex; index++) { + sequentialResult[index ] = op.applyAsLong(sequentialResult[index - 1], sequentialResult[index]); + } + + long[] parallelResult = data.clone(); + Arrays.parallelPrefix(parallelResult, fromIndex, toIndex, op); + assertEquals(parallelResult, sequentialResult); + + long[] parallelRangeResult = Arrays.copyOfRange(data, fromIndex, toIndex); + Arrays.parallelPrefix(parallelRangeResult, op); + assertEquals(parallelRangeResult, Arrays.copyOfRange(sequentialResult, fromIndex, toIndex)); + } + + @Test(dataProvider="doubleSet") + public void testParallelPrefixForDouble(double[] data, int fromIndex, int toIndex, DoubleBinaryOperator op) { + double[] sequentialResult = data.clone(); + for (int index = fromIndex + 1; index < toIndex; index++) { + sequentialResult[index ] = op.applyAsDouble(sequentialResult[index - 1], sequentialResult[index]); + } + + double[] parallelResult = data.clone(); + Arrays.parallelPrefix(parallelResult, fromIndex, toIndex, op); + assertEquals(parallelResult, sequentialResult); + + double[] parallelRangeResult = Arrays.copyOfRange(data, fromIndex, toIndex); + Arrays.parallelPrefix(parallelRangeResult, op); + assertEquals(parallelRangeResult, Arrays.copyOfRange(sequentialResult, fromIndex, toIndex)); + } + + @Test(dataProvider="stringSet") + public void testParallelPrefixForStringr(String[] data , int fromIndex, int toIndex, BinaryOperator op) { + String[] sequentialResult = data.clone(); + for (int index = fromIndex + 1; index < toIndex; index++) { + sequentialResult[index ] = op.apply(sequentialResult[index - 1], sequentialResult[index]); + } + + String[] parallelResult = data.clone(); + Arrays.parallelPrefix(parallelResult, fromIndex, toIndex, op); + assertEquals(parallelResult, sequentialResult); + + String[] parallelRangeResult = Arrays.copyOfRange(data, fromIndex, toIndex); + Arrays.parallelPrefix(parallelRangeResult, op); + assertEquals(parallelRangeResult, Arrays.copyOfRange(sequentialResult, fromIndex, toIndex)); + } +} + diff --git a/test/java/util/Collection/ListDefaults.java b/test/java/util/Collection/ListDefaults.java index 6011fbf7804c910e5a39d87f3a9ceb11306491d6..e0f8e6f6992d586c3191c5d47d5d714cad409e36 100644 --- a/test/java/util/Collection/ListDefaults.java +++ b/test/java/util/Collection/ListDefaults.java @@ -25,7 +25,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; -import java.util.Comparators; import java.util.List; import java.util.LinkedList; import java.util.Stack; @@ -337,23 +336,23 @@ public class ListDefaults { CollectionSupplier.shuffle(list); list.sort(null); - CollectionAsserts.assertSorted(list, Comparators.naturalOrder()); + CollectionAsserts.assertSorted(list, Comparator.naturalOrder()); if (test.name.startsWith("reverse")) { Collections.reverse(list); } CollectionAsserts.assertContents(list, original); CollectionSupplier.shuffle(list); - list.sort(Comparators.naturalOrder()); - CollectionAsserts.assertSorted(list, Comparators.naturalOrder()); + list.sort(Comparator.naturalOrder()); + CollectionAsserts.assertSorted(list, Comparator.naturalOrder()); if (test.name.startsWith("reverse")) { Collections.reverse(list); } CollectionAsserts.assertContents(list, original); CollectionSupplier.shuffle(list); - list.sort(Comparators.reverseOrder()); - CollectionAsserts.assertSorted(list, Comparators.reverseOrder()); + list.sort(Comparator.reverseOrder()); + CollectionAsserts.assertSorted(list, Comparator.reverseOrder()); if (!test.name.startsWith("reverse")) { Collections.reverse(list); } @@ -390,8 +389,8 @@ public class ListDefaults { final List copy = new ArrayList<>(list); final List subList = list.subList(SUBLIST_FROM, SUBLIST_TO); CollectionSupplier.shuffle(subList); - subList.sort(Comparators.naturalOrder()); - CollectionAsserts.assertSorted(subList, Comparators.naturalOrder()); + subList.sort(Comparator.naturalOrder()); + CollectionAsserts.assertSorted(subList, Comparator.naturalOrder()); // verify that elements [0, from) remain unmodified for (int i = 0; i < SUBLIST_FROM; i++) { assertTrue(list.get(i) == copy.get(i), @@ -412,8 +411,8 @@ public class ListDefaults { public void call(final List list) { final List copy = new ArrayList<>(list); CollectionSupplier.shuffle(list); - list.sort(Comparators.naturalOrder()); - CollectionAsserts.assertSorted(list, Comparators.naturalOrder()); + list.sort(Comparator.naturalOrder()); + CollectionAsserts.assertSorted(list, Comparator.naturalOrder()); } }); } diff --git a/test/java/util/Comparators/BasicTest.java b/test/java/util/Comparator/BasicTest.java similarity index 55% rename from test/java/util/Comparators/BasicTest.java rename to test/java/util/Comparator/BasicTest.java index 0913eb84b58cfab76e041a0bace6902bceb009ba..5bbb700e0b38f18ed322ec45ab7252fd47e1211d 100644 --- a/test/java/util/Comparators/BasicTest.java +++ b/test/java/util/Comparator/BasicTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,19 +21,16 @@ * questions. */ -/* +/** * @test - * @bug 8001667 8010279 + * @summary Comparator default method tests * @run testng BasicTest */ +import java.util.TreeMap; import java.util.Comparator; -import java.util.Comparators; -import java.util.AbstractMap; -import java.util.Map; import org.testng.annotations.Test; -import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.ToIntFunction; import java.util.function.ToLongFunction; @@ -41,12 +38,8 @@ import java.util.function.ToDoubleFunction; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; -import static org.testng.Assert.assertSame; import static org.testng.Assert.fail; -/** - * Unit tests for helper methods in Comparators - */ @Test(groups = "unit") public class BasicTest { private static class Thing { @@ -97,7 +90,7 @@ public class BasicTest { Thing[] things = new Thing[intValues.length]; for (int i=0; i comp = Comparators.comparing(new ToIntFunction() { + Comparator comp = Comparator.comparing(new ToIntFunction() { @Override public int applyAsInt(Thing thing) { return thing.getIntField(); @@ -111,7 +104,7 @@ public class BasicTest { Thing[] things = new Thing[longValues.length]; for (int i=0; i comp = Comparators.comparing(new ToLongFunction() { + Comparator comp = Comparator.comparing(new ToLongFunction() { @Override public long applyAsLong(Thing thing) { return thing.getLongField(); @@ -125,7 +118,7 @@ public class BasicTest { Thing[] things = new Thing[doubleValues.length]; for (int i=0; i comp = Comparators.comparing(new ToDoubleFunction() { + Comparator comp = Comparator.comparing(new ToDoubleFunction() { @Override public double applyAsDouble(Thing thing) { return thing.getDoubleField(); @@ -139,7 +132,7 @@ public class BasicTest { Thing[] things = new Thing[doubleValues.length]; for (int i=0; i comp = Comparators.comparing(new Function() { + Comparator comp = Comparator.comparing(new Function() { @Override public String apply(Thing thing) { return thing.getStringField(); @@ -150,16 +143,16 @@ public class BasicTest { } public void testNaturalOrderComparator() { - Comparator comp = Comparators.naturalOrder(); + Comparator comp = Comparator.naturalOrder(); assertComparisons(stringValues, comp, comparisons); } public void testReverseComparator() { - Comparator cmpr = Comparators.reverseOrder(); - Comparator cmp = cmpr.reverseOrder(); + Comparator cmpr = Comparator.reverseOrder(); + Comparator cmp = cmpr.reversed(); - assertEquals(cmp.reverseOrder(), cmpr); + assertEquals(cmp.reversed(), cmpr); assertEquals(0, cmp.compare("a", "a")); assertEquals(0, cmpr.compare("a", "a")); assertTrue(cmp.compare("a", "b") < 0); @@ -170,9 +163,9 @@ public class BasicTest { public void testReverseComparator2() { Comparator cmp = (s1, s2) -> s1.length() - s2.length(); - Comparator cmpr = cmp.reverseOrder(); + Comparator cmpr = cmp.reversed(); - assertEquals(cmpr.reverseOrder(), cmp); + assertEquals(cmpr.reversed(), cmp); assertEquals(0, cmp.compare("abc", "def")); assertEquals(0, cmpr.compare("abc", "def")); assertTrue(cmp.compare("abcd", "def") > 0); @@ -181,71 +174,11 @@ public class BasicTest { assertTrue(cmpr.compare("abc", "defg") > 0); } - @Test(expectedExceptions=NullPointerException.class) - public void testReverseComparatorNPE() { - Comparator cmp = Comparators.reverseOrder(null); - } - - public void testComposeComparator() { - // Longer string in front - Comparator first = (s1, s2) -> s2.length() - s1.length(); - Comparator second = Comparators.naturalOrder(); - Comparator composed = Comparators.compose(first, second); - - assertTrue(composed.compare("abcdefg", "abcdef") < 0); - assertTrue(composed.compare("abcdef", "abcdefg") > 0); - assertTrue(composed.compare("abcdef", "abcdef") == 0); - assertTrue(composed.compare("abcdef", "ghijkl") < 0); - assertTrue(composed.compare("ghijkl", "abcdefg") > 0); - } - - private void assertPairComparison(K k1, V v1, K k2, V v2, - Comparator> ck, - Comparator> cv) { - final Map.Entry p11 = new AbstractMap.SimpleImmutableEntry<>(k1, v1); - final Map.Entry p12 = new AbstractMap.SimpleImmutableEntry<>(k1, v2); - final Map.Entry p21 = new AbstractMap.SimpleImmutableEntry<>(k2, v1); - final Map.Entry p22 = new AbstractMap.SimpleImmutableEntry<>(k2, v2); - - assertTrue(ck.compare(p11, p11) == 0); - assertTrue(ck.compare(p12, p11) == 0); - assertTrue(ck.compare(p11, p12) == 0); - assertTrue(ck.compare(p12, p22) < 0); - assertTrue(ck.compare(p12, p21) < 0); - assertTrue(ck.compare(p21, p11) > 0); - assertTrue(ck.compare(p21, p12) > 0); - - assertTrue(cv.compare(p11, p11) == 0); - assertTrue(cv.compare(p12, p11) > 0); - assertTrue(cv.compare(p11, p12) < 0); - assertTrue(cv.compare(p12, p22) == 0); - assertTrue(cv.compare(p12, p21) > 0); - assertTrue(cv.compare(p21, p11) == 0); - assertTrue(cv.compare(p21, p12) < 0); - - Comparator> cmp = Comparators.compose(ck, cv); - assertTrue(cmp.compare(p11, p11) == 0); - assertTrue(cmp.compare(p12, p11) > 0); - assertTrue(cmp.compare(p11, p12) < 0); - assertTrue(cmp.compare(p12, p22) < 0); - assertTrue(cmp.compare(p12, p21) < 0); - assertTrue(cmp.compare(p21, p11) > 0); - assertTrue(cmp.compare(p21, p12) > 0); - - cmp = Comparators.compose(cv, ck); - assertTrue(cmp.compare(p11, p11) == 0); - assertTrue(cmp.compare(p12, p11) > 0); - assertTrue(cmp.compare(p11, p12) < 0); - assertTrue(cmp.compare(p12, p22) < 0); - assertTrue(cmp.compare(p12, p21) > 0); - assertTrue(cmp.compare(p21, p11) > 0); - assertTrue(cmp.compare(p21, p12) < 0); - } - - public void testKVComparatorable() { - assertPairComparison(1, "ABC", 2, "XYZ", - Comparators.naturalOrderKeys(), - Comparators.naturalOrderValues()); + private void assertComparison(Comparator cmp, T less, T greater) { + assertTrue(cmp.compare(less, greater) < 0, "less"); + assertTrue(cmp.compare(less, less) == 0, "equal"); + assertTrue(cmp.compare(greater, greater) == 0, "equal"); + assertTrue(cmp.compare(greater, less) > 0, "greater"); } private static class People { @@ -273,33 +206,15 @@ public class BasicTest { new People("Jonah", "Doe", 10), new People("John", "Cook", 54), new People("Mary", "Cook", 50), + new People("Mary", null, 25), + new People("John", null, 27) }; - public void testKVComparators() { - // Comparator cmp = Comparators.naturalOrder(); // Should fail to compiler as People is not comparable - // We can use simple comparator, but those have been tested above. - // Thus choose to do compose for some level of interation. - Comparator cmp1 = Comparators.comparing((Function) People::getFirstName); - Comparator cmp2 = Comparators.comparing((Function) People::getLastName); - Comparator cmp = Comparators.compose(cmp1, cmp2); - - assertPairComparison(people[0], people[0], people[1], people[1], - Comparators.byKey(cmp), - Comparators.byValue(cmp)); - - } - - private void assertComparison(Comparator cmp, T less, T greater) { - assertTrue(cmp.compare(less, greater) < 0, "less"); - assertTrue(cmp.compare(less, less) == 0, "equal"); - assertTrue(cmp.compare(greater, less) > 0, "greater"); - } - public void testComparatorDefaultMethods() { - Comparator cmp = Comparators.comparing((Function) People::getFirstName); - Comparator cmp2 = Comparators.comparing((Function) People::getLastName); + Comparator cmp = Comparator.comparing((Function) People::getFirstName); + Comparator cmp2 = Comparator.comparing((Function) People::getLastName); // reverseOrder - assertComparison(cmp.reverseOrder(), people[1], people[0]); + assertComparison(cmp.reversed(), people[1], people[0]); // thenComparing(Comparator) assertComparison(cmp.thenComparing(cmp2), people[0], people[1]); assertComparison(cmp.thenComparing(cmp2), people[4], people[0]); @@ -317,96 +232,138 @@ public class BasicTest { assertComparison(cmp.thenComparing(People::getAgeAsDouble), people[1], people[5]); } - public void testGreaterOf() { - // lesser - assertSame(Comparators.greaterOf(Comparators.comparing( - (Function) People::getFirstName)) - .apply(people[0], people[1]), - people[1]); - // euqal - assertSame(Comparators.greaterOf(Comparators.comparing( - (Function) People::getLastName)) - .apply(people[0], people[1]), - people[0]); - // greater - assertSame(Comparators.greaterOf(Comparators.comparing( - (ToIntFunction) People::getAge)) - .apply(people[0], people[1]), - people[0]); + + public void testNullsFirst() { + Comparator strcmp = Comparator.nullsFirst(Comparator.naturalOrder()); + Comparator cmp = Comparator.comparing(People::getLastName, strcmp) + .thenComparing(People::getFirstName, strcmp); + // Mary.null vs Mary.Cook - solve by last name + assertComparison(cmp, people[6], people[5]); + // John.null vs Mary.null - solve by first name + assertComparison(cmp, people[7], people[6]); + + // More than one thenComparing + strcmp = Comparator.nullsFirst(Comparator.comparing((ToIntFunction) String::length) + .thenComparing(String.CASE_INSENSITIVE_ORDER)); + assertComparison(strcmp, null, "abc"); + assertComparison(strcmp, "ab", "abc"); + assertComparison(strcmp, "abc", "def"); + assertEquals(0, strcmp.compare("abc", "ABC")); + + // Ensure reverse still handle null properly + Comparator strcmp2 = strcmp.reversed().thenComparing(Comparator.naturalOrder()); + assertComparison(strcmp2, "abc", null); + assertComparison(strcmp2, "abc", "ab"); + assertComparison(strcmp2, "def", "abc"); + assertComparison(strcmp2, "ABC", "abc"); + + // Considering non-null values to be equal + Comparator blind = Comparator.nullsFirst(null); + assertComparison(blind, null, "abc"); + assertEquals(0, blind.compare("abc", "def")); + // reverse still consider non-null values to be equal + strcmp = blind.reversed(); + assertComparison(strcmp, "abc", null); + assertEquals(0, strcmp.compare("abc", "def")); + // chain with another comparator to compare non-nulls + strcmp = blind.thenComparing(Comparator.naturalOrder()); + assertComparison(strcmp, null, "abc"); + assertComparison(strcmp, "abc", "def"); + } + + public void testNullsLast() { + Comparator strcmp = Comparator.nullsLast(Comparator.naturalOrder()); + Comparator cmp = Comparator.comparing(People::getLastName, strcmp) + .thenComparing(People::getFirstName, strcmp); + // Mary.null vs Mary.Cook - solve by last name + assertComparison(cmp, people[5], people[6]); + // John.null vs Mary.null - solve by first name + assertComparison(cmp, people[7], people[6]); + + // More than one thenComparing + strcmp = Comparator.nullsLast(Comparator.comparing((ToIntFunction) String::length) + .thenComparing(String.CASE_INSENSITIVE_ORDER)); + assertComparison(strcmp, "abc", null); + assertComparison(strcmp, "ab", "abc"); + assertComparison(strcmp, "abc", "def"); + + // Ensure reverse still handle null properly + Comparator strcmp2 = strcmp.reversed().thenComparing(Comparator.naturalOrder()); + assertComparison(strcmp2, null, "abc"); + assertComparison(strcmp2, "abc", "ab"); + assertComparison(strcmp2, "def", "abc"); + assertComparison(strcmp2, "ABC", "abc"); + + // Considering non-null values to be equal + Comparator blind = Comparator.nullsLast(null); + assertComparison(blind, "abc", null); + assertEquals(0, blind.compare("abc", "def")); + // reverse still consider non-null values to be equal + strcmp = blind.reversed(); + assertComparison(strcmp, null, "abc"); + assertEquals(0, strcmp.compare("abc", "def")); + // chain with another comparator to compare non-nulls + strcmp = blind.thenComparing(Comparator.naturalOrder()); + assertComparison(strcmp, "abc", null); + assertComparison(strcmp, "abc", "def"); } - public void testLesserOf() { - // lesser - assertSame(Comparators.lesserOf(Comparators.comparing( - (Function) People::getFirstName)) - .apply(people[0], people[1]), - people[0]); - // euqal - assertSame(Comparators.lesserOf(Comparators.comparing( - (Function) People::getLastName)) - .apply(people[0], people[1]), - people[0]); - // greater - assertSame(Comparators.lesserOf(Comparators.comparing( - (ToIntFunction) People::getAge)) - .apply(people[0], people[1]), - people[1]); + public void testComposeComparator() { + // Longer string in front + Comparator first = (s1, s2) -> s2.length() - s1.length(); + Comparator second = Comparator.naturalOrder(); + Comparator composed = first.thenComparing(second); + + assertTrue(composed.compare("abcdefg", "abcdef") < 0); + assertTrue(composed.compare("abcdef", "abcdefg") > 0); + assertTrue(composed.compare("abcdef", "abcdef") == 0); + assertTrue(composed.compare("abcdef", "ghijkl") < 0); + assertTrue(composed.compare("ghijkl", "abcdefg") > 0); } public void testNulls() { try { - Comparators.naturalOrder().compare("abc", (String) null); + Comparator.naturalOrder().compare("abc", (String) null); fail("expected NPE with naturalOrder"); } catch (NullPointerException npe) {} try { - Comparators.naturalOrder().compare((String) null, "abc"); + Comparator.naturalOrder().compare((String) null, "abc"); fail("expected NPE with naturalOrder"); } catch (NullPointerException npe) {} try { - Comparators.reverseOrder().compare("abc", (String) null); + Comparator.reverseOrder().compare("abc", (String) null); fail("expected NPE with naturalOrder"); } catch (NullPointerException npe) {} try { - Comparators.reverseOrder().compare((String) null, "abc"); + Comparator.reverseOrder().compare((String) null, "abc"); fail("expected NPE with naturalOrder"); } catch (NullPointerException npe) {} try { - Comparator> cmp = Comparators.byKey(null); - fail("byKey(null) should throw NPE"); + Comparator cmp = Comparator.comparing((Function) null, Comparator.naturalOrder()); + fail("comparing(null, cmp) should throw NPE"); } catch (NullPointerException npe) {} - try { - Comparator> cmp = Comparators.byValue(null); - fail("byValue(null) should throw NPE"); + Comparator cmp = Comparator.comparing((Function) People::getFirstName, null); + fail("comparing(f, null) should throw NPE"); } catch (NullPointerException npe) {} try { - Comparator cmp = Comparators.comparing((Function) null); + Comparator cmp = Comparator.comparing((Function) null); fail("comparing(null) should throw NPE"); } catch (NullPointerException npe) {} try { - Comparator cmp = Comparators.comparing((ToIntFunction) null); + Comparator cmp = Comparator.comparing((ToIntFunction) null); fail("comparing(null) should throw NPE"); } catch (NullPointerException npe) {} try { - Comparator cmp = Comparators.comparing((ToLongFunction) null); + Comparator cmp = Comparator.comparing((ToLongFunction) null); fail("comparing(null) should throw NPE"); } catch (NullPointerException npe) {} try { - Comparator cmp = Comparators.comparing((ToDoubleFunction) null); + Comparator cmp = Comparator.comparing((ToDoubleFunction) null); fail("comparing(null) should throw NPE"); } catch (NullPointerException npe) {} - - try { - BinaryOperator op = Comparators.lesserOf(null); - fail("lesserOf(null) should throw NPE"); - } catch (NullPointerException npe) {} - - try { - BinaryOperator op = Comparators.greaterOf(null); - fail("lesserOf(null) should throw NPE"); - } catch (NullPointerException npe) {} } } diff --git a/test/java/util/Comparator/TypeTest.java b/test/java/util/Comparator/TypeTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b1c8a41cf3a4f2494a2404c99ce3a26904220eff --- /dev/null +++ b/test/java/util/Comparator/TypeTest.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @summary Comparator API narrowing type test + * @run testng TypeTest + */ + +import java.util.function.Function; +import java.util.Map; +import java.util.TreeMap; +import java.util.Comparator; +import org.testng.annotations.Test; + +@Test(groups = "unit") +public class TypeTest { + static class Person { + String name; + static Comparator C = (p1, p2) -> p1.name.compareTo(p2.name); + + Person(String name) { + this.name = name; + } + + String getName() { return name; } + } + + static class Employee extends Person { + int id; + static Comparator C = (e1, e2) -> e1.id - e2.id; + + Employee(int id, String name) { + super(name); + this.id = id; + } + } + + static class Manager extends Employee { + long reports; + static Comparator C = (e1, e2) -> (int) (e1.reports - e2.reports); + + Manager(String name, int id, long reports) { + super(id, name); + this.reports = reports; + } + } + + static void assertOrder(T o1, T o2, Comparator cmp) { + if (cmp.compare(o1, o2) > 0) { + System.out.println("Fail!!"); + } + if (cmp.compare(o1, o2) == 0) { + System.out.println("Equal!!"); + } + } + + public static void main(String[] args) { + Manager m1 = new Manager("Manager", 2, 2000); + Manager m2 = new Manager("Manager", 4, 1300); + + // Comparator tmp = Person.C; + + // Comparator cmp = Employee.C.thenComparing(Person.C); + Comparator cmp = Employee.C.thenComparing(Person.C); + assertOrder(m1, m2, Employee.C.thenComparing(Person.C)); + assertOrder(m1, m2, cmp); + assertOrder(m1, new Employee(1, "Z"), Person.C); + assertOrder(new Employee(1, "Z"), m2, Employee.C); + + assertOrder(m1, m2, Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER)); + + Map map = new TreeMap<>(); + map.entrySet().stream().sorted(Map.Entry.comparingByKey(String.CASE_INSENSITIVE_ORDER)); + } +} diff --git a/test/java/util/Map/EntryComparators.java b/test/java/util/Map/EntryComparators.java new file mode 100644 index 0000000000000000000000000000000000000000..ce607a3690128e3e9a3e6dc39049817fb06b0688 --- /dev/null +++ b/test/java/util/Map/EntryComparators.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8009736 8010279 + * @run testng EntryComparators + */ +import java.util.function.Function; +import java.util.Comparator; +import java.util.AbstractMap; +import java.util.Map; +import org.testng.annotations.Test; + +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +/** + * Unit tests for Map.Entry.comparing + */ +@Test(groups = "unit") +public class EntryComparators { + + private void assertPairComparison(K k1, V v1, K k2, V v2, + Comparator> ck, + Comparator> cv) { + final Map.Entry p11 = new AbstractMap.SimpleImmutableEntry<>(k1, v1); + final Map.Entry p12 = new AbstractMap.SimpleImmutableEntry<>(k1, v2); + final Map.Entry p21 = new AbstractMap.SimpleImmutableEntry<>(k2, v1); + final Map.Entry p22 = new AbstractMap.SimpleImmutableEntry<>(k2, v2); + + assertTrue(ck.compare(p11, p11) == 0); + assertTrue(ck.compare(p12, p11) == 0); + assertTrue(ck.compare(p11, p12) == 0); + assertTrue(ck.compare(p12, p22) < 0); + assertTrue(ck.compare(p12, p21) < 0); + assertTrue(ck.compare(p21, p11) > 0); + assertTrue(ck.compare(p21, p12) > 0); + + assertTrue(cv.compare(p11, p11) == 0); + assertTrue(cv.compare(p12, p11) > 0); + assertTrue(cv.compare(p11, p12) < 0); + assertTrue(cv.compare(p12, p22) == 0); + assertTrue(cv.compare(p12, p21) > 0); + assertTrue(cv.compare(p21, p11) == 0); + assertTrue(cv.compare(p21, p12) < 0); + + Comparator> cmp = ck.thenComparing(cv); + assertTrue(cmp.compare(p11, p11) == 0); + assertTrue(cmp.compare(p12, p11) > 0); + assertTrue(cmp.compare(p11, p12) < 0); + assertTrue(cmp.compare(p12, p22) < 0); + assertTrue(cmp.compare(p12, p21) < 0); + assertTrue(cmp.compare(p21, p11) > 0); + assertTrue(cmp.compare(p21, p12) > 0); + + cmp = cv.thenComparing(ck); + assertTrue(cmp.compare(p11, p11) == 0); + assertTrue(cmp.compare(p12, p11) > 0); + assertTrue(cmp.compare(p11, p12) < 0); + assertTrue(cmp.compare(p12, p22) < 0); + assertTrue(cmp.compare(p12, p21) > 0); + assertTrue(cmp.compare(p21, p11) > 0); + assertTrue(cmp.compare(p21, p12) < 0); + } + + public void testKVComparables() { + assertPairComparison(1, "ABC", 2, "XYZ", + Map.Entry.comparingByKey(), + Map.Entry.comparingByValue()); + } + + private static class People { + final String firstName; + final String lastName; + final int age; + + People(String first, String last, int age) { + firstName = first; + lastName = last; + this.age = age; + } + + String getFirstName() { return firstName; } + String getLastName() { return lastName; } + int getAge() { return age; } + } + + private final People people[] = { + new People("John", "Doe", 34), + new People("Mary", "Doe", 30), + }; + + public void testKVComparators() { + // Comparator cmp = Comparator.naturalOrder(); // Should fail to compiler as People is not comparable + // We can use simple comparator, but those have been tested above. + // Thus choose to do compose for some level of interation. + Comparator cmp1 = Comparator.comparing((Function) People::getFirstName); + Comparator cmp2 = Comparator.comparing((Function) People::getLastName); + Comparator cmp = cmp1.thenComparing(cmp2); + + assertPairComparison(people[0], people[0], people[1], people[1], + Map.Entry.comparingByKey(cmp), + Map.Entry.comparingByValue(cmp)); + + } + + public void testNulls() { + try { + Comparator> cmp = Map.Entry.comparingByKey(null); + fail("comparingByKey(null) should throw NPE"); + } catch (NullPointerException npe) {} + + try { + Comparator> cmp = Map.Entry.comparingByValue(null); + fail("comparingByValue(null) should throw NPE"); + } catch (NullPointerException npe) {} + } +} diff --git a/test/java/util/Properties/Bug6609431.java b/test/java/util/Properties/Bug6609431.java new file mode 100644 index 0000000000000000000000000000000000000000..a1232f1fd4378ba9158226fc455693ed1433863a --- /dev/null +++ b/test/java/util/Properties/Bug6609431.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/* + * @test + * @bug 6609431 + * @summary Test whether loading of a property value in a file ending with + * a backslash works fine. + */ + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.Properties; + +public class Bug6609431 { + private static final String expected = "backslash"; + + public static void main(String[] args) throws IOException { + try (FileReader fr = + new FileReader(new File(System.getProperty("test.src", "."), + "Bug6609431.properties"))) { + Properties p = new Properties(); + p.load(fr); + p.getProperty("a"); + String val = p.getProperty("b"); + if (!val.equals(expected)) { + throw new RuntimeException("Value returned from the property" + + " list was incorrect. Returned: '" + val + + "', expected: '" + expected + "'"); + } + } + } +} diff --git a/test/java/util/Properties/Bug6609431.properties b/test/java/util/Properties/Bug6609431.properties new file mode 100644 index 0000000000000000000000000000000000000000..59f35f43823f51fbe61ee9a99a7420738f8bc12d --- /dev/null +++ b/test/java/util/Properties/Bug6609431.properties @@ -0,0 +1,24 @@ +# +# Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# +a=backslashbackslash +b=backslash\ diff --git a/test/java/util/function/BinaryOperator/BasicTest.java b/test/java/util/function/BinaryOperator/BasicTest.java new file mode 100644 index 0000000000000000000000000000000000000000..1519fb88177dca7719ba60e371eeef80e24d5a23 --- /dev/null +++ b/test/java/util/function/BinaryOperator/BasicTest.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8009736 8010279 + * @run testng BasicTest + */ + +import java.util.Comparator; +import java.util.function.BinaryOperator; +import java.util.function.Function; +import java.util.function.ToIntFunction; +import org.testng.annotations.Test; + + +import static java.util.function.BinaryOperator.minBy; +import static java.util.function.BinaryOperator.maxBy; +import static org.testng.Assert.assertSame; +import static org.testng.Assert.fail; + +/** + * Unit tests for helper methods in Comparators + */ +@Test(groups = "unit") +public class BasicTest { + + private static class People { + final String firstName; + final String lastName; + final int age; + + People(String first, String last, int age) { + firstName = first; + lastName = last; + this.age = age; + } + + String getFirstName() { return firstName; } + String getLastName() { return lastName; } + int getAge() { return age; } + } + + private final People people[] = { + new People("John", "Doe", 34), + new People("Mary", "Doe", 30), + }; + + public void testMaxBy() { + Comparator cmp = Comparator.comparing((Function) People::getFirstName); + // lesser + assertSame(maxBy(cmp).apply(people[0], people[1]), people[1]); + // euqal + cmp = Comparator.comparing((Function) People::getLastName); + assertSame(maxBy(cmp).apply(people[0], people[1]), people[0]); + // greater + cmp = Comparator.comparing((ToIntFunction) People::getAge); + assertSame(maxBy(cmp).apply(people[0], people[1]), people[0]); + } + + public void testLesserOf() { + Comparator cmp = Comparator.comparing((Function) People::getFirstName); + // lesser + assertSame(minBy(cmp).apply(people[0], people[1]), people[0]); + // euqal + cmp = Comparator.comparing((Function) People::getLastName); + assertSame(minBy(cmp).apply(people[0], people[1]), people[0]); + // greater + cmp = Comparator.comparing((ToIntFunction) People::getAge); + assertSame(minBy(cmp).apply(people[0], people[1]), people[1]); + } + + public void testNulls() { + try { + BinaryOperator op = minBy(null); + fail("minBy(null) should throw NPE"); + } catch (NullPointerException npe) {} + + try { + BinaryOperator op = maxBy(null); + fail("maxBy(null) should throw NPE"); + } catch (NullPointerException npe) {} + } +} diff --git a/test/java/util/logging/LogManagerInstanceTest.java b/test/java/util/logging/LogManagerInstanceTest.java index 3d3714d56566f7849a925d608ff00c96a8d0d30f..c6fbe1e56d7f46496a2c3b7fcaf379898ced4788 100644 --- a/test/java/util/logging/LogManagerInstanceTest.java +++ b/test/java/util/logging/LogManagerInstanceTest.java @@ -63,7 +63,7 @@ public class LogManagerInstanceTest { if (!super.addLogger(root)) throw new RuntimeException("Fail to addLogger " + root); } else { - System.out.println("Root logger already exists"); + throw new RuntimeException("Root logger already exists"); } this.base = root; } diff --git a/test/java/util/logging/Logger/getGlobal/TestGetGlobal.java b/test/java/util/logging/Logger/getGlobal/TestGetGlobal.java new file mode 100644 index 0000000000000000000000000000000000000000..dd901ed5f92ac9a7e0d9086db460aae3b304e6c4 --- /dev/null +++ b/test/java/util/logging/Logger/getGlobal/TestGetGlobal.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import java.util.Arrays; +import java.util.List; +import java.util.logging.Logger; + +/** + * @test + * @bug 7184195 + * @summary checks that java.util.logging.Logger.getGlobal().info() logs without configuration + * @build TestGetGlobal testgetglobal.HandlerImpl testgetglobal.LogManagerImpl1 testgetglobal.LogManagerImpl2 testgetglobal.LogManagerImpl3 testgetglobal.BadLogManagerImpl testgetglobal.DummyLogManagerImpl + * @run main/othervm/timeout=10 TestGetGlobal + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager TestGetGlobal + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.LogManagerImpl1 TestGetGlobal + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.LogManagerImpl1 TestGetGlobal + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.LogManagerImpl2 TestGetGlobal + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.LogManagerImpl2 TestGetGlobal + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.LogManagerImpl3 TestGetGlobal + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.LogManagerImpl3 TestGetGlobal + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.BadLogManagerImpl TestGetGlobal + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.BadLogManagerImpl TestGetGlobal + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.DummyLogManagerImpl TestGetGlobal + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.DummyLogManagerImpl TestGetGlobal + * @author danielfuchs + */ +public class TestGetGlobal { + + final static String[] messages = { + "1. This message should not appear on the console.", + "2. This message should appear on the console.", + "3. This message should now appear on the console too." + }; + + static { + System.setProperty("java.util.logging.config.file", + System.getProperty("test.src", ".") + java.io.File.separator + "logging.properties"); + } + + public static void main(String... args) { + + Logger.global.info(messages[0]); // at this point LogManager is not + // initialized yet, so this message should not appear. + Logger.getGlobal().info(messages[1]); // calling getGlobal() will + // initialize the LogManager - and thus this message should appear. + Logger.global.info(messages[2]); // Now that the LogManager is + // initialized, this message should appear too. + + final List expected = Arrays.asList(Arrays.copyOfRange(messages, 1, messages.length)); + if (!testgetglobal.HandlerImpl.received.equals(expected)) { + throw new Error("Unexpected message list: "+testgetglobal.HandlerImpl.received+" vs "+ expected); + } + } +} diff --git a/test/java/util/logging/Logger/getGlobal/TestGetGlobalByName.java b/test/java/util/logging/Logger/getGlobal/TestGetGlobalByName.java new file mode 100644 index 0000000000000000000000000000000000000000..62580a8bc3bf2f77ea6f7fc8b38f353b23826489 --- /dev/null +++ b/test/java/util/logging/Logger/getGlobal/TestGetGlobalByName.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import java.util.Arrays; +import java.util.List; +import java.util.logging.Logger; + +/** + * @test + * @bug 7184195 + * @summary checks that java.util.logging.Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info() logs without configuration + * @build TestGetGlobalByName testgetglobal.HandlerImpl testgetglobal.LogManagerImpl1 testgetglobal.LogManagerImpl2 testgetglobal.LogManagerImpl3 testgetglobal.BadLogManagerImpl testgetglobal.DummyLogManagerImpl + * @run main/othervm/timeout=10 TestGetGlobalByName + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager TestGetGlobalByName + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.LogManagerImpl1 TestGetGlobalByName + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.LogManagerImpl TestGetGlobalByName + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.LogManagerImpl2 TestGetGlobalByName + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.LogManagerImpl2 TestGetGlobalByName + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.LogManagerImpl3 TestGetGlobalByName + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.LogManagerImpl3 TestGetGlobalByName + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.BadLogManagerImpl TestGetGlobalByName + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.BadLogManagerImpl TestGetGlobalByName + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.DummyLogManagerImpl TestGetGlobalByName + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.DummyLogManagerImpl TestGetGlobalByName + * @author danielfuchs + */ +public class TestGetGlobalByName { + + final static String[] messages = { + "1. This message should not appear on the console.", + "2. This message should appear on the console.", + "3. This message should now appear on the console too." + }; + + static { + System.setProperty("java.util.logging.config.file", + System.getProperty("test.src", ".") + java.io.File.separator + "logging.properties"); + } + + public static void main(String... args) { + + Logger.global.info(messages[0]); // at this point LogManager is not + // initialized yet, so this message should not appear. + Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(messages[1]); // calling getLogger() will + // initialize the LogManager - and thus this message should appear. + Logger.global.info(messages[2]); // Now that the LogManager is + // initialized, this message should appear too. + + final List expected = Arrays.asList(Arrays.copyOfRange(messages, 1, messages.length)); + if (!testgetglobal.HandlerImpl.received.equals(expected)) { + throw new Error("Unexpected message list: "+testgetglobal.HandlerImpl.received+" vs "+ expected); + } + } +} diff --git a/test/java/util/logging/Logger/getGlobal/TestGetGlobalConcurrent.java b/test/java/util/logging/Logger/getGlobal/TestGetGlobalConcurrent.java new file mode 100644 index 0000000000000000000000000000000000000000..4ef38ce36116e66122ade5cb3a968bfd756e822c --- /dev/null +++ b/test/java/util/logging/Logger/getGlobal/TestGetGlobalConcurrent.java @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import java.util.Arrays; +import java.util.List; +import java.util.logging.Logger; + +/** + * @test + * @bug 7184195 + * @summary checks that java.util.logging.Logger.getGlobal().info() logs without configuration + * @build TestGetGlobalConcurrent testgetglobal.HandlerImpl testgetglobal.LogManagerImpl1 testgetglobal.LogManagerImpl2 testgetglobal.LogManagerImpl3 testgetglobal.BadLogManagerImpl testgetglobal.DummyLogManagerImpl + * @run main/othervm/timeout=10 TestGetGlobalConcurrent + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager TestGetGlobalConcurrent + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.LogManagerImpl TestGetGlobalConcurrent + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.LogManagerImpl TestGetGlobalConcurrent + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.LogManagerImpl2 TestGetGlobalConcurrent + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.LogManagerImpl2 TestGetGlobalConcurrent + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.LogManagerImpl3 TestGetGlobalConcurrent + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.LogManagerImpl3 TestGetGlobalConcurrent + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.BadLogManagerImpl TestGetGlobalConcurrent + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.BadLogManagerImpl TestGetGlobalConcurrent + * @run main/othervm/timeout=10 -Djava.util.logging.manager=testgetglobal.DummyLogManagerImpl TestGetGlobalConcurrent + * @run main/othervm/timeout=10/policy=policy -Djava.security.manager -Djava.util.logging.manager=testgetglobal.DummyLogManagerImpl TestGetGlobalConcurrent + * @author danielfuchs + */ +public class TestGetGlobalConcurrent { + + final static String[] messages = { + "1. This message should not appear on the console.", + "2. This message should appear on the console.", + "3. This message should now appear on the console too.", + "4. This message should appear on the console.", + "5. This message should now appear on the console too.", + "6. This message should appear on the console.", + "7. This message should now appear on the console too.", + "8. This message should appear on the console.", + "9. This message should now appear on the console too." + }; + + static { + System.setProperty("java.util.logging.config.file", + System.getProperty("test.src", ".") + java.io.File.separator + "logging.properties"); + } + + public static void test1() { + final int nb = 1; + final int i = 2*nb + 1; + Logger.getGlobal().info(messages[i]); // calling getGlobal() will + // initialize the LogManager - and thus this message should appear. + Logger.global.info(messages[i+1]); // Now that the LogManager is + // initialized, this message should appear too. + + final List expected = Arrays.asList(Arrays.copyOfRange(messages, i, i+2)); + if (!testgetglobal.HandlerImpl.received.containsAll(expected)) { + fail(new Error("Unexpected message list: "+testgetglobal.HandlerImpl.received+" vs "+ expected)); + } + } + public static void test2() { + final int nb = 2; + final int i = 2*nb + 1; + Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(messages[i]); // calling getGlobal() will + // initialize the LogManager - and thus this message should appear. + Logger.global.info(messages[i+1]); // Now that the LogManager is + // initialized, this message should appear too. + + final List expected = Arrays.asList(Arrays.copyOfRange(messages, i, i+2)); + if (!testgetglobal.HandlerImpl.received.containsAll(expected)) { + fail(new Error("Unexpected message list: "+testgetglobal.HandlerImpl.received+" vs "+ expected)); + } + } + public static void test3() { + final int nb = 3; + final int i = 2*nb + 1; + java.util.logging.LogManager.getLogManager(); + Logger.getGlobal().info(messages[i]); // calling getGlobal() will + // initialize the LogManager - and thus this message should appear. + Logger.global.info(messages[i+1]); // Now that the LogManager is + // initialized, this message should appear too. + + final List expected = Arrays.asList(Arrays.copyOfRange(messages, i, i+2)); + if (!testgetglobal.HandlerImpl.received.containsAll(expected)) { + fail(new Error("Unexpected message list: "+testgetglobal.HandlerImpl.received+" vs "+ expected)); + } + } + public static void test4() { + log = new MyLogger("foo.bar"); + java.util.logging.LogManager.getLogManager().addLogger(log); + } + + + private static volatile Throwable failed = null; + private static volatile Logger log = null; + + public static class MyLogger extends Logger { + public MyLogger(String name) { + super(name, null); + } + } + + public static void fail(Throwable failure) { + failure.printStackTrace(); + if (failed == null) failed = failure; + } + + public static class WaitAndRun implements Runnable { + private final Runnable run; + public WaitAndRun(Runnable run) { + this.run = run; + } + public void run() { + try { + Thread.sleep(10); + run.run(); + } catch (Exception | Error x) { + fail(x); + } + } + } + + final static class Run1 implements Runnable { + public void run() { test1(); } + } + final static class Run2 implements Runnable { + public void run() { test2(); } + } + final static class Run3 implements Runnable { + public void run() { test3(); } + } + final static class Run4 implements Runnable { + public void run() { test4(); } + } + + public static void main(String... args) throws Exception { + + final Thread t1 = new Thread(new WaitAndRun(new Run1()), "test1"); + final Thread t2 = new Thread(new WaitAndRun(new Run2()), "test2"); + final Thread t3 = new Thread(new WaitAndRun(new Run3()), "test3"); + final Thread t4 = new Thread(new WaitAndRun(new Run4()), "test4"); + + t1.setDaemon(true); t2.setDaemon(true); t3.setDaemon(true); t4.setDaemon(true); + t1.start(); t2.start(); t3.start(); t4.start(); + + Thread.sleep(10); + + Logger.getGlobal().info(messages[1]); // calling getGlobal() will + // initialize the LogManager - and thus this message should appear. + Logger.global.info(messages[2]); // Now that the LogManager is + // initialized, this message should appear too. + + final List expected = Arrays.asList(Arrays.copyOfRange(messages, 1, 3)); + if (!testgetglobal.HandlerImpl.received.containsAll(expected)) { + throw new Error("Unexpected message list: "+testgetglobal.HandlerImpl.received+" vs "+ expected); + } + + + t1.join(); t2.join(); t3.join(); t4.join(); + + if (failed != null) { + throw new Error("Test failed.", failed); + } + + System.out.println("Test passed"); + } +} diff --git a/test/java/util/logging/Logger/getGlobal/logging.properties b/test/java/util/logging/Logger/getGlobal/logging.properties new file mode 100644 index 0000000000000000000000000000000000000000..0e201a9c60ce0e0716ce4ce179fb52d550ff720d --- /dev/null +++ b/test/java/util/logging/Logger/getGlobal/logging.properties @@ -0,0 +1,2 @@ +.level=INFO +handlers=testgetglobal.HandlerImpl diff --git a/test/java/util/logging/Logger/getGlobal/policy b/test/java/util/logging/Logger/getGlobal/policy new file mode 100644 index 0000000000000000000000000000000000000000..bcb7cde0da364e180b1cb3c64a36484feb7a02fe --- /dev/null +++ b/test/java/util/logging/Logger/getGlobal/policy @@ -0,0 +1,7 @@ +grant { + permission java.util.PropertyPermission "java.util.logging.config.file", "write"; + permission java.util.PropertyPermission "test.src", "read"; + permission java.lang.RuntimePermission "setContextClassLoader"; + permission java.lang.RuntimePermission "shutdownHooks"; + permission java.util.logging.LoggingPermission "control"; +}; diff --git a/test/java/util/logging/Logger/getGlobal/testgetglobal/BadLogManagerImpl.java b/test/java/util/logging/Logger/getGlobal/testgetglobal/BadLogManagerImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..e3fd771ffd763b0e362066bd6605e8ccb514b938 --- /dev/null +++ b/test/java/util/logging/Logger/getGlobal/testgetglobal/BadLogManagerImpl.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package testgetglobal; + +import java.util.logging.LogManager; +import java.util.logging.Logger; + +/** + * This class is used to verify that calling Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) + * in the constructor of a LogManager subclass installed as default + * LogManager does not cause issues beyond throwing the expected NPE. + * In that case the default LogManager class will simply be used. + * @author danielfuchs + */ +public class BadLogManagerImpl extends LogManager { + + final Logger globalLogger; + public BadLogManagerImpl() { + // The call below should generate an NPE, which will be + // catched in LogManager initializer. + globalLogger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + System.err.println("Global is: " + globalLogger); + throw new Error("Should not have reached here"); + } + +} diff --git a/test/java/util/logging/Logger/getGlobal/testgetglobal/DummyLogManagerImpl.java b/test/java/util/logging/Logger/getGlobal/testgetglobal/DummyLogManagerImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..e3a48372fa729b665b9aa9d6b8210637f8ee146e --- /dev/null +++ b/test/java/util/logging/Logger/getGlobal/testgetglobal/DummyLogManagerImpl.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package testgetglobal; + +import java.util.logging.LogManager; +import java.util.logging.Logger; + +/** + * A dummy LogManager subclass that does nothing beyond extending LogManager. + * @author danielfuchs + */ +public class DummyLogManagerImpl extends LogManager { + + +} diff --git a/test/java/util/logging/Logger/getGlobal/testgetglobal/HandlerImpl.java b/test/java/util/logging/Logger/getGlobal/testgetglobal/HandlerImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..f8737acb25f47a905019870b938b1c18cfbf6b58 --- /dev/null +++ b/test/java/util/logging/Logger/getGlobal/testgetglobal/HandlerImpl.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package testgetglobal; + +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.List; +import java.util.logging.ConsoleHandler; +import java.util.logging.LogRecord; + +/** + * + * @author danielfuchs + */ +public class HandlerImpl extends ConsoleHandler { + + public final static List received = new CopyOnWriteArrayList<>(); + + public HandlerImpl() { + } + + @Override + public void publish(LogRecord record) { + received.add(record.getMessage()); + super.publish(record); + } +} diff --git a/test/java/util/logging/Logger/getGlobal/testgetglobal/LogManagerImpl1.java b/test/java/util/logging/Logger/getGlobal/testgetglobal/LogManagerImpl1.java new file mode 100644 index 0000000000000000000000000000000000000000..9f3f6432a58cec4907028b2ad1ea40c8ca395715 --- /dev/null +++ b/test/java/util/logging/Logger/getGlobal/testgetglobal/LogManagerImpl1.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package testgetglobal; + +import java.util.logging.LogManager; +import java.util.logging.Logger; + +/** + * This class is used to verify that calling Logger.getGlobal() in the static + * initializer of a LogManager subclass installed as default LogManager + * does not cause issues. + * @author danielfuchs + */ +public class LogManagerImpl1 extends LogManager { + + static final Logger global; + static { + global = Logger.getGlobal(); + System.err.println("Global is: " + global); + } + +} diff --git a/test/java/util/logging/Logger/getGlobal/testgetglobal/LogManagerImpl2.java b/test/java/util/logging/Logger/getGlobal/testgetglobal/LogManagerImpl2.java new file mode 100644 index 0000000000000000000000000000000000000000..dd9d7aeca7ffc4b6a1d4876bce8af0df5dc3fb71 --- /dev/null +++ b/test/java/util/logging/Logger/getGlobal/testgetglobal/LogManagerImpl2.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package testgetglobal; + +import java.util.logging.LogManager; +import java.util.logging.Logger; + +/** + * This class is used to verify that calling Logger.getGlobal() in the constructor + * initializer of a LogManager subclass installed as default LogManager + * does not cause issues. + * @author danielfuchs + */ +public class LogManagerImpl2 extends LogManager { + + final Logger globalLogger; + public LogManagerImpl2() { + globalLogger = Logger.getGlobal(); + System.err.println("Global is: " + globalLogger); + } + +} diff --git a/test/java/util/logging/Logger/getGlobal/testgetglobal/LogManagerImpl3.java b/test/java/util/logging/Logger/getGlobal/testgetglobal/LogManagerImpl3.java new file mode 100644 index 0000000000000000000000000000000000000000..f5ce01cd90dcb01b18f4b9ec3b029f804260932a --- /dev/null +++ b/test/java/util/logging/Logger/getGlobal/testgetglobal/LogManagerImpl3.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package testgetglobal; + +import java.util.logging.LogManager; +import java.util.logging.Logger; + +/** + * This class is used to verify that calling Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) + * in the static initializer of a LogManager subclass installed as default + * LogManager does not cause issues beyond throwing the expected NPE. + * @author danielfuchs + */ +public class LogManagerImpl3 extends LogManager { + + static final Logger global; + static { + Logger g = null; + try { + g = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + throw new Error("Should not have reached here"); + } catch (Exception x) { + // This is to be expected: Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) + // will call LogManager.getLogManager() which will return null, since + // we haven't manage to do new LogManagerImpl3() yet. + // + System.err.println("Got expected exception - you cannot call" + + " Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)" + + " in LogManager subclass static initializer: " + x); + x.printStackTrace(); + } + if (g == null) { + g = Logger.getGlobal(); + } + global = g; + System.err.println("Global is: " + global); + } + +} diff --git a/test/java/util/logging/TestAppletLoggerContext.java b/test/java/util/logging/TestAppletLoggerContext.java new file mode 100644 index 0000000000000000000000000000000000000000..c7f3d4f49911c2d98400177610a4ca97e491e25a --- /dev/null +++ b/test/java/util/logging/TestAppletLoggerContext.java @@ -0,0 +1,610 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.security.CodeSource; +import java.security.Permission; +import java.security.PermissionCollection; +import java.security.Permissions; +import java.security.Policy; +import java.security.ProtectionDomain; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.LogManager; +import java.util.logging.Logger; +import java.util.logging.LoggingPermission; +import sun.misc.JavaAWTAccess; +import sun.misc.SharedSecrets; + +/* + * @test + * @bug 8017174 8010727 + * @summary NPE when using Logger.getAnonymousLogger or + * LogManager.getLogManager().getLogger + * + * @run main/othervm -Dtest.security=off TestAppletLoggerContext LoadingApplet + * @run main/othervm -Dtest.security=on TestAppletLoggerContext LoadingApplet + * @run main/othervm -Dtest.security=off TestAppletLoggerContext LoadingMain + * @run main/othervm -Dtest.security=on TestAppletLoggerContext LoadingMain + * @run main/othervm -Dtest.security=off TestAppletLoggerContext One + * @run main/othervm -Dtest.security=on TestAppletLoggerContext One + * @run main/othervm -Dtest.security=off TestAppletLoggerContext Two + * @run main/othervm -Dtest.security=on TestAppletLoggerContext Two + * @run main/othervm -Dtest.security=off TestAppletLoggerContext Three + * @run main/othervm -Dtest.security=on TestAppletLoggerContext Three + * @run main/othervm -Dtest.security=off TestAppletLoggerContext Four + * @run main/othervm -Dtest.security=on TestAppletLoggerContext Four + * @run main/othervm -Dtest.security=off TestAppletLoggerContext Five + * @run main/othervm -Dtest.security=on TestAppletLoggerContext Five + * @run main/othervm -Dtest.security=off TestAppletLoggerContext Six + * @run main/othervm -Dtest.security=on TestAppletLoggerContext Six + * @run main/othervm -Dtest.security=off TestAppletLoggerContext Seven + * @run main/othervm -Dtest.security=on TestAppletLoggerContext Seven + * @run main/othervm -Dtest.security=off TestAppletLoggerContext + * @run main/othervm -Dtest.security=on TestAppletLoggerContext + */ + +// NOTE: We run in other VM in order to 1. switch security manager and 2. cause +// LogManager class to be loaded anew. +public class TestAppletLoggerContext { + + // Avoids the hassle of dealing with files and system props... + static class SimplePolicy extends Policy { + private final Permissions perms; + public SimplePolicy(Permission... permissions) { + perms = new Permissions(); + for (Permission permission : permissions) { + perms.add(permission); + } + } + @Override + public PermissionCollection getPermissions(CodeSource cs) { + return perms; + } + @Override + public PermissionCollection getPermissions(ProtectionDomain pd) { + return perms; + } + @Override + public boolean implies(ProtectionDomain pd, Permission p) { + return perms.implies(p); + } + } + + // The bridge class initializes the logging system. + // It stubs the applet context in order to simulate context changes. + // + public static class Bridge { + + private static class JavaAWTAccessStub implements JavaAWTAccess { + boolean active = true; + + private static class TestExc { + private final Map map = new HashMap<>(); + void put(Object key, Object v) { map.put(key, v); } + Object get(Object key) { return map.get(key); } + void remove(Object o) { map.remove(o); } + public static TestExc exc(Object o) { + return TestExc.class.cast(o); + } + } + + TestExc exc; + TestExc global = new TestExc(); + + @Override + public Object getContext() { return active ? global : null; } + @Override + public Object getExecutionContext() { return active ? exc : null; } + @Override + public Object get(Object o, Object o1) { return TestExc.exc(o).get(o1); } + @Override + public void put(Object o, Object o1, Object o2) { TestExc.exc(o).put(o1, o2); } + @Override + public void remove(Object o, Object o1) { TestExc.exc(o).remove(o1); } + @Override + public Object get(Object o) { return global.get(o); } + @Override + public void put(Object o, Object o1) { global.put(o, o1); } + @Override + public void remove(Object o) { global.remove(o); } + @Override + public boolean isDisposed() { return false; } + @Override + public boolean isMainAppContext() { return exc == null; } + } + + final static JavaAWTAccessStub javaAwtAccess = new JavaAWTAccessStub(); + public static void init() { + SharedSecrets.setJavaAWTAccess(javaAwtAccess); + if (System.getProperty("test.security", "on").equals("on")) { + Policy p = new SimplePolicy(new LoggingPermission("control", null), + new RuntimePermission("setContextClassLoader"), + new RuntimePermission("shutdownHooks")); + Policy.setPolicy(p); + System.setSecurityManager(new SecurityManager()); + } + } + + public static void changeContext() { + System.out.println("... Switching to a new applet context ..."); + javaAwtAccess.active = true; + javaAwtAccess.exc = new JavaAWTAccessStub.TestExc(); + } + + public static void desactivate() { + System.out.println("... Running with no applet context ..."); + javaAwtAccess.exc = null; + javaAwtAccess.active = false; + } + + public static class CustomAnonymousLogger extends Logger { + public CustomAnonymousLogger() { + this(""); + } + public CustomAnonymousLogger(String name) { + super(null, null); + System.out.println( " LogManager: " +LogManager.getLogManager()); + System.out.println( " getLogger: " +LogManager.getLogManager().getLogger(name)); + setParent(LogManager.getLogManager().getLogger(name)); + } + } + + public static class CustomLogger extends Logger { + CustomLogger(String name) { + super(name, null); + } + } + } + + public static enum TestCase { + LoadingApplet, LoadingMain, One, Two, Three, Four, Five, Six, Seven; + public void test() { + switch(this) { + // When run - each of these two tests must be + // run before any other tests and before each other. + case LoadingApplet: testLoadingApplet(); break; + case LoadingMain: testLoadingMain(); break; + case One: testOne(); break; + case Two: testTwo(); break; + case Three: testThree(); break; + case Four: testFour(); break; + case Five: testFive(); break; + case Six: testSix(); break; + case Seven: testSeven(); break; + } + } + public String describe() { + switch(this) { + case LoadingApplet: + return "Test that when the LogManager class is" + + " loaded in an applet thread first," + + "\n all LoggerContexts are correctly initialized"; + case LoadingMain: + return "Test that when the LogManager class is" + + " loaded in the main thread first," + + "\n all LoggerContexts are correctly initialized"; + case One: + return "Test that Logger.getAnonymousLogger()" + + " and new CustomAnonymousLogger() don't throw NPE"; + case Two: + return "Test that Logger.getLogger(\"\")" + + " does not return null nor throws NPE"; + case Three: + return "Test that LogManager.getLogManager().getLogger(\"\")" + + " does not return null nor throws NPE"; + case Four: + return "Test that Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)" + + " does not return null,\n and that" + + " new CustomAnonymousLogger(Logger.GLOBAL_LOGGER_NAME)" + + " does not throw NPE"; + case Five: + return "Test that LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME)" + + "\n does not return null nor throws NPE"; + case Six: + return "Test that manager.getLogger(Logger.GLOBAL_LOGGER_NAME)" + + " returns null\n when manager is not the default" + + " LogManager instance.\n" + + "Test adding a new logger named \"global\" in that" + + " non default instance."; + case Seven: return "Test that manager.getLogger(\"\")" + + " returns null\n when manager is not the default" + + " LogManager instance.\n" + + "Test adding a new logger named \"\" in that" + + " non default instance."; + default: return "Undefined"; + } + } + }; + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + Bridge.init(); + EnumSet tests = EnumSet.noneOf(TestCase.class); + for (String arg : args) { + tests.add(TestCase.valueOf(arg)); + } + if (args.length == 0) { + tests = EnumSet.complementOf(EnumSet.of(TestCase.LoadingMain)); + } + final EnumSet loadingTests = + EnumSet.of(TestCase.LoadingApplet, TestCase.LoadingMain); + int testrun = 0; + for (TestCase test : tests) { + if (loadingTests.contains(test)) { + if (testrun > 0) { + throw new UnsupportedOperationException("Test case " + + test + " must be executed first!"); + } + } + System.out.println("Testing "+ test+": "); + System.out.println(test.describe()); + try { + test.test(); + } catch (Exception x) { + throw new Error(String.valueOf(test) + + (System.getSecurityManager() == null ? " without " : " with ") + + "security failed: "+x+"\n "+"FAILED: "+test.describe()+"\n", x); + } finally { + testrun++; + } + Bridge.changeContext(); + System.out.println("PASSED: "+ test); + } + } + + public static void testLoadingApplet() { + Bridge.changeContext(); + + Logger bar = new Bridge.CustomLogger("com.foo.Bar"); + LogManager.getLogManager().addLogger(bar); + assertNotNull(bar.getParent()); + testParent(bar); + testParent(LogManager.getLogManager().getLogger("global")); + testParent(LogManager.getLogManager().getLogger(bar.getName())); + + Bridge.desactivate(); + + Logger foo = new Bridge.CustomLogger("com.foo.Foo"); + boolean b = LogManager.getLogManager().addLogger(foo); + assertEquals(Boolean.TRUE, Boolean.valueOf(b)); + assertNotNull(foo.getParent()); + testParent(foo); + testParent(LogManager.getLogManager().getLogger("global")); + testParent(LogManager.getLogManager().getLogger(foo.getName())); + } + + public static void testLoadingMain() { + Bridge.desactivate(); + + Logger bar = new Bridge.CustomLogger("com.foo.Bar"); + LogManager.getLogManager().addLogger(bar); + assertNotNull(bar.getParent()); + testParent(bar); + testParent(LogManager.getLogManager().getLogger("global")); + testParent(LogManager.getLogManager().getLogger(bar.getName())); + + Bridge.changeContext(); + + Logger foo = new Bridge.CustomLogger("com.foo.Foo"); + boolean b = LogManager.getLogManager().addLogger(foo); + assertEquals(Boolean.TRUE, Boolean.valueOf(b)); + assertNotNull(foo.getParent()); + testParent(foo); + testParent(LogManager.getLogManager().getLogger("global")); + testParent(LogManager.getLogManager().getLogger(foo.getName())); + + } + + public static void testOne() { + for (int i=0; i<3 ; i++) { + Logger logger1 = Logger.getAnonymousLogger(); + Logger logger1b = Logger.getAnonymousLogger(); + Bridge.changeContext(); + Logger logger2 = Logger.getAnonymousLogger(); + Logger logger2b = Logger.getAnonymousLogger(); + Bridge.changeContext(); + Logger logger3 = new Bridge.CustomAnonymousLogger(); + Logger logger3b = new Bridge.CustomAnonymousLogger(); + Bridge.changeContext(); + Logger logger4 = new Bridge.CustomAnonymousLogger(); + Logger logger4b = new Bridge.CustomAnonymousLogger(); + } + } + + + public static void testTwo() { + for (int i=0; i<3 ; i++) { + Logger logger1 = Logger.getLogger(""); + Logger logger1b = Logger.getLogger(""); + assertNotNull(logger1); + assertNotNull(logger1b); + assertEquals(logger1, logger1b); + Bridge.changeContext(); + Logger logger2 = Logger.getLogger(""); + Logger logger2b = Logger.getLogger(""); + assertNotNull(logger2); + assertNotNull(logger2b); + assertEquals(logger2, logger2b); + assertEquals(logger1, logger2); + } + } + + public static void testThree() { + for (int i=0; i<3 ; i++) { + Logger logger1 = LogManager.getLogManager().getLogger(""); + Logger logger1b = LogManager.getLogManager().getLogger(""); + assertNotNull(logger1); + assertNotNull(logger1b); + assertEquals(logger1, logger1b); + Bridge.changeContext(); + Logger logger2 = LogManager.getLogManager().getLogger(""); + Logger logger2b = LogManager.getLogManager().getLogger(""); + assertNotNull(logger2); + assertNotNull(logger2b); + assertEquals(logger2, logger2b); + assertEquals(logger1, logger2); + } + } + + public static void testFour() { + for (int i=0; i<3 ; i++) { + Logger logger1 = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + Logger logger1b = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + assertNotNull(logger1); + assertNotNull(logger1b); + assertEquals(logger1, logger1b); + Bridge.changeContext(); + + Logger logger2 = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + Logger logger2b = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + assertNotNull(logger2); + assertNotNull(logger2b); + assertEquals(logger2, logger2b); + + assertEquals(logger1, logger2); + + Bridge.changeContext(); + Logger logger3 = new Bridge.CustomAnonymousLogger(Logger.GLOBAL_LOGGER_NAME); + Logger logger3b = new Bridge.CustomAnonymousLogger(Logger.GLOBAL_LOGGER_NAME); + Bridge.changeContext(); + Logger logger4 = new Bridge.CustomAnonymousLogger(Logger.GLOBAL_LOGGER_NAME); + Logger logger4b = new Bridge.CustomAnonymousLogger(Logger.GLOBAL_LOGGER_NAME); + } + } + + public static void testFive() { + for (int i=0; i<3 ; i++) { + Logger logger1 = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME); + Logger logger1b = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME); + assertNotNull(logger1); + assertNotNull(logger1b); + assertEquals(logger1, logger1b); + + Bridge.changeContext(); + + Logger logger2 = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME); + Logger logger2b = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME); + assertNotNull(logger2); + assertNotNull(logger2b); + assertEquals(logger2, logger2b); + + assertEquals(logger1, logger2); + } + } + + /** + * This test is designed to test the behavior of additional LogManager instances. + * It must be noted that if the security manager is off, then calling + * Bridge.changeContext() has actually no effect - which explains why we have + * some differences between the cases security manager on & security manager + * off. + **/ + public static void testSix() { + for (int i=0; i<3 ; i++) { + Bridge.desactivate(); + LogManager manager = new LogManager() {}; + Logger logger1 = manager.getLogger(Logger.GLOBAL_LOGGER_NAME); + Logger logger1b = manager.getLogger(Logger.GLOBAL_LOGGER_NAME); + assertNull(logger1); + assertNull(logger1b); + Logger global = new Bridge.CustomLogger(Logger.GLOBAL_LOGGER_NAME); + manager.addLogger(global); + Logger logger2 = manager.getLogger(Logger.GLOBAL_LOGGER_NAME); + Logger logger2b = manager.getLogger(Logger.GLOBAL_LOGGER_NAME); + assertNotNull(logger2); + assertNotNull(logger2b); + assertEquals(logger2, global); + assertEquals(logger2b, global); + assertNull(manager.getLogger("")); + assertNull(manager.getLogger("")); + + Bridge.changeContext(); + + // this is not a supported configuration: + // We are in an applet context with several log managers. + // We however need to check our assumptions... + + // Applet context => root logger and global logger are not null. + // root == LogManager.getLogManager().rootLogger + // global == Logger.global + + Logger logger3 = manager.getLogger(Logger.GLOBAL_LOGGER_NAME); + Logger logger3b = manager.getLogger(Logger.GLOBAL_LOGGER_NAME); + assertNotNull(logger3); + assertNotNull(logger3b); + Logger expected = (System.getSecurityManager() != null + ? Logger.getGlobal() + : global); + assertEquals(logger3, expected); // in applet context, we will not see + // the LogManager's custom global logger added above... + assertEquals(logger3b, expected); // in applet context, we will not see + // the LogManager's custom global logger added above... + Logger global2 = new Bridge.CustomLogger(Logger.GLOBAL_LOGGER_NAME); + manager.addLogger(global2); // adding a global logger will not work in applet context + // we will always get back the global logger. + // this could be considered as a bug... + Logger logger4 = manager.getLogger(Logger.GLOBAL_LOGGER_NAME); + Logger logger4b = manager.getLogger(Logger.GLOBAL_LOGGER_NAME); + assertNotNull(logger4); + assertNotNull(logger4b); + assertEquals(logger4, expected); // adding a global logger will not work in applet context + assertEquals(logger4b, expected); // adding a global logger will not work in applet context + + Logger logger5 = manager.getLogger(""); + Logger logger5b = manager.getLogger(""); + Logger expectedRoot = (System.getSecurityManager() != null + ? LogManager.getLogManager().getLogger("") + : null); + assertEquals(logger5, expectedRoot); + assertEquals(logger5b, expectedRoot); + + } + } + + /** + * This test is designed to test the behavior of additional LogManager instances. + * It must be noted that if the security manager is off, then calling + * Bridge.changeContext() has actually no effect - which explains why we have + * some differences between the cases security manager on & security manager + * off. + **/ + public static void testSeven() { + for (int i=0; i<3 ; i++) { + Bridge.desactivate(); + LogManager manager = new LogManager() {}; + Logger logger1 = manager.getLogger(""); + Logger logger1b = manager.getLogger(""); + assertNull(logger1); + assertNull(logger1b); + Logger global = new Bridge.CustomLogger(Logger.GLOBAL_LOGGER_NAME); + manager.addLogger(global); + Logger logger2 = manager.getLogger(Logger.GLOBAL_LOGGER_NAME); + Logger logger2b = manager.getLogger(Logger.GLOBAL_LOGGER_NAME); + assertNotNull(logger2); + assertNotNull(logger2b); + assertEquals(logger2, global); + assertEquals(logger2b, global); + Logger logger3 = manager.getLogger(""); + Logger logger3b = manager.getLogger(""); + assertNull(logger3); + assertNull(logger3b); + Logger root = new Bridge.CustomLogger(""); + manager.addLogger(root); + Logger logger4 = manager.getLogger(""); + Logger logger4b = manager.getLogger(""); + assertNotNull(logger4); + assertNotNull(logger4b); + assertEquals(logger4, root); + assertEquals(logger4b, root); + + Bridge.changeContext(); + + // this is not a supported configuration: + // We are in an applet context with several log managers. + // We haowever need to check our assumptions... + + // Applet context => root logger and global logger are not null. + // root == LogManager.getLogManager().rootLogger + // global == Logger.global + + Logger logger5 = manager.getLogger(""); + Logger logger5b = manager.getLogger(""); + Logger expectedRoot = (System.getSecurityManager() != null + ? LogManager.getLogManager().getLogger("") + : root); + + assertNotNull(logger5); + assertNotNull(logger5b); + assertEquals(logger5, expectedRoot); + assertEquals(logger5b, expectedRoot); + if (System.getSecurityManager() != null) { + assertNotEquals(logger5, root); + assertNotEquals(logger5b, root); + } + + Logger global2 = new Bridge.CustomLogger(Logger.GLOBAL_LOGGER_NAME); + manager.addLogger(global2); // adding a global logger will not work in applet context + // we will always get back the global logger. + // this could be considered as a bug... + Logger logger6 = manager.getLogger(Logger.GLOBAL_LOGGER_NAME); + Logger logger6b = manager.getLogger(Logger.GLOBAL_LOGGER_NAME); + Logger expectedGlobal = (System.getSecurityManager() != null + ? Logger.getGlobal() + : global); + assertNotNull(logger6); + assertNotNull(logger6b); + assertEquals(logger6, expectedGlobal); // adding a global logger will not work in applet context + assertEquals(logger6b, expectedGlobal); // adding a global logger will not work in applet context + + Logger root2 = new Bridge.CustomLogger(""); + manager.addLogger(root2); // adding a root logger will not work in applet context + // we will always get back the default manager's root logger. + // this could be considered as a bug... + Logger logger7 = manager.getLogger(""); + Logger logger7b = manager.getLogger(""); + assertNotNull(logger7); + assertNotNull(logger7b); + assertEquals(logger7, expectedRoot); // adding a global logger will not work in applet context + assertEquals(logger7b, expectedRoot); // adding a global logger will not work in applet context + assertNotEquals(logger7, root2); + assertNotEquals(logger7b, root2); + } + } + + public static void testParent(Logger logger) { + Logger l = logger; + while (l.getParent() != null) { + l = l.getParent(); + } + assertEquals("", l.getName()); + } + + public static class TestError extends RuntimeException { + public TestError(String msg) { + super(msg); + } + } + + public static void assertNotNull(Object obj) { + if (obj == null) throw new NullPointerException(); + } + + public static void assertNull(Object obj) { + if (obj != null) throw new TestError("Null expected, got "+obj); + } + + public static void assertEquals(Object o1, Object o2) { + if (o1 != o2) { + throw new TestError(o1 + " != " + o2); + } + } + + public static void assertNotEquals(Object o1, Object o2) { + if (o1 == o2) { + throw new TestError(o1 + " == " + o2); + } + } +} diff --git a/test/java/util/stream/bootlib/java/util/stream/OpTestCase.java b/test/java/util/stream/bootlib/java/util/stream/OpTestCase.java index 84a574480b5416b70fa87d606fac356fe561a814..115a37dc6c5b452d606de84d1b4f348108f37605 100644 --- a/test/java/util/stream/bootlib/java/util/stream/OpTestCase.java +++ b/test/java/util/stream/bootlib/java/util/stream/OpTestCase.java @@ -79,11 +79,11 @@ public abstract class OpTestCase extends LoggingTestCase { * test. * * @param actual the actual result - * @param excepted the expected result + * @param expected the expected result * @param isOrdered true if the pipeline is ordered * @param isParallel true if the pipeline is parallel */ - void assertResult(R actual, R excepted, boolean isOrdered, boolean isParallel); + void assertResult(R actual, R expected, boolean isOrdered, boolean isParallel); } // Exercise stream operations diff --git a/test/java/util/stream/bootlib/java/util/stream/SpliteratorTestHelper.java b/test/java/util/stream/bootlib/java/util/stream/SpliteratorTestHelper.java index 7ba82a64616441c0632e99abe6c7558e31497d3a..4d221735315f57327449cb1a78187fc62a3d1580 100644 --- a/test/java/util/stream/bootlib/java/util/stream/SpliteratorTestHelper.java +++ b/test/java/util/stream/bootlib/java/util/stream/SpliteratorTestHelper.java @@ -42,11 +42,33 @@ import static org.testng.Assert.fail; */ public class SpliteratorTestHelper { + public interface ContentAsserter { + void assertContents(Collection actual, Collection expected, boolean isOrdered); + } + + private static ContentAsserter DEFAULT_CONTENT_ASSERTER + = SpliteratorTestHelper::assertContents; + + @SuppressWarnings("unchecked") + private static ContentAsserter defaultContentAsserter() { + return (ContentAsserter) DEFAULT_CONTENT_ASSERTER; + } + public static void testSpliterator(Supplier> supplier) { - testSpliterator(supplier, (Consumer b) -> b); + testSpliterator(supplier, defaultContentAsserter()); + } + + public static void testSpliterator(Supplier> supplier, + ContentAsserter asserter) { + testSpliterator(supplier, (Consumer b) -> b, asserter); } public static void testIntSpliterator(Supplier supplier) { + testIntSpliterator(supplier, defaultContentAsserter()); + } + + public static void testIntSpliterator(Supplier supplier, + ContentAsserter asserter) { class BoxingAdapter implements Consumer, IntConsumer { private final Consumer b; @@ -65,10 +87,15 @@ public class SpliteratorTestHelper { } } - testSpliterator(supplier, BoxingAdapter::new); + testSpliterator(supplier, BoxingAdapter::new, asserter); } public static void testLongSpliterator(Supplier supplier) { + testLongSpliterator(supplier, defaultContentAsserter()); + } + + public static void testLongSpliterator(Supplier supplier, + ContentAsserter asserter) { class BoxingAdapter implements Consumer, LongConsumer { private final Consumer b; @@ -87,10 +114,15 @@ public class SpliteratorTestHelper { } } - testSpliterator(supplier, BoxingAdapter::new); + testSpliterator(supplier, BoxingAdapter::new, asserter); } public static void testDoubleSpliterator(Supplier supplier) { + testDoubleSpliterator(supplier, defaultContentAsserter()); + } + + public static void testDoubleSpliterator(Supplier supplier, + ContentAsserter asserter) { class BoxingAdapter implements Consumer, DoubleConsumer { private final Consumer b; @@ -109,11 +141,12 @@ public class SpliteratorTestHelper { } } - testSpliterator(supplier, BoxingAdapter::new); + testSpliterator(supplier, BoxingAdapter::new, asserter); } static > void testSpliterator(Supplier supplier, - UnaryOperator> boxingAdapter) { + UnaryOperator> boxingAdapter, + ContentAsserter asserter) { ArrayList fromForEach = new ArrayList<>(); Spliterator spliterator = supplier.get(); Consumer addToFromForEach = boxingAdapter.apply(fromForEach::add); @@ -121,14 +154,14 @@ public class SpliteratorTestHelper { Collection exp = Collections.unmodifiableList(fromForEach); - testForEach(exp, supplier, boxingAdapter); - testTryAdvance(exp, supplier, boxingAdapter); - testMixedTryAdvanceForEach(exp, supplier, boxingAdapter); - testMixedTraverseAndSplit(exp, supplier, boxingAdapter); + testForEach(exp, supplier, boxingAdapter, asserter); + testTryAdvance(exp, supplier, boxingAdapter, asserter); + testMixedTryAdvanceForEach(exp, supplier, boxingAdapter, asserter); + testMixedTraverseAndSplit(exp, supplier, boxingAdapter, asserter); testSplitAfterFullTraversal(supplier, boxingAdapter); - testSplitOnce(exp, supplier, boxingAdapter); - testSplitSixDeep(exp, supplier, boxingAdapter); - testSplitUntilNull(exp, supplier, boxingAdapter); + testSplitOnce(exp, supplier, boxingAdapter, asserter); + testSplitSixDeep(exp, supplier, boxingAdapter, asserter); + testSplitUntilNull(exp, supplier, boxingAdapter, asserter); } // @@ -136,7 +169,8 @@ public class SpliteratorTestHelper { private static > void testForEach( Collection exp, Supplier supplier, - UnaryOperator> boxingAdapter) { + UnaryOperator> boxingAdapter, + ContentAsserter asserter) { S spliterator = supplier.get(); long sizeIfKnown = spliterator.getExactSizeIfKnown(); boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED); @@ -159,13 +193,14 @@ public class SpliteratorTestHelper { } assertEquals(fromForEach.size(), exp.size()); - assertContents(fromForEach, exp, isOrdered); + asserter.assertContents(fromForEach, exp, isOrdered); } private static > void testTryAdvance( Collection exp, Supplier supplier, - UnaryOperator> boxingAdapter) { + UnaryOperator> boxingAdapter, + ContentAsserter asserter) { S spliterator = supplier.get(); long sizeIfKnown = spliterator.getExactSizeIfKnown(); boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED); @@ -188,13 +223,14 @@ public class SpliteratorTestHelper { } assertEquals(fromTryAdvance.size(), exp.size()); - assertContents(fromTryAdvance, exp, isOrdered); + asserter.assertContents(fromTryAdvance, exp, isOrdered); } private static > void testMixedTryAdvanceForEach( Collection exp, Supplier supplier, - UnaryOperator> boxingAdapter) { + UnaryOperator> boxingAdapter, + ContentAsserter asserter) { S spliterator = supplier.get(); long sizeIfKnown = spliterator.getExactSizeIfKnown(); boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED); @@ -218,18 +254,14 @@ public class SpliteratorTestHelper { } assertEquals(dest.size(), exp.size()); - if (isOrdered) { - assertEquals(dest, exp); - } - else { - assertContentsUnordered(dest, exp); - } + asserter.assertContents(dest, exp, isOrdered); } private static > void testMixedTraverseAndSplit( Collection exp, Supplier supplier, - UnaryOperator> boxingAdapter) { + UnaryOperator> boxingAdapter, + ContentAsserter asserter) { S spliterator = supplier.get(); long sizeIfKnown = spliterator.getExactSizeIfKnown(); boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED); @@ -266,12 +298,7 @@ public class SpliteratorTestHelper { } assertEquals(dest.size(), exp.size()); - if (isOrdered) { - assertEquals(dest, exp); - } - else { - assertContentsUnordered(dest, exp); - } + asserter.assertContents(dest, exp, isOrdered); } private static > void testSplitAfterFullTraversal( @@ -285,16 +312,14 @@ public class SpliteratorTestHelper { // Full traversal using forEach spliterator = supplier.get(); - spliterator.forEachRemaining(boxingAdapter.apply(e -> { - })); + spliterator.forEachRemaining(boxingAdapter.apply(e -> { })); split = spliterator.trySplit(); assertNull(split); // Full traversal using tryAdvance then forEach spliterator = supplier.get(); spliterator.tryAdvance(boxingAdapter.apply(e -> { })); - spliterator.forEachRemaining(boxingAdapter.apply(e -> { - })); + spliterator.forEachRemaining(boxingAdapter.apply(e -> { })); split = spliterator.trySplit(); assertNull(split); } @@ -302,7 +327,8 @@ public class SpliteratorTestHelper { private static > void testSplitOnce( Collection exp, Supplier supplier, - UnaryOperator> boxingAdapter) { + UnaryOperator> boxingAdapter, + ContentAsserter asserter) { S spliterator = supplier.get(); long sizeIfKnown = spliterator.getExactSizeIfKnown(); boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED); @@ -322,13 +348,15 @@ public class SpliteratorTestHelper { if (s1Size >= 0 && s2Size >= 0) assertEquals(sizeIfKnown, s1Size + s2Size); } - assertContents(fromSplit, exp, isOrdered); + + asserter.assertContents(fromSplit, exp, isOrdered); } private static > void testSplitSixDeep( Collection exp, Supplier supplier, - UnaryOperator> boxingAdapter) { + UnaryOperator> boxingAdapter, + ContentAsserter asserter) { S spliterator = supplier.get(); boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED); @@ -340,13 +368,13 @@ public class SpliteratorTestHelper { // verify splitting with forEach splitSixDeepVisitor(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), false); - assertContents(dest, exp, isOrdered); + asserter.assertContents(dest, exp, isOrdered); // verify splitting with tryAdvance dest.clear(); spliterator = supplier.get(); splitSixDeepVisitor(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), true); - assertContents(dest, exp, isOrdered); + asserter.assertContents(dest, exp, isOrdered); } } @@ -411,7 +439,8 @@ public class SpliteratorTestHelper { private static > void testSplitUntilNull( Collection exp, Supplier supplier, - UnaryOperator> boxingAdapter) { + UnaryOperator> boxingAdapter, + ContentAsserter asserter) { Spliterator s = supplier.get(); boolean isOrdered = s.hasCharacteristics(Spliterator.ORDERED); assertSpliterator(s); @@ -420,7 +449,7 @@ public class SpliteratorTestHelper { Consumer c = boxingAdapter.apply(splits::add); testSplitUntilNull(new SplitNode(c, s)); - assertContents(splits, exp, isOrdered); + asserter.assertContents(splits, exp, isOrdered); } private static class SplitNode { @@ -540,23 +569,10 @@ public class SpliteratorTestHelper { assertEquals(actual, expected); } else { - assertContentsUnordered(actual, expected); + LambdaTestHelpers.assertContentsUnordered(actual, expected); } } - private static void assertContentsUnordered(Iterable actual, Iterable expected) { - assertEquals(toBoxedMultiset(actual), toBoxedMultiset(expected)); - } - - private static Map toBoxedMultiset(Iterable c) { - Map result = new HashMap<>(); - c.forEach(e -> { - if (result.containsKey(e)) result.put(e, result.get(e) + 1); - else result.put(e, 1); - }); - return result; - } - static void mixedTraverseAndSplit(Consumer b, Spliterator splTop) { Spliterator spl1, spl2, spl3; splTop.tryAdvance(b); diff --git a/test/java/util/stream/boottest/java/util/stream/SliceSpliteratorTest.java b/test/java/util/stream/boottest/java/util/stream/SliceSpliteratorTest.java new file mode 100644 index 0000000000000000000000000000000000000000..7aa27bf5b8896d50c0d2e6a35d6ea951b50a3e71 --- /dev/null +++ b/test/java/util/stream/boottest/java/util/stream/SliceSpliteratorTest.java @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package java.util.stream; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Spliterator; + +import static java.util.stream.Collectors.toList; +import static org.testng.Assert.assertEquals; + +/** + * @bug 8012987 + */ +@Test +public class SliceSpliteratorTest extends LoggingTestCase { + + static class UnorderedContentAsserter implements SpliteratorTestHelper.ContentAsserter { + Collection source; + + UnorderedContentAsserter(Collection source) { + this.source = source; + } + + @Override + public void assertContents(Collection actual, Collection expected, boolean isOrdered) { + if (isOrdered) { + assertEquals(actual, expected); + } + else { + assertEquals(actual.size(), expected.size()); + assertTrue(source.containsAll(actual)); + } + } + } + + interface SliceTester { + void test(int size, int skip, int limit); + } + + @DataProvider(name = "sliceSpliteratorDataProvider") + public static Object[][] sliceSpliteratorDataProvider() { + List data = new ArrayList<>(); + + // SIZED/SUBSIZED slice spliterator + + { + SliceTester r = (size, skip, limit) -> { + final Collection source = IntStream.range(0, size).boxed().collect(toList()); + + SpliteratorTestHelper.testSpliterator(() -> { + Spliterator s = Arrays.spliterator(source.stream().toArray(Integer[]::new)); + + return new StreamSpliterators.SliceSpliterator.OfRef<>(s, skip, limit); + }); + }; + data.add(new Object[]{"StreamSpliterators.SliceSpliterator.OfRef", r}); + } + + { + SliceTester r = (size, skip, limit) -> { + final Collection source = IntStream.range(0, size).boxed().collect(toList()); + + SpliteratorTestHelper.testIntSpliterator(() -> { + Spliterator.OfInt s = Arrays.spliterator(source.stream().mapToInt(i->i).toArray()); + + return new StreamSpliterators.SliceSpliterator.OfInt(s, skip, limit); + }); + }; + data.add(new Object[]{"StreamSpliterators.SliceSpliterator.OfInt", r}); + } + + { + SliceTester r = (size, skip, limit) -> { + final Collection source = LongStream.range(0, size).boxed().collect(toList()); + + SpliteratorTestHelper.testLongSpliterator(() -> { + Spliterator.OfLong s = Arrays.spliterator(source.stream().mapToLong(i->i).toArray()); + + return new StreamSpliterators.SliceSpliterator.OfLong(s, skip, limit); + }); + }; + data.add(new Object[]{"StreamSpliterators.SliceSpliterator.OfLong", r}); + } + + { + SliceTester r = (size, skip, limit) -> { + final Collection source = LongStream.range(0, size).asDoubleStream().boxed().collect(toList()); + + SpliteratorTestHelper.testDoubleSpliterator(() -> { + Spliterator.OfDouble s = Arrays.spliterator(source.stream().mapToDouble(i->i).toArray()); + + return new StreamSpliterators.SliceSpliterator.OfDouble(s, skip, limit); + }); + }; + data.add(new Object[]{"StreamSpliterators.SliceSpliterator.OfLong", r}); + } + + + // Unordered slice spliterator + + { + SliceTester r = (size, skip, limit) -> { + final Collection source = IntStream.range(0, size).boxed().collect(toList()); + final UnorderedContentAsserter uca = new UnorderedContentAsserter<>(source); + + SpliteratorTestHelper.testSpliterator(() -> { + Spliterator s = Arrays.spliterator(source.stream().toArray(Integer[]::new)); + + return new StreamSpliterators.UnorderedSliceSpliterator.OfRef<>(s, skip, limit); + }, uca); + }; + data.add(new Object[]{"StreamSpliterators.UnorderedSliceSpliterator.OfRef", r}); + } + + { + SliceTester r = (size, skip, limit) -> { + final Collection source = IntStream.range(0, size).boxed().collect(toList()); + final UnorderedContentAsserter uca = new UnorderedContentAsserter<>(source); + + SpliteratorTestHelper.testIntSpliterator(() -> { + Spliterator.OfInt s = Arrays.spliterator(source.stream().mapToInt(i->i).toArray()); + + return new StreamSpliterators.UnorderedSliceSpliterator.OfInt(s, skip, limit); + }, uca); + }; + data.add(new Object[]{"StreamSpliterators.UnorderedSliceSpliterator.OfInt", r}); + } + + { + SliceTester r = (size, skip, limit) -> { + final Collection source = LongStream.range(0, size).boxed().collect(toList()); + final UnorderedContentAsserter uca = new UnorderedContentAsserter<>(source); + + SpliteratorTestHelper.testLongSpliterator(() -> { + Spliterator.OfLong s = Arrays.spliterator(source.stream().mapToLong(i->i).toArray()); + + return new StreamSpliterators.UnorderedSliceSpliterator.OfLong(s, skip, limit); + }, uca); + }; + data.add(new Object[]{"StreamSpliterators.UnorderedSliceSpliterator.OfLong", r}); + } + + { + SliceTester r = (size, skip, limit) -> { + final Collection source = LongStream.range(0, size).asDoubleStream().boxed().collect(toList()); + final UnorderedContentAsserter uca = new UnorderedContentAsserter<>(source); + + SpliteratorTestHelper.testDoubleSpliterator(() -> { + Spliterator.OfDouble s = Arrays.spliterator(LongStream.range(0, SIZE).asDoubleStream().toArray()); + + return new StreamSpliterators.UnorderedSliceSpliterator.OfDouble(s, skip, limit); + }, uca); + }; + data.add(new Object[]{"StreamSpliterators.UnorderedSliceSpliterator.OfLong", r}); + } + + return data.toArray(new Object[0][]); + } + + static final int SIZE = 256; + + static final int STEP = 32; + + @Test(dataProvider = "sliceSpliteratorDataProvider") + public void testSliceSpliterator(String description, SliceTester r) { + setContext("size", SIZE); + for (int skip = 0; skip < SIZE; skip += STEP) { + setContext("skip", skip); + for (int limit = 0; limit < SIZE; limit += STEP) { + setContext("limit", skip); + r.test(SIZE, skip, limit); + } + } + } +} diff --git a/test/java/util/stream/boottest/java/util/stream/StreamFlagsTest.java b/test/java/util/stream/boottest/java/util/stream/StreamFlagsTest.java index a5fa364e1e06430c768217b095d7e74394065f56..29243cfb90a15486bc4dfeca1205876e5ca64d87 100644 --- a/test/java/util/stream/boottest/java/util/stream/StreamFlagsTest.java +++ b/test/java/util/stream/boottest/java/util/stream/StreamFlagsTest.java @@ -80,8 +80,8 @@ public class StreamFlagsTest { EnumSet.of(ORDERED, DISTINCT, SIZED), EnumSet.of(SORTED, SHORT_CIRCUIT)); assertFlags(OpTestCase.getStreamFlags(repeat), - EnumSet.of(ORDERED), - EnumSet.of(SIZED, DISTINCT, SORTED, SHORT_CIRCUIT)); + EnumSet.noneOf(StreamOpFlag.class), + EnumSet.of(DISTINCT, SORTED, SHORT_CIRCUIT)); } public void testFilter() { diff --git a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/InfiniteStreamWithLimitOpTest.java b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/InfiniteStreamWithLimitOpTest.java index a43802cc4197ad498732ceb2df63e5e4c2576af1..dc086668f54f845a8cafb29037607c6155cb528b 100644 --- a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/InfiniteStreamWithLimitOpTest.java +++ b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/InfiniteStreamWithLimitOpTest.java @@ -22,45 +22,440 @@ */ package org.openjdk.tests.java.util.stream; -import java.util.stream.OpTestCase; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import java.util.Arrays; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; +import java.util.Spliterator; +import java.util.function.Function; +import java.util.function.UnaryOperator; +import java.util.stream.DoubleStream; +import java.util.stream.DoubleStreamTestScenario; +import java.util.stream.IntStream; +import java.util.stream.IntStreamTestScenario; +import java.util.stream.LambdaTestHelpers; +import java.util.stream.LongStream; +import java.util.stream.LongStreamTestScenario; +import java.util.stream.OpTestCase; import java.util.stream.Stream; +import java.util.stream.StreamSupport; +import java.util.stream.StreamTestScenario; +import java.util.stream.TestData; -import static java.util.stream.LambdaTestHelpers.assertContents; +import static java.util.stream.LambdaTestHelpers.assertUnique; @Test public class InfiniteStreamWithLimitOpTest extends OpTestCase { - private static final List tenAs = Arrays.asList("A", "A", "A", "A", "A", "A", "A", "A", "A", "A"); + private static final long SKIP_LIMIT_SIZE = 1 << 16; + + @DataProvider(name = "Stream.limit") + @SuppressWarnings("rawtypes") + public static Object[][] sliceFunctionsDataProvider() { + Function f = s -> String.format(s, SKIP_LIMIT_SIZE); + + List data = new ArrayList<>(); + + data.add(new Object[]{f.apply("Stream.limit(%d)"), + (UnaryOperator) s -> s.limit(SKIP_LIMIT_SIZE)}); + data.add(new Object[]{f.apply("Stream.substream(%d)"), + (UnaryOperator) s -> s.substream(SKIP_LIMIT_SIZE, SKIP_LIMIT_SIZE * 2)}); + data.add(new Object[]{f.apply("Stream.substream(%1$d).limit(%1$d)"), + (UnaryOperator) s -> s.substream(SKIP_LIMIT_SIZE).limit(SKIP_LIMIT_SIZE)}); + + return data.toArray(new Object[0][]); + } + + @DataProvider(name = "IntStream.limit") + public static Object[][] intSliceFunctionsDataProvider() { + Function f = s -> String.format(s, SKIP_LIMIT_SIZE); + + List data = new ArrayList<>(); + + data.add(new Object[]{f.apply("IntStream.limit(%d)"), + (UnaryOperator) s -> s.limit(SKIP_LIMIT_SIZE)}); + data.add(new Object[]{f.apply("IntStream.substream(%d)"), + (UnaryOperator) s -> s.substream(SKIP_LIMIT_SIZE, SKIP_LIMIT_SIZE * 2)}); + data.add(new Object[]{f.apply("IntStream.substream(%1$d).limit(%1$d)"), + (UnaryOperator) s -> s.substream(SKIP_LIMIT_SIZE).limit(SKIP_LIMIT_SIZE)}); + + return data.toArray(new Object[0][]); + } + + @DataProvider(name = "LongStream.limit") + public static Object[][] longSliceFunctionsDataProvider() { + Function f = s -> String.format(s, SKIP_LIMIT_SIZE); + + List data = new ArrayList<>(); + + data.add(new Object[]{f.apply("LongStream.limit(%d)"), + (UnaryOperator) s -> s.limit(SKIP_LIMIT_SIZE)}); + data.add(new Object[]{f.apply("LongStream.substream(%d)"), + (UnaryOperator) s -> s.substream(SKIP_LIMIT_SIZE, SKIP_LIMIT_SIZE * 2)}); + data.add(new Object[]{f.apply("LongStream.substream(%1$d).limit(%1$d)"), + (UnaryOperator) s -> s.substream(SKIP_LIMIT_SIZE).limit(SKIP_LIMIT_SIZE)}); + + return data.toArray(new Object[0][]); + } + + @DataProvider(name = "DoubleStream.limit") + public static Object[][] doubleSliceFunctionsDataProvider() { + Function f = s -> String.format(s, SKIP_LIMIT_SIZE); + + List data = new ArrayList<>(); + + data.add(new Object[]{f.apply("DoubleStream.limit(%d)"), + (UnaryOperator) s -> s.limit(SKIP_LIMIT_SIZE)}); + data.add(new Object[]{f.apply("DoubleStream.substream(%d)"), + (UnaryOperator) s -> s.substream(SKIP_LIMIT_SIZE, SKIP_LIMIT_SIZE * 2)}); + data.add(new Object[]{f.apply("DoubleStream.substream(%1$d).limit(%1$d)"), + (UnaryOperator) s -> s.substream(SKIP_LIMIT_SIZE).limit(SKIP_LIMIT_SIZE)}); + + return data.toArray(new Object[0][]); + } + + private ResultAsserter> unorderedAsserter() { + return (act, exp, ord, par) -> { + if (par & !ord) { + // Can only assert that all elements of the actual result + // are distinct and that the count is the limit size + // any element within the range [0, Long.MAX_VALUE) may be + // present + assertUnique(act); + long count = 0; + for (T l : act) { + count++; + } + assertEquals(count, SKIP_LIMIT_SIZE, "size not equal"); + } + else { + LambdaTestHelpers.assertContents(act, exp); + } + }; + } + + private TestData.OfRef refLongs() { + return refLongRange(0, Long.MAX_VALUE); + } + + private TestData.OfRef refLongRange(long l, long u) { + return TestData.Factory.ofSupplier( + String.format("[%d, %d)", l, u), + () -> LongStream.range(l, u).boxed()); + } + + private TestData.OfInt ints() { + return intRange(0, Integer.MAX_VALUE); + } + + private TestData.OfInt intRange(int l, int u) { + return TestData.Factory.ofIntSupplier( + String.format("[%d, %d)", l, u), + () -> IntStream.range(l, u)); + } + + private TestData.OfLong longs() { + return longRange(0, Long.MAX_VALUE); + } + + private TestData.OfLong longRange(long l, long u) { + return TestData.Factory.ofLongSupplier( + String.format("[%d, %d)", l, u), + () -> LongStream.range(l, u)); + } + + private TestData.OfDouble doubles() { + return doubleRange(0, 1L << 53); + } + + private TestData.OfDouble doubleRange(long l, long u) { + return TestData.Factory.ofDoubleSupplier( + String.format("[%d, %d)", l, u), + () -> LongStream.range(l, u).mapToDouble(i -> (double) i)); + } + + + // Sized/subsized range + + @Test(dataProvider = "Stream.limit") + public void testSubsizedWithRange(String description, UnaryOperator> fs) { + // Range is [0, Long.MAX_VALUE), splits are SUBSIZED + // Such a size will induce out of memory errors for incorrect + // slice implementations + withData(refLongs()). + stream(s -> fs.apply(s)). + without(StreamTestScenario.PAR_STREAM_TO_ARRAY_CLEAR_SIZED). + exercise(); + } + + @Test(dataProvider = "IntStream.limit") + public void testIntSubsizedWithRange(String description, UnaryOperator fs) { + // Range is [0, Integer.MAX_VALUE), splits are SUBSIZED + // Such a size will induce out of memory errors for incorrect + // slice implementations + withData(ints()). + stream(s -> fs.apply(s)). + without(IntStreamTestScenario.PAR_STREAM_TO_ARRAY_CLEAR_SIZED). + exercise(); + } + + @Test(dataProvider = "LongStream.limit") + public void testLongSubsizedWithRange(String description, UnaryOperator fs) { + // Range is [0, Long.MAX_VALUE), splits are SUBSIZED + // Such a size will induce out of memory errors for incorrect + // slice implementations + withData(longs()). + stream(s -> fs.apply(s)). + without(LongStreamTestScenario.PAR_STREAM_TO_ARRAY_CLEAR_SIZED). + exercise(); + } + + @Test(dataProvider = "DoubleStream.limit") + public void testDoubleSubsizedWithRange(String description, UnaryOperator fs) { + // Range is [0, 2^53), splits are SUBSIZED + // Such a size will induce out of memory errors for incorrect + // slice implementations + withData(doubles()). + stream(s -> fs.apply(s)). + without(DoubleStreamTestScenario.PAR_STREAM_TO_ARRAY_CLEAR_SIZED). + exercise(); + } + + + // Unordered finite not SIZED/SUBSIZED + + @Test(dataProvider = "Stream.limit") + public void testUnorderedFinite(String description, UnaryOperator> fs) { + // Range is [0, Long.MAX_VALUE), splits are SUBSIZED + // Such a size will induce out of memory errors for incorrect + // slice implementations + withData(longs()). + stream(s -> fs.apply(s.filter(i -> true).unordered().boxed())). + resultAsserter(unorderedAsserter()). + exercise(); + } + + @Test(dataProvider = "IntStream.limit") + public void testIntUnorderedFinite(String description, UnaryOperator fs) { + // Range is [0, Integer.MAX_VALUE), splits are SUBSIZED + // Such a size will induce out of memory errors for incorrect + // slice implementations + withData(ints()). + stream(s -> fs.apply(s.filter(i -> true).unordered())). + resultAsserter(unorderedAsserter()). + exercise(); + } + + @Test(dataProvider = "LongStream.limit") + public void testLongUnorderedFinite(String description, UnaryOperator fs) { + // Range is [0, Long.MAX_VALUE), splits are SUBSIZED + // Such a size will induce out of memory errors for incorrect + // slice implementations + withData(longs()). + stream(s -> fs.apply(s.filter(i -> true).unordered())). + resultAsserter(unorderedAsserter()). + exercise(); + } + + @Test(dataProvider = "DoubleStream.limit") + public void testDoubleUnorderedFinite(String description, UnaryOperator fs) { + // Range is [0, 1L << 53), splits are SUBSIZED + // Such a size will induce out of memory errors for incorrect + // slice implementations + // Upper bound ensures values mapped to doubles will be unique + withData(doubles()). + stream(s -> fs.apply(s.filter(i -> true).unordered())). + resultAsserter(unorderedAsserter()). + exercise(); + } + + + // Unordered finite not SUBSIZED + + @SuppressWarnings({"rawtypes", "unchecked"}) + private Spliterator.OfLong proxyNotSubsized(Spliterator.OfLong s) { + InvocationHandler ih = new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + switch (method.getName()) { + case "characteristics": { + int c = (Integer) method.invoke(s, args); + return c & ~Spliterator.SUBSIZED; + } + case "hasCharacteristics": { + int c = (Integer) args[0]; + boolean b = (Boolean) method.invoke(s, args); + return b & ((c & Spliterator.SUBSIZED) == 0); + } + default: + return method.invoke(s, args); + } + } + }; + + return (Spliterator.OfLong) Proxy.newProxyInstance(this.getClass().getClassLoader(), + new Class[]{Spliterator.OfLong.class}, + ih); + } - public void testRepeatLimit() { - assertContents(Stream.generate(() -> "A").limit(10).iterator(), tenAs.iterator()); + private TestData.OfLong proxiedLongRange(long l, long u) { + return TestData.Factory.ofLongSupplier( + String.format("[%d, %d)", l, u), + () -> StreamSupport.longStream(proxyNotSubsized(LongStream.range(l, u).spliterator()))); } - public void testIterateLimit() { - assertContents(Stream.iterate("A", s -> s).limit(10).iterator(), tenAs.iterator()); + @Test(dataProvider = "Stream.limit") + public void testUnorderedSizedNotSubsizedFinite(String description, UnaryOperator> fs) { + // Range is [0, Long.MAX_VALUE), splits are not SUBSIZED (proxy clears + // the SUBSIZED characteristic) + // Such a size will induce out of memory errors for incorrect + // slice implementations + withData(proxiedLongRange(0, Long.MAX_VALUE)). + stream(s -> fs.apply(s.unordered().boxed())). + resultAsserter(unorderedAsserter()). + exercise(); } - public void testIterateFibLimit() { - Stream fib = Stream.iterate(new int[] {0, 1}, pair -> new int[] {pair[1], pair[0] + pair[1]}) - .map(pair -> pair[0]); + @Test(dataProvider = "IntStream.limit") + public void testIntUnorderedSizedNotSubsizedFinite(String description, UnaryOperator fs) { + // Range is [0, Integer.MAX_VALUE), splits are not SUBSIZED (proxy clears + // the SUBSIZED characteristic) + // Such a size will induce out of memory errors for incorrect + // slice implementations + withData(proxiedLongRange(0, Integer.MAX_VALUE)). + stream(s -> fs.apply(s.unordered().mapToInt(i -> (int) i))). + resultAsserter(unorderedAsserter()). + exercise(); + } + + @Test(dataProvider = "LongStream.limit") + public void testLongUnorderedSizedNotSubsizedFinite(String description, UnaryOperator fs) { + // Range is [0, Long.MAX_VALUE), splits are not SUBSIZED (proxy clears + // the SUBSIZED characteristic) + // Such a size will induce out of memory errors for incorrect + // slice implementations + withData(proxiedLongRange(0, Long.MAX_VALUE)). + stream(s -> fs.apply(s.unordered())). + resultAsserter(unorderedAsserter()). + exercise(); + } - assertContents( - fib.limit(10).iterator(), - Arrays.asList(0, 1, 1, 2, 3, 5, 8, 13, 21, 34).iterator()); + @Test(dataProvider = "DoubleStream.limit") + public void testDoubleUnorderedSizedNotSubsizedFinite(String description, UnaryOperator fs) { + // Range is [0, Double.MAX_VALUE), splits are not SUBSIZED (proxy clears + // the SUBSIZED characteristic) + // Such a size will induce out of memory errors for incorrect + // slice implementations + withData(proxiedLongRange(0, 1L << 53)). + stream(s -> fs.apply(s.unordered().mapToDouble(i -> (double) i))). + resultAsserter(unorderedAsserter()). + exercise(); } - public void testInfiniteWithLimitToShortCircuitTerminal() { - Object[] array = Stream.generate(() -> 1).limit(4).toArray(); - assertEquals(4, array.length); - array = Stream.generate(() -> 1).limit(4).filter(i -> true).toArray(); - assertEquals(4, array.length); - List result = Stream.generate(() -> 1).limit(4).collect(Collectors.toList()); - assertEquals(result, Arrays.asList(1, 1, 1, 1)); + + // Unordered generation + + @Test(dataProvider = "Stream.limit") + public void testUnorderedGenerator(String description, UnaryOperator> fs) { + // Source is spliterator of infinite size + TestData.OfRef generator = TestData.Factory.ofSupplier( + "[1L, 1L, ...]", () -> Stream.generate(() -> 1L)); + + withData(generator). + stream(s -> fs.apply(s.filter(i -> true).unordered())). + exercise(); + } + + @Test(dataProvider = "IntStream.limit") + public void testIntUnorderedGenerator(String description, UnaryOperator fs) { + // Source is spliterator of infinite size + TestData.OfInt generator = TestData.Factory.ofIntSupplier( + "[1, 1, ...]", () -> IntStream.generate(() -> 1)); + + withData(generator). + stream(s -> fs.apply(s.filter(i -> true).unordered())). + exercise(); + } + + @Test(dataProvider = "LongStream.limit") + public void testLongUnorderedGenerator(String description, UnaryOperator fs) { + // Source is spliterator of infinite size + TestData.OfLong generator = TestData.Factory.ofLongSupplier( + "[1L, 1L, ...]", () -> LongStream.generate(() -> 1)); + + withData(generator). + stream(s -> fs.apply(s.filter(i -> true).unordered())). + exercise(); + } + + @Test(dataProvider = "DoubleStream.limit") + public void testDoubleUnorderedGenerator(String description, UnaryOperator fs) { + // Source is spliterator of infinite size + TestData.OfDouble generator = TestData.Factory.ofDoubleSupplier( + "[1.0, 1.0, ...]", () -> DoubleStream.generate(() -> 1.0)); + + withData(generator). + stream(s -> fs.apply(s.filter(i -> true).unordered())). + exercise(); + } + + + // Unordered iteration + + @Test(dataProvider = "Stream.limit") + public void testUnorderedIteration(String description, UnaryOperator> fs) { + // Source is a right-balanced tree of infinite size + TestData.OfRef iterator = TestData.Factory.ofSupplier( + "[1L, 2L, 3L, ...]", () -> Stream.iterate(1L, i -> i + 1L)); + + // Ref + withData(iterator). + stream(s -> fs.apply(s.unordered())). + resultAsserter(unorderedAsserter()). + exercise(); + } + + @Test(dataProvider = "IntStream.limit") + public void testIntUnorderedIteration(String description, UnaryOperator fs) { + // Source is a right-balanced tree of infinite size + TestData.OfInt iterator = TestData.Factory.ofIntSupplier( + "[1, 2, 3, ...]", () -> IntStream.iterate(1, i -> i + 1)); + + // Ref + withData(iterator). + stream(s -> fs.apply(s.unordered())). + resultAsserter(unorderedAsserter()). + exercise(); + } + + @Test(dataProvider = "LongStream.limit") + public void testLongUnorderedIteration(String description, UnaryOperator fs) { + // Source is a right-balanced tree of infinite size + TestData.OfLong iterator = TestData.Factory.ofLongSupplier( + "[1L, 2L, 3L, ...]", () -> LongStream.iterate(1, i -> i + 1)); + + // Ref + withData(iterator). + stream(s -> fs.apply(s.unordered())). + resultAsserter(unorderedAsserter()). + exercise(); + } + + @Test(dataProvider = "DoubleStream.limit") + public void testDoubleUnorderedIteration(String description, UnaryOperator fs) { + // Source is a right-balanced tree of infinite size + TestData.OfDouble iterator = TestData.Factory.ofDoubleSupplier( + "[1.0, 2.0, 3.0, ...]", () -> DoubleStream.iterate(1, i -> i + 1)); + + // Ref + withData(iterator). + stream(s -> fs.apply(s.unordered())). + resultAsserter(unorderedAsserter()). + exercise(); } } diff --git a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SequentialOpTest.java b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SequentialOpTest.java index 793b31daed44fe6b1d6f6691bc083a8367d216e2..efa5c62e640ebf588c268d445704cb52f67f9397 100644 --- a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SequentialOpTest.java +++ b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SequentialOpTest.java @@ -22,7 +22,6 @@ */ package org.openjdk.tests.java.util.stream; -import java.util.Comparators; import java.util.stream.LambdaTestHelpers; import java.util.stream.OpTestCase; import java.util.stream.StreamTestDataProvider; @@ -109,9 +108,9 @@ public class SequentialOpTest extends OpTestCase { = new UnaryOperator[] { (UnaryOperator>) s -> s, (UnaryOperator>) s -> s.map(id), - (UnaryOperator>) s -> s.sorted(Comparators.naturalOrder()), - (UnaryOperator>) s -> s.map(id).sorted(Comparators.naturalOrder()).map(id), - (UnaryOperator>) s -> s.filter(LambdaTestHelpers.pEven).sorted(Comparators.naturalOrder()).map(id), + (UnaryOperator>) s -> s.sorted(Comparator.naturalOrder()), + (UnaryOperator>) s -> s.map(id).sorted(Comparator.naturalOrder()).map(id), + (UnaryOperator>) s -> s.filter(LambdaTestHelpers.pEven).sorted(Comparator.naturalOrder()).map(id), }; for (int c1Index = 0; c1Index < changers.length; c1Index++) { diff --git a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SliceOpTest.java b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SliceOpTest.java index ff9400359806e658191363b300817a55417c889d..29086fa351d947dce3198cf109e277a8afa14191 100644 --- a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SliceOpTest.java +++ b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SliceOpTest.java @@ -270,7 +270,7 @@ public class SliceOpTest extends OpTestCase { public void testLimitSort() { List l = countTo(100); Collections.reverse(l); - exerciseOps(l, s -> s.limit(10).sorted(Comparators.naturalOrder())); + exerciseOps(l, s -> s.limit(10).sorted(Comparator.naturalOrder())); } @Test(groups = { "serialization-hostile" }) diff --git a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SortedOpTest.java b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SortedOpTest.java index 93ac4eae386ebbd3a9d829f2d6885a9ebe9e141b..956dea39ec3f233b0ea5e9d757048caa5c6dc2b7 100644 --- a/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SortedOpTest.java +++ b/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SortedOpTest.java @@ -40,10 +40,10 @@ public class SortedOpTest extends OpTestCase { public void testSorted() { assertCountSum(countTo(0).stream().sorted(), 0, 0); assertCountSum(countTo(10).stream().sorted(), 10, 55); - assertCountSum(countTo(10).stream().sorted(cInteger.reverseOrder()), 10, 55); + assertCountSum(countTo(10).stream().sorted(cInteger.reversed()), 10, 55); List to10 = countTo(10); - assertSorted(to10.stream().sorted(cInteger.reverseOrder()).iterator(), cInteger.reverseOrder()); + assertSorted(to10.stream().sorted(cInteger.reversed()).iterator(), cInteger.reversed()); Collections.reverse(to10); assertSorted(to10.stream().sorted().iterator()); @@ -51,7 +51,7 @@ public class SortedOpTest extends OpTestCase { Spliterator s = to10.stream().sorted().spliterator(); assertTrue(s.hasCharacteristics(Spliterator.SORTED)); - s = to10.stream().sorted(cInteger.reverseOrder()).spliterator(); + s = to10.stream().sorted(cInteger.reversed()).spliterator(); assertFalse(s.hasCharacteristics(Spliterator.SORTED)); } @@ -87,8 +87,8 @@ public class SortedOpTest extends OpTestCase { assertSorted(result.iterator()); assertContentsUnordered(data, result); - result = exerciseOps(data, s -> s.sorted(cInteger.reverseOrder())); - assertSorted(result.iterator(), cInteger.reverseOrder()); + result = exerciseOps(data, s -> s.sorted(cInteger.reversed())); + assertSorted(result.iterator(), cInteger.reversed()); assertContentsUnordered(data, result); } @@ -104,23 +104,23 @@ public class SortedOpTest extends OpTestCase { assertContentsUnordered(data, result); result = withData(data) - .stream(s -> s.sorted(cInteger.reverseOrder()).sorted(cInteger.reverseOrder()), + .stream(s -> s.sorted(cInteger.reversed()).sorted(cInteger.reversed()), new CollectorOps.TestParallelSizedOp()) .exercise(); - assertSorted(result, cInteger.reverseOrder()); + assertSorted(result, cInteger.reversed()); assertContentsUnordered(data, result); result = withData(data) - .stream(s -> s.sorted().sorted(cInteger.reverseOrder()), + .stream(s -> s.sorted().sorted(cInteger.reversed()), new CollectorOps.TestParallelSizedOp()) .exercise(); - assertSorted(result, cInteger.reverseOrder()); + assertSorted(result, cInteger.reversed()); assertContentsUnordered(data, result); result = withData(data) - .stream(s -> s.sorted(cInteger.reverseOrder()).sorted(), + .stream(s -> s.sorted(cInteger.reversed()).sorted(), new CollectorOps.TestParallelSizedOp()) .exercise(); diff --git a/test/javax/print/PrintServiceLookup/GetPrintServices.java b/test/javax/print/PrintServiceLookup/GetPrintServices.java new file mode 100644 index 0000000000000000000000000000000000000000..f8373a6383a5bd9f2b7362632cd96647c04b2f1f --- /dev/null +++ b/test/javax/print/PrintServiceLookup/GetPrintServices.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.print.PrintService; +import javax.print.PrintServiceLookup; +import javax.print.attribute.AttributeSet; +import javax.print.attribute.HashAttributeSet; +import javax.print.attribute.standard.PrinterName; + +/* + * @test + * @bug 8013810 + * @summary Test that print service returned without filter are of the same class as with name filter + */ +public class GetPrintServices { + + public static void main(String[] args) throws Exception { + for (PrintService service : PrintServiceLookup.lookupPrintServices(null, null)) { + String serviceName = service.getName(); + PrintService serviceByName = lookupByName(serviceName); + if (!service.equals(serviceByName)) { + throw new RuntimeException("NOK " + serviceName + + " expected: " + service.getClass().getName() + + " got: " + serviceByName.getClass().getName()); + } + } + System.out.println("Test PASSED"); + } + + private static PrintService lookupByName(String name) { + AttributeSet attributes = new HashAttributeSet(); + attributes.add(new PrinterName(name, null)); + for (PrintService service : PrintServiceLookup.lookupPrintServices(null, attributes)) { + return service; + } + return null; + } +} diff --git a/test/javax/swing/JFileChooser/8013442/Test8013442.java b/test/javax/swing/JFileChooser/8013442/Test8013442.java new file mode 100644 index 0000000000000000000000000000000000000000..e7b892ddaed4a6bee9f35d9b16516c20c21d88e2 --- /dev/null +++ b/test/javax/swing/JFileChooser/8013442/Test8013442.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8013442 + * @summary Tests that at least one file filter is selected + * @author Sergey Malenkov + */ + +import java.io.File; +import java.util.concurrent.CountDownLatch; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.UIManager.LookAndFeelInfo; +import javax.swing.filechooser.FileFilter; + +public class Test8013442 extends FileFilter implements Runnable, Thread.UncaughtExceptionHandler { + private static final CountDownLatch LATCH = new CountDownLatch(1); + + public static void main(String[] args) throws InterruptedException { + SwingUtilities.invokeLater(new Test8013442()); + LATCH.await(); // workaround for jtreg + } + + private int index; + private LookAndFeelInfo[] infos; + private JFileChooser chooser; + + @Override + public boolean accept(File file) { + return !file.isFile() || file.getName().toLowerCase().endsWith(".txt"); + } + + @Override + public String getDescription() { + return "Text files"; + } + + @Override + public void run() { + if (this.infos == null) { + this.infos = UIManager.getInstalledLookAndFeels(); + Thread.currentThread().setUncaughtExceptionHandler(this); + } + if (this.infos.length == this.index) { + LATCH.countDown(); // release main thread + } else if (this.chooser == null) { + // change LaF before creation of Swing components + LookAndFeelInfo info = this.infos[this.index]; + System.out.println(info.getName()); + try { + UIManager.setLookAndFeel(info.getClassName()); + } + catch (Exception exception) { + throw new Error("could not change look and feel", exception); + } + // create and show new file chooser + JFrame frame = new JFrame(getClass().getSimpleName()); + frame.add(this.chooser = new JFileChooser()); + frame.setSize(800, 600); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + SwingUtilities.invokeLater(this); + } + else { + int count = this.chooser.getChoosableFileFilters().length; + System.out.println("count = " + count + "; " + this.chooser.isAcceptAllFileFilterUsed()); + if (count == 0) { + if (null != this.chooser.getFileFilter()) { + throw new Error("file filter is selected"); + } + // close window and stop testing file chooser for current LaF + SwingUtilities.getWindowAncestor(this.chooser).dispose(); + this.chooser = null; + this.index++; + } else { + if (null == this.chooser.getFileFilter()) { + throw new Error("file filter is not selected"); + } + if (count == 2) { + // remove default file filter + this.chooser.setAcceptAllFileFilterUsed(false); + } else if (this.chooser.isAcceptAllFileFilterUsed()) { + // remove add file filter + this.chooser.addChoosableFileFilter(this); + } else { + // remove custom file filter + this.chooser.removeChoosableFileFilter(this); + } + } + SwingUtilities.invokeLater(this); + } + } + + public void uncaughtException(Thread thread, Throwable throwable) { + throwable.printStackTrace(); + System.exit(1); + } +} diff --git a/test/javax/swing/JMenu/4692443/bug4692443.java b/test/javax/swing/JMenu/4692443/bug4692443.java new file mode 100644 index 0000000000000000000000000000000000000000..6032287e53405eda8610c15a4a4e331b8d8f09c6 --- /dev/null +++ b/test/javax/swing/JMenu/4692443/bug4692443.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @library ../../regtesthelpers + * @build Util + * @bug 4692443 7105030 + * @summary JMenu: MenuListener.menuSelected() event fired too late when using mnemonics + * @author Alexander Zuev + * @run main bug4692443 + */ + +import javax.swing.*; +import javax.swing.event.*; +import java.awt.event.*; +import java.awt.*; +import sun.awt.SunToolkit; + +public class bug4692443 { + + public static PassedListener pass; + public static FailedListener fail; + public static volatile Boolean passed; + + public static void main(String args[]) throws Throwable { + + fail = new FailedListener(); + pass = new PassedListener(); + passed = false; + Robot robo = new Robot(); + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + createAndShowGUI(); + } + }); + + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + toolkit.realSync(); + + try { + robo = new Robot(); + } catch (AWTException e) { + throw new RuntimeException("Robot could not be created"); + } + int altKey = java.awt.event.KeyEvent.VK_ALT; + robo.setAutoDelay(100); + Util.hitMnemonics(robo, KeyEvent.VK_F); // Enter File menu + robo.keyPress(KeyEvent.VK_S); // Enter submenu + robo.keyRelease(KeyEvent.VK_S); + robo.keyPress(KeyEvent.VK_O); // Launch "One" action + robo.keyRelease(KeyEvent.VK_O); + robo.keyPress(KeyEvent.VK_M); // Launch "One" action + robo.keyRelease(KeyEvent.VK_M); + + toolkit.realSync(); + + if (!passed) { + throw new RuntimeException("Test failed."); + } + + } + + private static void createAndShowGUI() { + JFrame mainFrame = new JFrame("Bug 4692443"); + JMenuBar mbar = new JMenuBar(); + JMenu menu = new JMenu("File"); + menu.setMnemonic('F'); + menu.add(new JMenuItem("Menu Item 1")).setMnemonic('I'); + final JMenu submenu = new JMenu("Submenu"); + submenu.setMnemonic('S'); + submenu.addMenuListener(new MenuListener() { + public void menuSelected(MenuEvent e) { + JMenuItem item = submenu.add(new JMenuItem("One", 'O')); + item.addActionListener(pass); + submenu.add(new JMenuItem("Two", 'w')); + submenu.add(new JMenuItem("Three", 'r')); + } + public void menuDeselected(MenuEvent e) { + submenu.removeAll(); + } + public void menuCanceled(MenuEvent e) { + submenu.removeAll(); + } + }); + menu.add(submenu); + JMenuItem menuItem = menu.add(new JMenuItem("Menu Item 2")); + menuItem.setMnemonic('M'); + menuItem.addActionListener(fail); + mbar.add(menu); + mainFrame.setJMenuBar(mbar); + + mainFrame.setSize(200, 200); + mainFrame.setLocation(200, 200); + mainFrame.setVisible(true); + mainFrame.toFront(); + } + + public static class FailedListener implements ActionListener { + public void actionPerformed(ActionEvent ev) { + throw new RuntimeException("Test failed."); + } + } + + public static class PassedListener implements ActionListener { + public void actionPerformed(ActionEvent ev) { + passed = true; + } + } + +} diff --git a/test/javax/swing/JTree/8013571/Test8013571.java b/test/javax/swing/JTree/8013571/Test8013571.java new file mode 100644 index 0000000000000000000000000000000000000000..15ad391dcf235269ea865fa0599537c0dff49290 --- /dev/null +++ b/test/javax/swing/JTree/8013571/Test8013571.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.swing.JTree; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; + +/* + * @test + * @bug 8016545 + * @summary Tests beans with public fields + * @author Sergey Malenkov + */ + +public class Test8013571 extends DefaultTreeModel { + public static void main(String[] args) { + DefaultMutableTreeNode root = create("root"); + root.add(create("colors", "blue", "violet", "red", "yellow")); + root.add(create("sports", "basketball", "soccer", "football", "hockey")); + root.add(create("food", "hot dogs", "pizza", "ravioli", "bananas")); + Test8013571 model = new Test8013571(root); + JTree tree = new JTree(model); + model.fireTreeChanged(tree); + } + + private static DefaultMutableTreeNode create(String name, String... values) { + DefaultMutableTreeNode node = new DefaultMutableTreeNode(name); + for (String value : values) { + node.add(create(value)); + } + return node; + } + + private Test8013571(DefaultMutableTreeNode root) { + super(root); + } + + private void fireTreeChanged(Object source) { + fireTreeNodesInserted(source, null, null, null); + fireTreeNodesChanged(source, null, null, null); + fireTreeNodesRemoved(source, null, null, null); + fireTreeStructureChanged(source, null, null, null); + } +} diff --git a/test/javax/swing/plaf/basic/BasicComboBoxEditor/Test8015336.java b/test/javax/swing/plaf/basic/BasicComboBoxEditor/Test8015336.java new file mode 100644 index 0000000000000000000000000000000000000000..742fc99091aeaee0e0f747fd9a7f13a82ea741ed --- /dev/null +++ b/test/javax/swing/plaf/basic/BasicComboBoxEditor/Test8015336.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.swing.JComboBox; + +/* + * @test + * @bug 8015336 + * @summary No NPE for BasicComboBoxEditor.setItem(null) + * @author Sergey Malenkov + */ +public class Test8015336 { + public static void main(String[] args) throws Exception { + new JComboBox().getEditor().setItem(new Test8015336()); + } + + @Override + public String toString() { + return null; + } +} diff --git a/test/javax/swing/text/View/8014863/bug8014863.java b/test/javax/swing/text/View/8014863/bug8014863.java index 3ceebd676f224e7f2db446e7f86a361ae146feba..ba78b4bbbbb86fa59ad758468c7ea8eef43a88d5 100644 --- a/test/javax/swing/text/View/8014863/bug8014863.java +++ b/test/javax/swing/text/View/8014863/bug8014863.java @@ -136,9 +136,12 @@ public class bug8014863 { "qqqq pp qqqq pp qqqq pp qqqq pp" + " qqqq pp qqqq pp qqqq pp qqqq

      "); editorPane.setCaretPosition(1); - + // An actual font size depends on OS and might be differnet on various OSs. + // It is necessary to calculate the width to meet the expected number of lines. + int width = SwingUtilities.computeStringWidth(editorPane.getFontMetrics(editorPane.getFont()), + "qqqq pp qqqq pp qqqq pp qqqqqqqq"); frame.add(editorPane); - frame.setSize(200, 200); + frame.setSize(width, 200); frame.setVisible(true); } }); diff --git a/test/javax/swing/text/View/8015853/bug8015853.java b/test/javax/swing/text/View/8015853/bug8015853.java new file mode 100644 index 0000000000000000000000000000000000000000..f63210683beae30c17d30b429ec136b0ff90ed46 --- /dev/null +++ b/test/javax/swing/text/View/8015853/bug8015853.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8015853 + * @summary Tests the rendering of a large HTML document + * @author Dmitry Markov + * @run main bug8015853 + */ + +import java.io.*; +import java.net.URL; +import java.util.Scanner; +import javax.swing.*; +import javax.swing.text.html.HTMLEditorKit; + +public class bug8015853 { + + private static String text = ""; + + public static void main(String[] args) throws Exception { + + try { + URL path = ClassLoader.getSystemResource("bug8015853.txt"); + File file = new File(path.toURI()); + Scanner scanner = new Scanner(file); + while (scanner.hasNextLine()) { + text += scanner.nextLine() + "\n"; + } + scanner.close(); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + + text += text; + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + createAndShowGUI(); + } + }); + } + + private static void createAndShowGUI() { + try { + UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + JFrame frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JEditorPane editorPane = new JEditorPane(); + HTMLEditorKit editorKit = new HTMLEditorKit(); + editorPane.setEditorKit(editorKit); + editorPane.setText(text); + + frame.add(editorPane); + frame.setVisible(true); + } +} diff --git a/test/javax/swing/text/View/8015853/bug8015853.txt b/test/javax/swing/text/View/8015853/bug8015853.txt new file mode 100644 index 0000000000000000000000000000000000000000..d9a6230684fe0939c1a39d88e8486a9ed4ddbd6c --- /dev/null +++ b/test/javax/swing/text/View/8015853/bug8015853.txt @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import java.io.*; +import java.net.URL; +import java.util.Scanner; +import javax.swing.*; +import javax.swing.text.html.HTMLEditorKit; +public class bug8015853 { + private static String text = ""; + public static void main(String[] args) throws Exception { + + try { + URL path = ClassLoader.getSystemResource("bug8015853.txt"); + File file = new File(path.toURI()); + Scanner scanner = new Scanner(file); + while (scanner.hasNextLine()) { + text += scanner.nextLine() + "\n"; + } + scanner.close(); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + + System.out.println(text); + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + createAndShowGUI(); + } + }); + } + private static void createAndShowGUI() { + try { + UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + JFrame frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + JEditorPane editorPane = new JEditorPane(); + HTMLEditorKit editorKit = new HTMLEditorKit(); + editorPane.setEditorKit(editorKit); + editorPane.setText(text); + frame.add(editorPane); + frame.setVisible(true); + } +} \ No newline at end of file diff --git a/test/sun/java2d/cmm/ColorConvertOp/ColConvCCMTest.java b/test/sun/java2d/cmm/ColorConvertOp/ColConvCCMTest.java index 89bd29af05675b535b59bc2589f665ec25233f13..12418c0ed2a3f01277e6abaf97acf814265748a6 100644 --- a/test/sun/java2d/cmm/ColorConvertOp/ColConvCCMTest.java +++ b/test/sun/java2d/cmm/ColorConvertOp/ColConvCCMTest.java @@ -23,7 +23,7 @@ /** * @test - * @bug 6476665 7033534 + * @bug 6476665 7033534 6830714 * @summary Verifies color conversion of Component Color Model based images * @run main ColConvCCMTest */ @@ -57,9 +57,9 @@ public class ColConvCCMTest extends ColConvTest { final static double [] ACCURACY = { // Accuracy for color conversions 2.5, // sRGB - 6.5, // LINEAR_RGB + (isOpenProfile() ? 45.0 : 10.1), // LINEAR_RGB 10.5, // GRAY - 45.5, // PYCC + (isOpenProfile() ? 207 : 45.5), // PYCC 47.5 // CIEXYZ }; diff --git a/test/sun/java2d/cmm/ColorConvertOp/ColConvDCMTest.java b/test/sun/java2d/cmm/ColorConvertOp/ColConvDCMTest.java index b9f85c72519d61722dd77c4cdea81742007a365f..9ad05689942f9ca242e0dfd0caa59752ba21542a 100644 --- a/test/sun/java2d/cmm/ColorConvertOp/ColConvDCMTest.java +++ b/test/sun/java2d/cmm/ColorConvertOp/ColConvDCMTest.java @@ -62,7 +62,11 @@ public class ColConvDCMTest extends ColConvTest { ColorSpace.CS_LINEAR_RGB, }; - final static double ACCURACY = 2.5; + final static double [] ACCURACY = { + // Accuracy for color conversions + 2.5, // sRGB + (isOpenProfile() ? 45.0 : 2.5), // LINEAR_RGB + }; final static String [] gldImgNames = { "SRGB.png", "SRGB555.png", "SRGB565.png", "LRGB.png", "LRGB555.png", @@ -142,7 +146,7 @@ public class ColConvDCMTest extends ColConvTest { if (!testImage(imgTypes[i][0], imgTypes[i][1], imgTypes[i][2], imgTypes[i][3], cSpaces[imgTypes[i][4]], gldImage, - ACCURACY)) + ACCURACY[imgTypes[i][4]])) { throw new RuntimeException( "Invalid result of the ColorConvertOp for " + @@ -154,7 +158,8 @@ public class ColConvDCMTest extends ColConvTest { if (!testSubImage(SI_X, SI_Y, SI_W, SI_H, imgTypes[i][0], imgTypes[i][1], imgTypes[i][2], imgTypes[i][3], - cSpaces[imgTypes[i][4]], gldImage, ACCURACY)) + cSpaces[imgTypes[i][4]], gldImage, + ACCURACY[imgTypes[i][4]])) { throw new RuntimeException( "Invalid result of the ColorConvertOp for " + diff --git a/test/sun/java2d/cmm/ColorConvertOp/ColConvTest.java b/test/sun/java2d/cmm/ColorConvertOp/ColConvTest.java index db3719134f18febb752fecb9298f0924eaf410a0..b3f1c2e4da2f0bef9f4eb49463585ce42141ac34 100644 --- a/test/sun/java2d/cmm/ColorConvertOp/ColConvTest.java +++ b/test/sun/java2d/cmm/ColorConvertOp/ColConvTest.java @@ -22,6 +22,7 @@ */ import java.awt.color.ColorSpace; +import java.awt.color.ICC_Profile; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; @@ -126,4 +127,33 @@ public abstract class ColConvTest implements Runnable { public boolean isPassed() { return passed; } + + private static Boolean isOpenProfile = null; + + public static boolean isOpenProfile() { + if (isOpenProfile == null) { + ICC_Profile p = ICC_Profile.getInstance(ColorSpace.CS_sRGB); + + byte[] h = p.getData(ICC_Profile.icSigHead); + + if (h == null || h.length < 128) { + throw new RuntimeException("Test failed: invalid sRGB header"); + } + + final byte[] lcmsID = new byte[] { + (byte)0x6c, // l + (byte)0x63, // c + (byte)0x6d, // m + (byte)0x73, // s + }; + + int off = ICC_Profile.icHdrCmmId; + + isOpenProfile = ((h[off + 0] == lcmsID[0]) + && (h[off + 1] == lcmsID[1]) + && (h[off + 2] == lcmsID[2]) + && (h[off + 3] == lcmsID[3])); + } + return isOpenProfile; + } } diff --git a/test/sun/misc/JavaLangAccess/NewUnsafeString.java b/test/sun/misc/JavaLangAccess/NewUnsafeString.java index 930d57bee80f52f07d0c5d0fe4999e8ca21e8112..ab608d7dcf53d7932d85d5210384703126f8de27 100644 --- a/test/sun/misc/JavaLangAccess/NewUnsafeString.java +++ b/test/sun/misc/JavaLangAccess/NewUnsafeString.java @@ -22,7 +22,7 @@ */ import java.util.Objects; -import java.util.Comparators; +import java.util.Comparator; import sun.misc.JavaLangAccess; import sun.misc.SharedSecrets; @@ -48,7 +48,7 @@ public class NewUnsafeString { if (!benchmark.equals(constructorCopy)) { throw new Error("Copy not equal"); } - if (0 != Objects.compare(benchmark, constructorCopy, Comparators.naturalOrder())) { + if (0 != Objects.compare(benchmark, constructorCopy, Comparator.naturalOrder())) { throw new Error("Copy not equal"); } @@ -58,7 +58,7 @@ public class NewUnsafeString { if (!benchmark.equals(jlaCopy)) { throw new Error("Copy not equal"); } - if (0 != Objects.compare(benchmark, jlaCopy, Comparators.naturalOrder())) { + if (0 != Objects.compare(benchmark, jlaCopy, Comparator.naturalOrder())) { throw new Error("Copy not equal"); } @@ -68,7 +68,7 @@ public class NewUnsafeString { if (!constructorCopy.equals(jlaCopy)) { throw new Error("Copy not equal"); } - if (0 != Objects.compare(constructorCopy, jlaCopy, Comparators.naturalOrder())) { + if (0 != Objects.compare(constructorCopy, jlaCopy, Comparator.naturalOrder())) { throw new Error("Copy not equal"); } diff --git a/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/NoImpactServerRenego.java b/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/NoImpactServerRenego.java index 5ef0c76dca13157f4a8e0d85fe1c4f0b51d76fc1..ab23ce4239c9e529a8f21316cc6e03059cdf5427 100644 --- a/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/NoImpactServerRenego.java +++ b/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/NoImpactServerRenego.java @@ -29,7 +29,7 @@ * @bug 7188658 * @summary Add possibility to disable client initiated renegotiation * @run main/othervm - * -Djdk.tls.rejectClientInitializedRenego=true NoImpactServerRenego + * -Djdk.tls.rejectClientInitiatedRenegotiation=true NoImpactServerRenego */ import java.io.*; diff --git a/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/RejectClientRenego.java b/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/RejectClientRenego.java index 29f80d9e15b6abf0e9e81c88d13022a027df68df..01a7febca29fbbe75766fa5536cd57fcf3f6067d 100644 --- a/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/RejectClientRenego.java +++ b/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/RejectClientRenego.java @@ -216,7 +216,8 @@ public class RejectClientRenego implements System.setProperty("javax.net.ssl.trustStorePassword", passwd); // reject client initialized SSL renegotiation. - System.setProperty("jdk.tls.rejectClientInitializedRenego", "true"); + System.setProperty( + "jdk.tls.rejectClientInitiatedRenegotiation", "true"); if (debug) System.setProperty("javax.net.debug", "all"); diff --git a/test/sun/text/resources/LocaleData b/test/sun/text/resources/LocaleData index 91d4c46b85488ff307b797a012fa764f0bf347de..4bcb9739295881a565908e5443f152ff856bb4c9 100644 --- a/test/sun/text/resources/LocaleData +++ b/test/sun/text/resources/LocaleData @@ -11,7 +11,7 @@ LocaleNames//es=Spanish # bug #4052679 LocaleNames/fr/fr=fran\u00e7ais -# bug #4055602, 4290801 +# bug #4055602, 4290801, 8013836 CurrencyNames/pt_BR/BRL=R$ FormatData/pt_BR/NumberPatterns/0=#,##0.###;-#,##0.### # FormatData/pt_BR/NumberPatterns/1=R$ #,##0.##;-R$ #,##0.## # Changed; see bug 4122840 @@ -34,7 +34,7 @@ FormatData/pt_BR/DayAbbreviations/2=Ter FormatData/pt_BR/DayNames/0=Domingo FormatData/pt_BR/DayNames/1=Segunda-feira FormatData/pt_BR/DayNames/2=Ter\u00e7a-feira -CalendarData/pt_BR/firstDayOfWeek=2 +CalendarData/pt_BR/firstDayOfWeek=1 CalendarData/pt_BR/minimalDaysInFirstWeek=1 FormatData/pt_BR/MonthNames/0=Janeiro FormatData/pt_BR/MonthNames/1=Fevereiro diff --git a/test/sun/text/resources/LocaleDataTest.java b/test/sun/text/resources/LocaleDataTest.java index 73cd7e805adedb0ddbb5c3d78f0fb84d9b4306d1..961fcf52be1b5798d41f106de77169414ee40a7e 100644 --- a/test/sun/text/resources/LocaleDataTest.java +++ b/test/sun/text/resources/LocaleDataTest.java @@ -35,7 +35,7 @@ * 6645405 6650730 6910489 6573250 6870908 6585666 6716626 6914413 6916787 * 6919624 6998391 7019267 7020960 7025837 7020583 7036905 7066203 7101495 * 7003124 7085757 7028073 7171028 7189611 8000983 7195759 8004489 8006509 - * 7114053 7074882 7040556 + * 7114053 7074882 7040556 8013836 * @summary Verify locale data * */ diff --git a/test/sun/tools/jcmd/jcmd_Output1.awk b/test/sun/tools/jcmd/jcmd_Output1.awk index 986951dc178b7a22cce6d49ea9d68d98baa57e85..5bf0403fa2db9097df780012994c763257e8bd29 100644 --- a/test/sun/tools/jcmd/jcmd_Output1.awk +++ b/test/sun/tools/jcmd/jcmd_Output1.awk @@ -8,10 +8,10 @@ BEGIN { current=1; } -# or match on a path name to a jar file followed by arbitraty arguments +# or match on a path name to a jar or war file followed by arbitraty arguments # - note, jar files ending with ".jar" is only a convention, not a requirement. #Theoretically, any valid file name could occur here. -/^[0-9]+ .*\.jar($| .*$)/ { +/^[0-9]+ .*\.(jar|war)($| .*$)/ { current=1; } diff --git a/test/sun/tools/jps/jps-l_Output1.awk b/test/sun/tools/jps/jps-l_Output1.awk index 5280197ed6b8d96038a59b021190afc1ebad9881..08a48c176592ba27fb66eebc2fc03edcc945303e 100644 --- a/test/sun/tools/jps/jps-l_Output1.awk +++ b/test/sun/tools/jps/jps-l_Output1.awk @@ -8,10 +8,10 @@ BEGIN { matched++; } -# or match on a jar file name - note, jar files ending with +# or match on a jar or war file name - note, jar files ending with # ".jar" is only a convention , not a requirement. Theoretically, # any valid file name could occur here. -/^[0-9]+ .*\.jar$/ { +/^[0-9]+ .*\.(jar|war)$/ { matched++; } diff --git a/test/sun/tools/jps/jps_Output1.awk b/test/sun/tools/jps/jps_Output1.awk index 1781bc560e32b785e944f884b3c0955bf9e30b79..c64b0f104f5b46d7b191e5fe58733b8fdd18f87a 100644 --- a/test/sun/tools/jps/jps_Output1.awk +++ b/test/sun/tools/jps/jps_Output1.awk @@ -8,10 +8,10 @@ BEGIN { matched++; } -# or match on a path name to a jar file - note, jar files ending with +# or match on a path name to a jar or war file - note, jar files ending with # ".jar" is only a convention, not a requirement. Theoretically, # any valid file name could occur here. -/^[0-9]+ .*\.jar$/ { +/^[0-9]+ .*\.(jar|war)$/ { matched++; } diff --git a/test/tools/pack200/AttributeTests.java b/test/tools/pack200/AttributeTests.java index bcf4c7c92825114a9f6943b00ef89b181cf08e2c..09b9986175cf090aaec9346c2e4d8d8975f60af0 100644 --- a/test/tools/pack200/AttributeTests.java +++ b/test/tools/pack200/AttributeTests.java @@ -37,6 +37,7 @@ public class AttributeTests { public static void main(String... args) throws Exception { test6746111(); testMethodParameters(); + Utils.cleanup(); } /* diff --git a/test/tools/pack200/BandIntegrity.java b/test/tools/pack200/BandIntegrity.java index 1145972267f11d1c4260d270b18301afe5cb611b..2a59f3b8c1397f119d7d918eda86f0d02adb59d4 100644 --- a/test/tools/pack200/BandIntegrity.java +++ b/test/tools/pack200/BandIntegrity.java @@ -40,7 +40,7 @@ import java.util.List; * the java packer and unpacker must be called in the same java instance. */ public class BandIntegrity { - public static void main(String... args) throws IOException { + public static void main(String... args) throws IOException { File testFile = new File("test.jar"); Utils.jar("cvf", testFile.getName(), "-C", Utils.TEST_CLS_DIR.getAbsolutePath(), @@ -56,6 +56,7 @@ public class BandIntegrity { Utils.createFile(configFile, scratch); File outFile = new File("out.jar"); Utils.repack(testFile, outFile, true, - "-v", "--config-file=" + configFile.getName()); + "-v", "--config-file=" + configFile.getName()); + Utils.cleanup(); } } diff --git a/test/tools/pack200/CommandLineTests.java b/test/tools/pack200/CommandLineTests.java index 4e0c8b1e0036ff23e755f74f042dd9ec3e235984..2a53b30904600f66237aaf26179b6c552ad50eee 100644 --- a/test/tools/pack200/CommandLineTests.java +++ b/test/tools/pack200/CommandLineTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -83,6 +83,11 @@ public class CommandLineTests { Utils.recursiveCopy(Utils.JavaSDK, EXP_SDK); creatConfigFile(); } + // cleanup the test area + static void cleanup() throws IOException { + Utils.recursiveDelete(EXP_SDK); + Utils.cleanup(); + } // Hopefully, this should be kept in sync with what the installer does. static void creatConfigFile() throws IOException { @@ -172,6 +177,7 @@ public class CommandLineTests { init(); testJRE(); testJDK(); + cleanup(); // cleanup only if we pass successfully } catch (IOException ioe) { throw new RuntimeException(ioe); } diff --git a/test/tools/pack200/InstructionTests.java b/test/tools/pack200/InstructionTests.java index 171fe4ee88a24e8377e9c84c4bcf80de42d7bb13..569b7a0acb09fbdb1c979f60ddd2d10b5e2d8ff8 100644 --- a/test/tools/pack200/InstructionTests.java +++ b/test/tools/pack200/InstructionTests.java @@ -35,6 +35,7 @@ import java.util.List; public class InstructionTests { public static void main(String... args) throws Exception { testInvokeOpCodes(); + Utils.cleanup(); } /* * the following should produce invokestatic and invokespecial diff --git a/test/tools/pack200/Pack200Props.java b/test/tools/pack200/Pack200Props.java index 61b718ea9d9d58959b916c6a1cda51342539e6df..50fb0b147430999c7962ef8a717a537448ec0d0b 100644 --- a/test/tools/pack200/Pack200Props.java +++ b/test/tools/pack200/Pack200Props.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,6 +31,7 @@ */ import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -45,11 +46,12 @@ import java.util.jar.Pack200.Packer; public class Pack200Props { - public static void main(String... args) { + public static void main(String... args) throws IOException { verifyDefaults(); File out = new File("test" + Utils.PACK_FILE_EXT); out.delete(); verifySegmentLimit(out); + Utils.cleanup(); } static void verifySegmentLimit(File outFile) { diff --git a/test/tools/pack200/Pack200Test.java b/test/tools/pack200/Pack200Test.java index d897bf8682491d12d56a7c8a3526717d05277a31..b4226f2845a4e986c64499318a11e555369a2bae 100644 --- a/test/tools/pack200/Pack200Test.java +++ b/test/tools/pack200/Pack200Test.java @@ -66,7 +66,7 @@ public class Pack200Test { } } - private static void doPackUnpack() { + private static void doPackUnpack() throws IOException { for (File in : jarList) { JarOutputStream javaUnpackerStream = null; JarOutputStream nativeUnpackerStream = null; @@ -117,12 +117,13 @@ public class Pack200Test { Utils.close((Closeable) jarFile); } } + Utils.cleanup(); // cleanup artifacts, if successful run } /** * @param args the command line arguments */ - public static void main(String[] args) { + public static void main(String[] args) throws IOException { // select the jars carefully, adding more jars will increase the // testing time, especially for jprt. jarList.add(Utils.locateJar("tools.jar")); diff --git a/test/tools/pack200/PackageVersionTest.java b/test/tools/pack200/PackageVersionTest.java index fe6d5d9cb596d8a7040ae29300d3afb77934721e..dc109b8a39188d508715a89847cb4446fd812216 100644 --- a/test/tools/pack200/PackageVersionTest.java +++ b/test/tools/pack200/PackageVersionTest.java @@ -1,6 +1,5 @@ - /* - * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -54,7 +53,7 @@ public class PackageVersionTest { public final static int JAVA7_PACKAGE_MAJOR_VERSION = 170; public final static int JAVA7_PACKAGE_MINOR_VERSION = 1; - public static void main(String... args) { + public static void main(String... args) throws IOException { if (!javaHome.getName().endsWith("jre")) { throw new RuntimeException("Error: requires an SDK to run"); } @@ -78,6 +77,7 @@ public class PackageVersionTest { // test for resource file, ie. no class files verifyPack("Test6.java", JAVA5_PACKAGE_MAJOR_VERSION, JAVA5_PACKAGE_MINOR_VERSION); + Utils.cleanup(); } static void verify6991164() { diff --git a/test/tools/pack200/RepackTest.java b/test/tools/pack200/RepackTest.java index 774e0d66eb3141201364bfc32c76c4fef0136187..8a3d86e7c94c12fc7163c547d7daccc84d589d3e 100644 --- a/test/tools/pack200/RepackTest.java +++ b/test/tools/pack200/RepackTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,6 +36,7 @@ public class RepackTest { public static void main(String... args) throws Exception { testRepack(); + Utils.cleanup(); } /* diff --git a/test/tools/pack200/T7007157.java b/test/tools/pack200/T7007157.java index 72f8792c22b6888a24d950f36d3d247e834abf52..29a8ca7fc1faac2b23c23bb73982a18ec87e982f 100644 --- a/test/tools/pack200/T7007157.java +++ b/test/tools/pack200/T7007157.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -63,5 +63,6 @@ public class T7007157 { Utils.close(fos); Utils.close(jarFile); } + Utils.cleanup(); } } diff --git a/test/tools/pack200/TestExceptions.java b/test/tools/pack200/TestExceptions.java index 0778cf5c7e17fe4a837b9acd4a91e045871cf9c9..1b6f39a78cc8e56b17f2f0ee7a2a76af8af7ea38 100644 --- a/test/tools/pack200/TestExceptions.java +++ b/test/tools/pack200/TestExceptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -219,12 +219,13 @@ public class TestExceptions { } } - public static void main(String... args) { + public static void main(String... args) throws IOException { init(); pack200Test1(); pack200Test2(); pack200Test3(); unpack200Test1(); + Utils.cleanup(); } // containers for test inputs and management diff --git a/test/tools/pack200/TimeStamp.java b/test/tools/pack200/TimeStamp.java index 8dfc2d9bc2ea5fe13323b0b1ee86709a859b8ef2..acce4624aab82c026d4a30f64975b1a9dc210ca6 100644 --- a/test/tools/pack200/TimeStamp.java +++ b/test/tools/pack200/TimeStamp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -149,6 +149,7 @@ public class TimeStamp { Utils.close(jf1); Utils.close(jf2); } + Utils.cleanup(); if (errors > 0) { throw new RuntimeException("FAIL:" + errors + " error(s) encounted"); } diff --git a/test/tools/pack200/UnpackerMemoryTest.java b/test/tools/pack200/UnpackerMemoryTest.java index fc63d154f9061e68738a9d09383aecbe9808e3fb..ec8ffb6a402aa17c3cff8bf324d135c26da6792d 100644 --- a/test/tools/pack200/UnpackerMemoryTest.java +++ b/test/tools/pack200/UnpackerMemoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -81,6 +81,7 @@ public class UnpackerMemoryTest { Utils.close(fos); } } + Utils.cleanup(); } } diff --git a/test/tools/pack200/Utils.java b/test/tools/pack200/Utils.java index df3426431d4d56974830f2f015179272aa1f9eb1..b1bc2f894b1cebaf01d408f2f37ef8aa515f9186 100644 --- a/test/tools/pack200/Utils.java +++ b/test/tools/pack200/Utils.java @@ -75,6 +75,7 @@ class Utils { static final File TEST_CLS_DIR = new File(System.getProperty("test.classes")); static final String VERIFIER_DIR_NAME = "pack200-verifier"; static final File VerifierJar = new File(VERIFIER_DIR_NAME + JAR_FILE_EXT); + static final File XCLASSES = new File("xclasses"); private Utils() {} // all static @@ -95,8 +96,7 @@ class Utils { } List javaFileList = findFiles(srcDir, createFilter(JAVA_FILE_EXT)); File tmpFile = File.createTempFile("javac", ".tmp"); - File classesDir = new File("xclasses"); - classesDir.mkdirs(); + XCLASSES.mkdirs(); FileOutputStream fos = null; PrintStream ps = null; try { @@ -111,14 +111,14 @@ class Utils { } compiler("-d", - "xclasses", + XCLASSES.getName(), "@" + tmpFile.getAbsolutePath()); jar("cvfe", VerifierJar.getName(), "sun.tools.pack.verify.Main", "-C", - "xclasses", + XCLASSES.getName(), "."); } @@ -175,6 +175,33 @@ class Utils { }; } + /* + * clean up all the usual suspects + */ + static void cleanup() throws IOException { + recursiveDelete(XCLASSES); + List toDelete = new ArrayList<>(); + toDelete.addAll(Utils.findFiles(new File("."), + Utils.createFilter(".out"))); + toDelete.addAll(Utils.findFiles(new File("."), + Utils.createFilter(".bak"))); + toDelete.addAll(Utils.findFiles(new File("."), + Utils.createFilter(".jar"))); + toDelete.addAll(Utils.findFiles(new File("."), + Utils.createFilter(".pack"))); + toDelete.addAll(Utils.findFiles(new File("."), + Utils.createFilter(".bnd"))); + toDelete.addAll(Utils.findFiles(new File("."), + Utils.createFilter(".txt"))); + toDelete.addAll(Utils.findFiles(new File("."), + Utils.createFilter(".idx"))); + toDelete.addAll(Utils.findFiles(new File("."), + Utils.createFilter(".gidx"))); + for (File f : toDelete) { + f.delete(); + } + } + static final FileFilter DIR_FILTER = new FileFilter() { public boolean accept(File pathname) { if (pathname.isDirectory()) { @@ -199,6 +226,9 @@ class Utils { Files.createDirectories(parent); } Files.copy(src.toPath(), dst.toPath(), COPY_ATTRIBUTES, REPLACE_EXISTING); + if (dst.isDirectory() && !dst.canWrite()) { + dst.setWritable(true); + } } static String baseName(File file, String extension) { diff --git a/test/tools/pack200/typeannos/TestTypeAnnotations.java b/test/tools/pack200/typeannos/TestTypeAnnotations.java index 598185aaabc783ba4f1128f8c7e99a059f7875ad..f00801b5b14c5fa6956fbc1fe24bb357fb4b330b 100644 --- a/test/tools/pack200/typeannos/TestTypeAnnotations.java +++ b/test/tools/pack200/typeannos/TestTypeAnnotations.java @@ -41,5 +41,6 @@ public class TestTypeAnnotations { "-C", Utils.TEST_CLS_DIR.getAbsolutePath(), "."); Utils.testWithRepack(testFile, "--unknown-attribute=error"); + Utils.cleanup(); } }