--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/make/common/Defs-embedded.gmk Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,53 @@
+#
+# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+#
+# Variable definitions for SE Embedded builds. This file should
+# not contain rules.
+#
+ifdef JAVASE_EMBEDDED
+
+# Compress jar files
+COMPRESS_JARS = true
+
+# Don't mmap zip files
+LIBZIP_CAN_USE_MMAP = false
+
+# Disable ALSA version check
+REQUIRED_ALSA_VERSION =
+
+# Compilation settings
+OTHER_CPPFLAGS += -DJAVASE_EMBEDDED
+
+# Product naming
+PRODUCT_SUFFIX = SE Runtime Environment for Embedded
+RUNTIME_NAME = $(PRODUCT_NAME) $(PRODUCT_SUFFIX)
+
+# Reduced JRE locations
+JRE_REDUCED_HEADLESS_IMAGE_DIR = $(ABS_OUTPUTDIR)/j2re-reduced-headless-image
+JRE_REDUCED_IMAGE_DIR = $(ABS_OUTPUTDIR)/j2re-reduced-image
+
+endif # JAVASE_EMBEDDED
+
--- a/jdk/make/common/Defs.gmk Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/common/Defs.gmk Sun Apr 10 10:23:28 2011 -0700
@@ -116,6 +116,12 @@
include $(JDK_TOPDIR)/make/common/Defs-$(PLATFORM).gmk
#
+# SE-Embedded support, if enabled
+#
+
+include $(JDK_TOPDIR)/make/common/Defs-embedded.gmk
+
+#
# Cross-compilation Settings
#
ifdef CROSS_COMPILE_ARCH
@@ -144,7 +150,6 @@
VM_NAME = client
endif
-
#
# Freetype logic is applicable to OpenJDK only
#
--- a/jdk/make/common/Library.gmk Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/common/Library.gmk Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
#
-# Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -78,7 +78,7 @@
endif
$(ACTUAL_LIBRARY):: $(INIT) $(TEMPDIR) $(LIBDIR) $(BINDIR) $(EXTDIR) classheaders
-
+ @$(ECHO) Building lib:$(ACTUAL_LIBRARY)
#
# COMPILE_APPROACH: Different approaches to compile up the native object
# files as quickly as possible.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/make/common/Release-embedded.gmk Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,232 @@
+#
+# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+#
+# SE-Embedded Reduced JRE targets
+#
+ifdef JAVASE_EMBEDDED
+
+reduced-image-jre reduced-headless-image-jre ::
+ @$(ECHO) ">>>Making "$@" @ `$(DATE)` ..."
+
+# Add the reduced-jre images as pre-reqs. These will be processed last
+images:: reduced-image-jre reduced-headless-image-jre
+
+
+######################################################
+# Create the headless rt.jar
+######################################################
+
+NOT_HEADLESS_RT_JAR_LIST = $(ABS_TEMPDIR)/not_hl_rt_jar.list
+HEADLESS_RT_JAR_FILELIST=$(JARFILELISTS_TEMPDIR)/hl_rt_jar_list
+TOTAL_HEADLESS_JAR_FILELIST=$(REORDER_TEMPDIR)/hl_file_list
+HEADLESS_CLASSLIST=$(ABS_TEMPDIR)/headless_classlist
+
+# Add the jar file directories that we don't want in the
+# headless JRE. If you want to remove most classes in a
+# directory, put the directory in the NOT_HEADLESS_RT_JAR_LIST
+# and put the individual classes you want to keep in the
+# HEADLESS_CLASSLIST file.
+$(NOT_HEADLESS_RT_JAR_LIST): $(NOT_RT_JAR_LIST)
+ $(RM) $(HEADLESS_CLASSLIST)
+ $(RM) $(NOT_HEADLESS_RT_JAR_LIST)
+ $(CP) $(NOT_RT_JAR_LIST) $(NOT_HEADLESS_RT_JAR_LIST)
+ $(ECHO) "sun/awt/motif/" >> $@
+ $(ECHO) "sun/awt/X11/" >> $@
+ $(ECHO) "sun/applet/" >> $@
+ $(ECHO) "sun/java2d/opengl/" >> $@
+ $(ECHO) "com/sun/java/swing/plaf/" >> $@
+ $(ECHO) "sun/awt/motif/MFontConfiguration" >$(HEADLESS_CLASSLIST)
+ $(ECHO) "sun/applet/AppContextCreator" >>$(HEADLESS_CLASSLIST)
+ $(ECHO) "sun/applet/AppletAudioClip" >>$(HEADLESS_CLASSLIST)
+ $(ECHO) "sun/java2d/opengl/GLXSurfaceData" >>$(HEADLESS_CLASSLIST)
+ $(ECHO) "sun/java2d/opengl/GLXSurfaceData"\$$"GLXOffScreenSurfaceData" >>$(HEADLESS_CLASSLIST)
+ $(ECHO) "sun/java2d/opengl/GLXVolatileSurfaceManager" >>$(HEADLESS_CLASSLIST)
+ $(ECHO) "sun/java2d/opengl/OGLSurfaceData" >>$(HEADLESS_CLASSLIST)
+
+$(TOTAL_HEADLESS_JAR_FILELIST): $(JARREORDER_JARFILE) $(NOT_HEADLESS_RT_JAR_LIST)
+ $(prep-target)
+ $(RM) $@.temp
+ $(CD) $(CLASSBINDIR) ; \
+ $(BOOT_JAVA_CMD) -jar $(JARREORDER_JARFILE) \
+ -o $@.temp $(HEADLESS_CLASSLIST) $(NOT_HEADLESS_RT_JAR_LIST) .
+ $(MV) $@.temp $@
+ @$(CD) $(CLASSBINDIR); $(java-vm-cleanup)
+
+# Create the headless rt.jar file list & non-class files list
+MakeHeadlessJarFileList: $(TOTAL_HEADLESS_JAR_FILELIST) $(JARSPLIT_JARFILE)
+ @$(RM) $(HEADLESS_RT_JAR_FILELIST) $(RES_JAR_FILELIST)
+ $(BOOT_JAVA_CMD) -jar $(JARSPLIT_JARFILE) $(TOTAL_HEADLESS_JAR_FILELIST) \
+ -o $(HEADLESS_RT_JAR_FILELIST) $(RES_JAR_FILELIST)
+ @$(java-vm-cleanup)
+
+# Create headless rt.jar
+HL_RT_JAR=$(ABS_TEMPDIR)/rt-hl-orig.jar
+$(HL_RT_JAR): MakeHeadlessJarFileList $(JAR_MANIFEST_FILE)
+ $(prep-target)
+ $(CD) $(CLASSBINDIR) ; \
+ $(BOOT_JAR_CMD) $(CREATE_JAR_OPTS) $(JAR_MANIFEST_FILE) $@ @$(HEADLESS_RT_JAR_FILELIST) \
+ $(JAR_JFLAGS)
+ @$(CD) $(CLASSBINDIR); $(java-vm-cleanup)
+
+
+#
+# Produce a reduced Headful JRE for Embedded Devices
+#
+# The deployment binaries are added during the deployment build process
+#
+
+# Binaries that don't get included in reduced jre image bin directory
+NOT_REDUCEDJRE_BIN = \
+ java_vm \
+ kinit \
+ klist \
+ ktab \
+ orbd \
+ policytool \
+ rmid \
+ rmiregistry \
+ servertool \
+ tnameserv \
+ pack200 \
+ unpack200
+
+# jars/resources/libs that don't get included in reduced jre image lib directory
+NOT_REDUCEDJRE_LIB = \
+ charsets.jar \
+ ext/dnsns.jar \
+ ext/localedata.jar \
+ $(LIBARCH)/client/classes.jsa \
+ $(LIBARCH)/libjavaplugin_jni.so \
+ $(LIBARCH)/libjavaplugin_nscp_gcc29.so \
+ $(LIBARCH)/libjavaplugin_nscp.so \
+ $(LIBARCH)/libjavaplugin_oji.so
+
+
+ifeq ($(PLATFORM), linux)
+ STRIP_OPTS = --strip-unneeded
+else
+ STRIP_OPTS = -x
+endif
+
+
+reduced-image-jre::
+ @$(ECHO) Starting to Produce Reduced JRE
+ @#
+ @# First make a copy of the full JRE
+ @#
+ $(RM) -r $(JRE_REDUCED_IMAGE_DIR)
+ $(MKDIR) -p $(JRE_REDUCED_IMAGE_DIR)
+ $(CD) $(JRE_IMAGE_DIR); \
+ $(TAR) cf - . | ($(CD) $(JRE_REDUCED_IMAGE_DIR); $(TAR) xf - );
+
+ @# strip the main .so files
+ $(STRIP) $(STRIP_OPTS) $(JRE_REDUCED_IMAGE_DIR)/lib/$(LIBARCH)/client/libjvm.so
+ifndef BUILD_CLIENT_ONLY
+ $(STRIP) $(STRIP_OPTS) $(JRE_REDUCED_IMAGE_DIR)/lib/$(LIBARCH)/server/libjvm.so
+endif
+
+ @#
+ @# Remove all of the files that are not needed for the
+ @# reduced JRE
+ @#
+ for l in $(NOT_REDUCEDJRE_BIN) ; do \
+ $(RM) $(JRE_REDUCED_IMAGE_DIR)/bin/$$l ; \
+ done
+ for l in $(NOT_REDUCEDJRE_LIB) ; do \
+ $(RM) $(JRE_REDUCED_IMAGE_DIR)/lib/$$l ; \
+ done
+
+ @# Remove misc. other files
+ $(RM) -r $(JRE_REDUCED_IMAGE_DIR)/man
+ $(RM) -f $(JRE_REDUCED_IMAGE_DIR)/CHANGES
+
+ @$(ECHO) Done Creating Reduced JRE
+
+#
+# Produce a reduced Headless JRE
+#
+reduced-headless-image-jre:: $(RT_JAR) $(RESOURCES_JAR) $(BUILD_META_INDEX) $(HL_RT_JAR)
+ @$(ECHO) Starting to Produce Reduced Headless JRE
+ @#
+ @# First make a copy of the reduced JRE we just built
+ @#
+ $(RM) -r $(JRE_REDUCED_HEADLESS_IMAGE_DIR)
+ $(MKDIR) -p $(JRE_REDUCED_HEADLESS_IMAGE_DIR)
+ $(CD) $(JRE_REDUCED_IMAGE_DIR); \
+ $(TAR) cf - . | ($(CD) $(JRE_REDUCED_HEADLESS_IMAGE_DIR); $(TAR) xf - );
+
+ @# Replace the full rt.jar with the headless rt.jar
+ $(RM) -f $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/rt.jar
+ $(CP) $(HL_RT_JAR) $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/rt.jar
+
+ @#
+ @# Remove all of the files that are not needed for the
+ @# reduced Headless JRE
+ @#
+ $(RM) -f $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/$(LIBARCH)/gtkhelper
+ $(RM) $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/$(LIBARCH)/libjsoundalsa.so
+ $(RM) -r $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/audio
+ $(RM) -fr $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/applet
+ $(RM) $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/$(LIBARCH)/awt_robot
+ $(RM) -r $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/$(LIBARCH)/xawt
+ $(RM) -r $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/$(LIBARCH)/libsplashscreen.so
+ @# Remove oblique fonts and reduce font support to LucidaSansRegular only
+ $(RM) -fr $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/oblique-fonts
+ $(RM) -f $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/LucidaBrightDemiBold.ttf
+ $(RM) -f $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/LucidaBrightDemiItalic.ttf
+ $(RM) -f $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/LucidaBrightItalic.ttf
+ $(RM) -f $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/LucidaBrightRegular.ttf
+ $(RM) -f $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/LucidaSansDemiBold.ttf
+ $(RM) -f $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/LucidaTypewriterBold.ttf
+ $(RM) -f $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/LucidaTypewriterRegular.ttf
+
+ifeq ($(PLATFORM), linux)
+# put out minimal fonts.dir file for the remaining font
+ $(RM) -f $(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/fonts.dir
+ $(ECHO) 6>$(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/fonts.dir
+ $(ECHO) "LucidaSansRegular.ttf -b&h-lucidasans-medium-r-normal-sans-0-0-0-0-p-0-iso8859-1">>$(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/fonts.dir
+ $(ECHO) "LucidaSansRegular.ttf -b&h-lucidasans-medium-r-normal-sans-0-0-0-0-p-0-iso8859-2">>$(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/fonts.dir
+ $(ECHO) "LucidaSansRegular.ttf -b&h-lucidasans-medium-r-normal-sans-0-0-0-0-p-0-iso8859-4">>$(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/fonts.dir
+ $(ECHO) "LucidaSansRegular.ttf -b&h-lucidasans-medium-r-normal-sans-0-0-0-0-p-0-iso8859-5">>$(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/fonts.dir
+ $(ECHO) "LucidaSansRegular.ttf -b&h-lucidasans-medium-r-normal-sans-0-0-0-0-p-0-iso8859-7">>$(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/fonts.dir
+ $(ECHO) "LucidaSansRegular.ttf -b&h-lucidasans-medium-r-normal-sans-0-0-0-0-p-0-iso8859-9">>$(JRE_REDUCED_HEADLESS_IMAGE_DIR)/lib/fonts/fonts.dir
+
+endif # Linux
+
+ @#
+ @# all done with JRE reduced headless image
+ @#
+
+ @$(ECHO) Done Creating Reduced Headless JRE
+
+images-clobber::
+ $(RM) -r $(JRE_REDUCED_IMAGE_DIR)
+ $(RM) -r $(JRE_REDUCED_HEADLESS_IMAGE_DIR)
+
+.PHONY: reduced-image-jre reduced-headless-image-jre
+
+endif # JAVASE_EMBEDDED
+
--- a/jdk/make/common/Release.gmk Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/common/Release.gmk Sun Apr 10 10:23:28 2011 -0700
@@ -38,7 +38,7 @@
IMAGE_BINDIR = bin
-# The compiler should not issue a "Sun Propietary" warning when compiling
+# The compiler should not issue a "Proprietary" warning when compiling
# classes in the com.sun.java.swing.plaf packages, since we've always
# allowed, and even advocated, extending them (see bug 6476749).
#
@@ -195,6 +195,16 @@
fi
endef
+
+# no compression unless requested
+ifndef COMPRESS_JARS
+ CREATE_JAR_OPTS = c0mf
+ CREATE_JAR_OPTS_NOMANIFEST = c0f
+else
+ CREATE_JAR_OPTS = cmf
+ CREATE_JAR_OPTS_NOMANIFEST = cf
+endif
+
#
# Targets.
#
@@ -222,7 +232,7 @@
$(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
# Don't use these
image-jre:: initial-image-jre trim-image-jre identify-image-jre process-image-jre
@@ -613,7 +623,7 @@
$(RESOURCES_JAR): $(RES_JAR_FILELIST) $(JAR_MANIFEST_FILE)
$(prep-target)
$(CD) $(CLASSBINDIR) && \
- $(BOOT_JAR_CMD) c0mf $(JAR_MANIFEST_FILE) $@ \
+ $(BOOT_JAR_CMD) $(CREATE_JAR_OPTS) $(JAR_MANIFEST_FILE) $@ \
@$(RES_JAR_FILELIST) $(BOOT_JAR_JFLAGS)
@$(CD) $(CLASSBINDIR) && $(java-vm-cleanup)
@@ -622,7 +632,7 @@
$(JSSE_JAR): $(JAR_MANIFEST_FILE)
$(prep-target)
$(CD) $(CLASSBINDIR) && \
- $(BOOT_JAR_CMD) c0mf $(JAR_MANIFEST_FILE) $@ \
+ $(BOOT_JAR_CMD) $(CREATE_JAR_OPTS) $(JAR_MANIFEST_FILE) $@ \
$(JSSE_CLASSES_DIRS) $(BOOT_JAR_JFLAGS)
@$(CD) $(CLASSBINDIR) && $(java-vm-cleanup)
@@ -669,7 +679,7 @@
$(RT_JAR): $(RT_JAR_FILELIST) $(JAR_MANIFEST_FILE)
$(prep-target)
$(CD) $(CLASSBINDIR) && \
- $(BOOT_JAR_CMD) c0mf $(JAR_MANIFEST_FILE) $@ \
+ $(BOOT_JAR_CMD) $(CREATE_JAR_OPTS) $(JAR_MANIFEST_FILE) $@ \
@$(RT_JAR_FILELIST) $(BOOT_JAR_JFLAGS)
@$(CD) $(CLASSBINDIR) && $(java-vm-cleanup)
@@ -677,6 +687,10 @@
BUILDMETAINDEX_JARFILE = $(ABS_BUILDTOOLJARDIR)/buildmetaindex.jar
+# SE-Embedded targets if enabled
+include $(JDK_TOPDIR)/make/common/Release-embedded.gmk
+
+
######################################################
# JRE Image
######################################################
@@ -924,7 +938,7 @@
@# lib/tools.jar
@#
$(CD) $(CLASSBINDIR) && \
- $(BOOT_JAR_CMD) c0f $(ABS_LIBDIR)/tools.jar \
+ $(BOOT_JAR_CMD) $(CREATE_JAR_OPTS_NOMANIFEST) $(ABS_LIBDIR)/tools.jar \
$(TOOLS) $(BOOT_JAR_JFLAGS)
@$(CD) $(CLASSBINDIR) && $(java-vm-cleanup)
$(CP) $(LIBDIR)/tools.jar $(JDK_IMAGE_DIR)/lib/tools.jar
@@ -937,7 +951,7 @@
-Acom.sun.tools.javac.sym.Jar=$(RT_JAR) \
-Acom.sun.tools.javac.sym.Dest=$(OUTPUTDIR)/symbols/META-INF/sym/rt.jar \
$(CORE_PKGS) $(NON_CORE_PKGS) $(EXCLUDE_PROPWARN_PKGS) $(EXPORTED_PRIVATE_PKGS)
- $(BOOT_JAR_CMD) c0f $(LIBDIR)/ct.sym \
+ $(BOOT_JAR_CMD) $(CREATE_JAR_OPTS_NOMANIFEST) $(LIBDIR)/ct.sym \
-C $(OUTPUTDIR)/symbols META-INF $(BOOT_JAR_JFLAGS)
@$(java-vm-cleanup)
$(CP) $(LIBDIR)/ct.sym $(JDK_IMAGE_DIR)/lib/ct.sym
--- a/jdk/make/common/shared/Sanity-Settings.gmk Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/common/shared/Sanity-Settings.gmk Sun Apr 10 10:23:28 2011 -0700
@@ -185,7 +185,9 @@
endif
endif
ifeq ($(PLATFORM),linux)
- ALL_SETTINGS+=$(call addRequiredSetting,ALSA_VERSION)
+ ifdef REQUIRED_ALSA_VERSION
+ ALL_SETTINGS+=$(call addRequiredSetting,ALSA_VERSION)
+ endif
endif
ALL_SETTINGS+=$(call addRequiredVersionSetting,OS_VERSION)
ALL_SETTINGS+=$(call addOptionalSetting,OS_VARIANT_NAME)
--- a/jdk/make/java/java/Makefile Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/java/java/Makefile Sun Apr 10 10:23:28 2011 -0700
@@ -198,10 +198,12 @@
#
# What to link?
+# On Windows, shell32 is not normally required and so it is delay loaded.
#
ifeq ($(PLATFORM),windows)
OTHER_LDLIBS += $(JVMLIB) -libpath:$(OBJDIR)/../../../fdlibm/$(OBJDIRNAME) fdlibm.lib \
- -libpath:$(OBJDIR)/../../../verify/$(OBJDIRNAME) verify.lib
+ -libpath:$(OBJDIR)/../../../verify/$(OBJDIRNAME) verify.lib \
+ shell32.lib delayimp.lib /DELAYLOAD:shell32.dll
else
OTHER_LDLIBS += $(JVMLIB) -lverify $(LIBSOCKET) $(LIBNSL) -ldl \
-L$(OBJDIR)/../../../fdlibm/$(OBJDIRNAME) -lfdlibm.$(ARCH)
--- a/jdk/make/java/management/Makefile Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/java/management/Makefile Sun Apr 10 10:23:28 2011 -0700
@@ -86,7 +86,8 @@
-I$(SHARE_SRC)/native/sun/management
ifeq ($(PLATFORM),windows)
- OTHER_LDLIBS += $(JVMLIB)
+ # Need process status helper API (psapi) on Windows
+ OTHER_LDLIBS += $(JVMLIB) psapi.lib
endif
#
--- a/jdk/make/java/net/Makefile Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/java/net/Makefile Sun Apr 10 10:23:28 2011 -0700
@@ -37,10 +37,6 @@
AUTO_FILES_JAVA_DIRS = java/net
ifeq ($(PLATFORM), windows)
- # Windows 9x module only needed on 32-bit build
- ifeq ($(ARCH_DATA_MODEL), 32)
- FILES_c += NetworkInterface_win9x.c
- endif
FILES_c += NTLMAuthSequence.c
FILES_c += NetworkInterface_winXP.c
else
@@ -96,7 +92,9 @@
include $(BUILDDIR)/common/Library.gmk
ifeq ($(PLATFORM), windows)
- OTHER_LDLIBS = ws2_32.lib $(JVMLIB)
+ OTHER_LDLIBS = ws2_32.lib $(JVMLIB) \
+ secur32.lib iphlpapi.lib delayimp.lib \
+ /DELAYLOAD:secur32.dll /DELAYLOAD:iphlpapi.dll
else
OTHER_LDLIBS = $(LIBSOCKET) $(LIBNSL) -ldl $(JVMLIB)
endif
--- a/jdk/make/java/zip/Makefile Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/java/zip/Makefile Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
#
-# Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -50,7 +50,10 @@
java/util/jar/JarFile.java
ifneq ($(PLATFORM), windows)
-OTHER_CFLAGS += -DUSE_MMAP
+ # Use mmap unless explicitly disallowed
+ ifneq ($(LIBZIP_CAN_USE_MMAP),false)
+ OTHER_CFLAGS += -DUSE_MMAP
+ endif
endif
#
--- a/jdk/make/jprt.properties Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/jprt.properties Sun Apr 10 10:23:28 2011 -0700
@@ -52,8 +52,11 @@
${jprt.my.windows.i586}-{product|fastdebug}, \
windows_x64_5.2-{product|fastdebug}
+# User can select the test set with jprt submit "-testset name" option
+jprt.my.test.set=${jprt.test.set}
+
# Standard vm test target
-jprt.test.targets= \
+jprt.vm.default.test.targets= \
solaris_sparc_5.10-product-c1-jvm98, \
solaris_sparcv9_5.10-product-c2-jvm98, \
solaris_i586_5.10-product-c1-jvm98, \
@@ -63,8 +66,10 @@
${jprt.my.windows.i586}-product-c1-jvm98, \
windows_x64_5.2-product-c2-jvm98
-# User can select the test set with jprt submit "-testset name" option
-jprt.my.test.set=${jprt.test.set}
+# Select vm testlist to use (allow for testset to be empty too)
+jprt.vm.all.test.targets=${jprt.vm.default.test.targets}
+jprt.vm..test.targets=${jprt.vm.default.test.targets}
+jprt.test.targets=${jprt.vm.${jprt.my.test.set}.test.targets}
# Default jdk test targets in test/Makefile (no fastdebug & limited c2)
jprt.make.rule.default.test.targets= \
@@ -281,6 +286,21 @@
${jprt.my.windows.i586}-product-c1-jdk_tools2, \
windows_x64_5.2-product-c2-jdk_tools2
+# JCK test targets in test/Makefile (no fastdebug & limited c2, windows broken)
+jprt.my.jck.test.target.set= \
+ solaris_sparc_5.10-product-c1-JCK7TESTRULE, \
+ solaris_sparcv9_5.10-product-c2-JCK7TESTRULE, \
+ solaris_i586_5.10-product-c1-JCK7TESTRULE, \
+ solaris_x64_5.10-product-c2-JCK7TESTRULE, \
+ linux_i586_2.6-product-c1-JCK7TESTRULE, \
+ linux_x64_2.6-product-c2-JCK7TESTRULE
+
+# JCK testset targets (e.g. jprt submit -testset jck ... )
+jprt.make.rule.jck.test.targets= \
+ ${jprt.my.jck.test.target.set:JCK7TESTRULE=jck7devtools}, \
+ ${jprt.my.jck.test.target.set:JCK7TESTRULE=jck7runtime}, \
+ ${jprt.my.jck.test.target.set:JCK7TESTRULE=jck7compiler}
+
# Select list to use (allow for testset to be empty too)
jprt.make.rule..test.targets=${jprt.make.rule.default.test.targets}
jprt.make.rule.test.targets=${jprt.make.rule.${jprt.my.test.set}.test.targets}
--- a/jdk/make/launchers/Makefile Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/launchers/Makefile Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
#
-# Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -44,8 +44,17 @@
endef
# Run MAKE $@ for all generic launchers
+ifndef BUILD_HEADLESS_ONLY
+define make-appletviewer
+$(call make-launcher, appletviewer, sun.applet.Main, , )
+endef
+else
+define make-appletviewer
+endef
+endif
+
define make-all-launchers
-$(call make-launcher, appletviewer, sun.applet.Main, , )
+$(make-appletviewer)
$(call make-launcher, apt, com.sun.tools.apt.Main, , )
$(call make-launcher, extcheck, com.sun.tools.extcheck.Main, , )
$(call make-launcher, idlj, com.sun.tools.corba.se.idl.toJavaPortable.Compile, , )
--- a/jdk/make/mkdemo/jfc/Makefile Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/mkdemo/jfc/Makefile Sun Apr 10 10:23:28 2011 -0700
@@ -39,7 +39,8 @@
Notepad \
SampleTree \
SwingApplet \
- TableExample
+ TableExample \
+ TransparentRuler
# Some demos aren't currently included in OpenJDK
ifndef OPENJDK
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/make/mkdemo/jfc/TransparentRuler/Makefile Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,44 @@
+#
+# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+#
+# Makefile to build the TransparentRuler demo.
+#
+
+BUILDDIR = ../../..
+PRODUCT = demo/jfc
+DEMONAME = TransparentRuler
+include $(BUILDDIR)/common/Defs.gmk
+
+DEMO_ROOT = $(SHARE_SRC)/demo/jfc/$(DEMONAME)
+DEMO_TOPFILES = ./README.txt
+DEMO_MAINCLASS = transparentruler.Ruler
+DEMO_DESTDIR = $(DEMODIR)/jfc/$(DEMONAME)
+
+
+#
+# Demo jar building rules.
+#
+include $(BUILDDIR)/common/Demo.gmk
--- a/jdk/make/sun/Makefile Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/sun/Makefile Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
#
-# Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -69,10 +69,17 @@
# nio need to be compiled before awt to have all charsets ready
SUBDIRS = jar security javazic misc net nio text launcher
+
+ifdef BUILD_HEADLESS_ONLY
+ DISPLAY_LIBS = awt $(HEADLESS_SUBDIR)
+ DISPLAY_TOOLS =
+else
+ DISPLAY_LIBS = awt splashscreen $(XAWT_SUBDIR) $(HEADLESS_SUBDIR)
+ DISPLAY_TOOLS = applet
+endif
SUBDIRS_desktop = audio $(RENDER_SUBDIR) image \
- awt splashscreen $(XAWT_SUBDIR) \
- $(HEADLESS_SUBDIR) $(DGA_SUBDIR) \
- jawt font jpeg cmm applet beans
+ $(DISPLAY_LIBS) $(DGA_SUBDIR) \
+ jawt font jpeg cmm $(DISPLAY_TOOLS) beans
SUBDIRS_management = management
SUBDIRS_misc = $(ORG_SUBDIR) rmi $(JDBC_SUBDIR) tracing
SUBDIRS_tools = native2ascii serialver tools jconsole
--- a/jdk/make/sun/awt/mawt.gmk Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/sun/awt/mawt.gmk Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
#
-# Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -149,13 +149,13 @@
LIBXT = -lXt
else
# Allows for builds on Debian GNU Linux, X11 is in a different place
- LIBXT = $(firstword $(wildcard /usr/X11R6/lib/libXt.a) \
+ LIBXT = $(firstword $(wildcard $(OPENWIN_LIB)/libXt.a) \
$(wildcard /usr/lib/libXt.a))
- LIBSM = $(firstword $(wildcard /usr/X11R6/lib/libSM.a) \
+ LIBSM = $(firstword $(wildcard $(OPENWIN_LIB)/libSM.a) \
$(wildcard /usr/lib/libSM.a))
- LIBICE = $(firstword $(wildcard /usr/X11R6/lib/libICE.a) \
+ LIBICE = $(firstword $(wildcard $(OPENWIN_LIB)/libICE.a) \
$(wildcard /usr/lib/libICE.a))
- LIBXTST = $(firstword $(wildcard /usr/X11R6/lib/libXtst.a) \
+ LIBXTST = $(firstword $(wildcard $(OPENWIN_LIB)/libXtst.a) \
$(wildcard /usr/lib/libXtst.a))
endif
endif
@@ -224,9 +224,9 @@
$(EVENT_MODEL)
ifeq ($(PLATFORM), linux)
-# Checking for the X11/extensions headers at the additional location
- CPPFLAGS += -I/X11R6/include/X11/extensions \
- -I/usr/include/X11/extensions
+ # Checking for the X11/extensions headers at the additional location
+ CPPFLAGS += -I$(firstword $(wildcard $(OPENWIN_HOME)/include/X11/extensions) \
+ $(wildcard /usr/include/X11/extensions))
endif
ifeq ($(PLATFORM), solaris)
--- a/jdk/make/sun/javazic/tzdata/VERSION Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/sun/javazic/tzdata/VERSION Sun Apr 10 10:23:28 2011 -0700
@@ -21,4 +21,4 @@
# or visit www.oracle.com if you need additional information or have any
# questions.
#
-tzdata2011d
+tzdata2011e
--- a/jdk/make/sun/javazic/tzdata/africa Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/sun/javazic/tzdata/africa Sun Apr 10 10:23:28 2011 -0700
@@ -734,6 +734,48 @@
# http://www.timeanddate.com/news/time/morocco-starts-dst-2010.html
# </a>
+# From Dan Abitol (2011-03-30):
+# ...Rules for Africa/Casablanca are the following (24h format)
+# The 3rd april 2011 at 00:00:00, [it] will be 3rd april 1:00:00
+# The 31th july 2011 at 00:59:59, [it] will be 31th July 00:00:00
+# ...Official links of change in morocco
+# The change was broadcast on the FM Radio
+# I ve called ANRT (telecom regulations in Morocco) at
+# +212.537.71.84.00
+# <a href="http://www.anrt.net.ma/fr/">
+# http://www.anrt.net.ma/fr/
+# </a>
+# They said that
+# <a href="http://www.map.ma/fr/sections/accueil/l_heure_legale_au_ma/view">
+# http://www.map.ma/fr/sections/accueil/l_heure_legale_au_ma/view
+# </a>
+# is the official publication to look at.
+# They said that the decision was already taken.
+#
+# More articles in the press
+# <a href="http://www.yabiladi.com/articles/details/5058/secret-l-heure-d-ete-maroc-lev">
+# http://www.yabiladi.com/articles/details/5058/secret-l-heure-d-ete-maroc-lev
+# </a>
+# e.html
+# <a href="http://www.lematin.ma/Actualite/Express/Article.asp?id=148923">
+# http://www.lematin.ma/Actualite/Express/Article.asp?id=148923
+# </a>
+# <a href="http://www.lavieeco.com/actualite/Le-Maroc-passe-sur-GMT%2B1-a-partir-de-dim">
+# http://www.lavieeco.com/actualite/Le-Maroc-passe-sur-GMT%2B1-a-partir-de-dim
+# anche-prochain-5538.html
+# </a>
+
+# From Petr Machata (2011-03-30):
+# They have it written in English here:
+# <a href="http://www.map.ma/eng/sections/home/morocco_to_spring_fo/view">
+# http://www.map.ma/eng/sections/home/morocco_to_spring_fo/view
+# </a>
+#
+# It says there that "Morocco will resume its standard time on July 31,
+# 2011 at midnight." Now they don't say whether they mean midnight of
+# wall clock time (i.e. 11pm UTC), but that's what I would assume. It has
+# also been like that in the past.
+
# RULE NAME FROM TO TYPE IN ON AT SAVE LETTER/S
Rule Morocco 1939 only - Sep 12 0:00 1:00 S
@@ -757,6 +799,8 @@
Rule Morocco 2009 only - Aug 21 0:00 0 -
Rule Morocco 2010 only - May 2 0:00 1:00 S
Rule Morocco 2010 only - Aug 8 0:00 0 -
+Rule Morocco 2011 only - Apr 3 0:00 1:00 S
+Rule Morocco 2011 only - Jul 31 0 0 -
# Zone NAME GMTOFF RULES FORMAT [UNTIL]
Zone Africa/Casablanca -0:30:20 - LMT 1913 Oct 26
0:00 Morocco WE%sT 1984 Mar 16
--- a/jdk/make/sun/javazic/tzdata/southamerica Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/sun/javazic/tzdata/southamerica Sun Apr 10 10:23:28 2011 -0700
@@ -1193,6 +1193,19 @@
# From Arthur David Olson (2011-03-02):
# The emol.com article mentions a water shortage as the cause of the
# postponement, which may mean that it's not a permanent change.
+
+# From Glenn Eychaner (2011-03-28):
+# The article:
+# <a href="http://diario.elmercurio.com/2011/03/28/_portada/_portada/noticias/7565897A-CA86-49E6-9E03-660B21A4883E.htm?id=3D{7565897A-CA86-49E6-9E03-660B21A4883E}">
+# http://diario.elmercurio.com/2011/03/28/_portada/_portada/noticias/7565897A-CA86-49E6-9E03-660B21A4883E.htm?id=3D{7565897A-CA86-49E6-9E03-660B21A4883E}
+# </a>
+#
+# In English:
+# Chile's clocks will go back an hour this year on the 7th of May instead
+# of this Saturday. They will go forward again the 3rd Saturday in
+# August, not in October as they have since 1968. This is a pilot plan
+# which will be reevaluated in 2012.
+
# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S
Rule Chile 1927 1932 - Sep 1 0:00 1:00 S
Rule Chile 1928 1932 - Apr 1 0:00 0 -
@@ -1222,13 +1235,16 @@
Rule Chile 1998 only - Mar Sun>=9 3:00u 0 -
Rule Chile 1998 only - Sep 27 4:00u 1:00 S
Rule Chile 1999 only - Apr 4 3:00u 0 -
-Rule Chile 1999 max - Oct Sun>=9 4:00u 1:00 S
+Rule Chile 1999 2010 - Oct Sun>=9 4:00u 1:00 S
+Rule Chile 2011 only - Aug Sun>=16 4:00u 1:00 S
+Rule Chile 2012 max - Oct Sun>=9 4:00u 1:00 S
Rule Chile 2000 2007 - Mar Sun>=9 3:00u 0 -
# N.B.: the end of March 29 in Chile is March 30 in Universal time,
# which is used below in specifying the transition.
Rule Chile 2008 only - Mar 30 3:00u 0 -
Rule Chile 2009 only - Mar Sun>=9 3:00u 0 -
-Rule Chile 2010 2011 - Apr Sun>=1 3:00u 0 -
+Rule Chile 2010 only - Apr Sun>=1 3:00u 0 -
+Rule Chile 2011 only - May Sun>=2 3:00u 0 -
Rule Chile 2012 max - Mar Sun>=9 3:00u 0 -
# IATA SSIM anomalies: (1992-02) says 1992-03-14;
# (1996-09) says 1998-03-08. Ignore these.
--- a/jdk/make/sun/jawt/Makefile Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/sun/jawt/Makefile Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
#
-# Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -112,11 +112,20 @@
# Libraries to link in.
#
ifeq ($(PLATFORM), solaris)
-OTHER_LDLIBS = -L$(LIBDIR)/$(LIBARCH) -L$(OPENWIN_LIB) -L$(LIBDIR)/$(LIBARCH)/xawt -lmawt -L/usr/openwin/sfw/lib$(ISA_DIR) -lXrender
+ ifndef BUILD_HEADLESS_ONLY
+ OTHER_LDLIBS = -L$(LIBDIR)/$(LIBARCH) -L$(OPENWIN_LIB) -L$(LIBDIR)/$(LIBARCH)/xawt -lmawt -L/usr/openwin/sfw/lib$(ISA_DIR) -lXrender
+ else
+ OTHER_LDLIBS = -L$(LIBDIR)/$(LIBARCH) -L$(OPENWIN_LIB) -L$(LIBDIR)/$(LIBARCH)/headless -lmawt -L/usr/openwin/sfw/lib$(ISA_DIR) -lXrender
+ endif
endif # PLATFORM
ifeq ($(PLATFORM), linux)
-OTHER_LDLIBS = -L$(LIBDIR)/$(LIBARCH) -lawt -L$(LIBDIR)/$(LIBARCH)/xawt -lmawt
+ ifndef BUILD_HEADLESS_ONLY
+ OTHER_LDLIBS = -L$(LIBDIR)/$(LIBARCH) -lawt -L$(LIBDIR)/$(LIBARCH)/xawt -lmawt
+ else
+ OTHER_LDLIBS = -L$(LIBDIR)/$(LIBARCH) -lawt -L$(LIBDIR)/$(LIBARCH)/headless -lmawt
+ CFLAGS += -DHEADLESS
+ endif
endif # PLATFORM
endif # PLATFORM
--- a/jdk/make/sun/jpeg/Makefile Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/sun/jpeg/Makefile Sun Apr 10 10:23:28 2011 -0700
@@ -73,9 +73,10 @@
# Recommended way to avoid such warning is to declare the variable as
# volatile to prevent the optimization. However, this approach does not
# work because we have to declare all variables as volatile in result.
-
+ifndef CROSS_COMPILE_ARCH
OTHER_CFLAGS += -Wno-clobbered
endif
+endif
include $(BUILDDIR)/common/Mapfile-vers.gmk
include $(BUILDDIR)/common/Library.gmk
--- a/jdk/make/sun/nio/cs/Makefile Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/sun/nio/cs/Makefile Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
#
-# Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -120,8 +120,15 @@
$(SHARE_SRC)/classes/sun/nio/cs/ext/$(SERVICE_DESCRIPTION_PATH)
$(install-file)
+# no compression unless requested
+ifndef COMPRESS_JARS
+ CREATE_JAR_OPTS_NOMANIFEST = cf0
+else
+ CREATE_JAR_OPTS_NOMANIFEST = cf
+endif
+
$(CHARSETS_JAR): $(FILES_class) $(CLASSDESTDIR)/$(SERVICE_DESCRIPTION_PATH) $(FILES_DAT)
- $(BOOT_JAR_CMD) cf0 $(CHARSETS_JAR) \
+ $(BOOT_JAR_CMD) $(CREATE_JAR_OPTS_NOMANIFEST) $(CHARSETS_JAR) \
-C $(CLASSDESTDIR) sun \
-C $(CLASSDESTDIR) $(SERVICE_DESCRIPTION_PATH) \
$(BOOT_JAR_JFLAGS)
--- a/jdk/make/sun/security/tools/Makefile Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/sun/security/tools/Makefile Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
#
-# Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -46,5 +46,7 @@
build:
$(call make-launcher, keytool, sun.security.tools.KeyTool, , )
+ifndef BUILD_HEADLESS_ONLY
$(call make-launcher, policytool, sun.security.tools.policytool.PolicyTool, , )
+endif
--- a/jdk/make/sun/xawt/Makefile Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/sun/xawt/Makefile Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
#
-# Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -129,10 +129,17 @@
-I$(PLATFORM_SRC)/native/sun/awt
ifeq ($(PLATFORM), linux)
-# Allows for builds on Debian GNU Linux, X11 is in a different place
- CPPFLAGS += -I/usr/X11R6/include/X11/extensions \
- -I/usr/include/X11/extensions \
- -I$(OPENWIN_HOME)/include
+ ifndef CROSS_COMPILE_ARCH
+ # Allows for builds on Debian GNU Linux, X11 is in a different place
+ # This should really be handled at a higher-level so we don't have to
+ # work-around this when cross-compiling
+ CPPFLAGS += -I/usr/X11R6/include/X11/extensions \
+ -I/usr/include/X11/extensions \
+ -I$(OPENWIN_HOME)/include
+ else
+ CPPFLAGS += -I$(OPENWIN_HOME)/include/X11/extensions \
+ -I$(OPENWIN_HOME)/include
+ endif
endif
# We have some odd logic here because some Solaris 10 updates
@@ -245,7 +252,11 @@
$(SIZERS): $(SIZERS_C)
$(prep-target)
+ifndef CROSS_COMPILE_ARCH
$(CC) $(CFLAGS_$(subst .,,$(suffix $@))) $(CPPFLAGS) -o $@ $(SIZER)$(suffix $@).c
+else
+ $(HOST_CC) $(CPPFLAGS) -o $@ $(SIZER)$(suffix $@).c
+endif
$(WRAPPER_GENERATOR_CLASS): $(WRAPPER_GENERATOR_JAVA)
$(prep-target)
--- a/jdk/make/sun/xawt/mapfile-vers Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/make/sun/xawt/mapfile-vers Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
#
-# Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -158,6 +158,7 @@
Java_sun_awt_X11_XRobotPeer_mouseReleaseImpl;
Java_sun_awt_X11_XRobotPeer_mouseWheelImpl;
Java_sun_awt_X11_XRobotPeer_setup;
+ Java_sun_awt_X11_XRobotPeer__1dispose;
Java_sun_awt_X11_XToolkit_getNumberOfButtonsImpl;
Java_java_awt_Component_initIDs;
Java_java_awt_Container_initIDs;
@@ -225,6 +226,7 @@
Java_sun_awt_X11GraphicsConfig_destroyBackBuffer;
Java_sun_awt_X11GraphicsConfig_swapBuffers;
Java_sun_awt_X11GraphicsConfig_isTranslucencyCapable;
+ Java_sun_awt_X11_XToolkit_getTrayIconDisplayTimeout;
Java_java_awt_Insets_initIDs;
Java_java_awt_KeyboardFocusManager_initIDs;
Java_java_awt_Font_initIDs;
--- a/jdk/src/share/classes/com/sun/security/auth/PolicyParser.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/com/sun/security/auth/PolicyParser.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -30,13 +30,14 @@
import java.net.MalformedURLException;
import java.net.SocketPermission;
import java.net.URL;
+import java.security.GeneralSecurityException;
+import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Vector;
import java.util.StringTokenizer;
-import java.security.GeneralSecurityException;
import sun.security.util.PropertyExpander;
/**
@@ -368,8 +369,8 @@
"WILDCARD class but no WILDCARD name");
throw new ParsingException
(st.lineno(),
- rb.getString("can.not.specify.Principal.with.a.") +
- rb.getString("wildcard.class.without.a.wildcard.name"));
+ rb.getString("can.not.specify.Principal.with.a." +
+ "wildcard.class.without.a.wildcard.name"));
}
try {
@@ -525,9 +526,10 @@
rb.getString("number.") +
String.valueOf(st.nval));
case StreamTokenizer.TT_EOF:
- throw new ParsingException
- (rb.getString("expected.") + expect +
- rb.getString(".read.end.of.file"));
+ MessageFormat form = new MessageFormat(
+ rb.getString("expected.expect.read.end.of.file."));
+ Object[] source = {expect};
+ throw new ParsingException(form.format(source));
case StreamTokenizer.TT_WORD:
if (expect.equalsIgnoreCase(st.sval)) {
lookahead = st.nextToken();
--- a/jdk/src/share/classes/java/awt/Component.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/awt/Component.java Sun Apr 10 10:23:28 2011 -0700
@@ -5821,7 +5821,7 @@
* <code>InputMethodRequests</code> instance.
* If listener <code>l</code> is <code>null</code>,
* no exception is thrown and no action is performed.
- * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
+ * <p>Refer to <a href="{@docRoot}/java/awt/doc-files/AWTThreadIssues.html#ListenersThreads"
* >AWT Threading Issues</a> for details on AWT's threading model.
*
* @param l the input method listener
--- a/jdk/src/share/classes/java/awt/Shape.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/awt/Shape.java Sun Apr 10 10:23:28 2011 -0700
@@ -43,7 +43,7 @@
* object that describes the trajectory path of the <code>Shape</code>
* outline.
* <p>
- * <b>Definition of insideness:</b>
+ * <a name="def_insideness"><b>Definition of insideness:</b></a>
* A point is considered to lie inside a
* <code>Shape</code> if and only if:
* <ul>
@@ -88,6 +88,32 @@
* <code>getBounds2D</code> method generally returns a
* tighter bounding box due to its greater flexibility in
* representation.
+ *
+ * <p>
+ * Note that the <a href="{@docRoot}/java/awt/Shape.html#def_insideness">
+ * definition of insideness</a> can lead to situations where points
+ * on the defining outline of the {@code shape} may not be considered
+ * contained in the returned {@code bounds} object, but only in cases
+ * where those points are also not considered contained in the original
+ * {@code shape}.
+ * </p>
+ * <p>
+ * If a {@code point} is inside the {@code shape} according to the
+ * {@link #contains(double x, double y) contains(point)} method, then
+ * it must be inside the returned {@code Rectangle} bounds object
+ * according to the {@link #contains(double x, double y) contains(point)}
+ * method of the {@code bounds}. Specifically:
+ * </p>
+ * <p>
+ * {@code shape.contains(x,y)} requires {@code bounds.contains(x,y)}
+ * </p>
+ * <p>
+ * If a {@code point} is not inside the {@code shape}, then it might
+ * still be contained in the {@code bounds} object:
+ * </p>
+ * <p>
+ * {@code bounds.contains(x,y)} does not imply {@code shape.contains(x,y)}
+ * </p>
* @return an integer <code>Rectangle</code> that completely encloses
* the <code>Shape</code>.
* @see #getBounds2D
@@ -107,6 +133,32 @@
* to overflow problems since the return value can be an instance of
* the <code>Rectangle2D</code> that uses double precision values to
* store the dimensions.
+ *
+ * <p>
+ * Note that the <a href="{@docRoot}/java/awt/Shape.html#def_insideness">
+ * definition of insideness</a> can lead to situations where points
+ * on the defining outline of the {@code shape} may not be considered
+ * contained in the returned {@code bounds} object, but only in cases
+ * where those points are also not considered contained in the original
+ * {@code shape}.
+ * </p>
+ * <p>
+ * If a {@code point} is inside the {@code shape} according to the
+ * {@link #contains(Point2D p) contains(point)} method, then it must
+ * be inside the returned {@code Rectangle2D} bounds object according
+ * to the {@link #contains(Point2D p) contains(point)} method of the
+ * {@code bounds}. Specifically:
+ * </p>
+ * <p>
+ * {@code shape.contains(p)} requires {@code bounds.contains(p)}
+ * </p>
+ * <p>
+ * If a {@code point} is not inside the {@code shape}, then it might
+ * still be contained in the {@code bounds} object:
+ * </p>
+ * <p>
+ * {@code bounds.contains(p)} does not imply {@code shape.contains(p)}
+ * </p>
* @return an instance of <code>Rectangle2D</code> that is a
* high-precision bounding box of the <code>Shape</code>.
* @see #getBounds
@@ -116,7 +168,9 @@
/**
* Tests if the specified coordinates are inside the boundary of the
- * <code>Shape</code>.
+ * <code>Shape</code>, as described by the
+ * <a href="{@docRoot}/java/awt/Shape.html#def_insideness">
+ * definition of insideness</a>.
* @param x the specified X coordinate to be tested
* @param y the specified Y coordinate to be tested
* @return <code>true</code> if the specified coordinates are inside
@@ -128,7 +182,9 @@
/**
* Tests if a specified {@link Point2D} is inside the boundary
- * of the <code>Shape</code>.
+ * of the <code>Shape</code>, as described by the
+ * <a href="{@docRoot}/java/awt/Shape.html#def_insideness">
+ * definition of insideness</a>.
* @param p the specified <code>Point2D</code> to be tested
* @return <code>true</code> if the specified <code>Point2D</code> is
* inside the boundary of the <code>Shape</code>;
--- a/jdk/src/share/classes/java/awt/Toolkit.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/awt/Toolkit.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -858,7 +858,7 @@
String nm = null;
Class cls = null;
try {
- nm = System.getProperty("awt.toolkit", "sun.awt.X11.XToolkit");
+ nm = System.getProperty("awt.toolkit");
try {
cls = Class.forName(nm);
} catch (ClassNotFoundException e) {
@@ -1157,12 +1157,9 @@
* takes JobAttributes and PageAttributes objects. This object
* may be updated to reflect the user's job choices on exit. May
* be null.
- *
* @return a <code>PrintJob</code> object, or <code>null</code> if the
* user cancelled the print job.
- * @throws NullPointerException if frame is null. This exception is
- * always thrown when GraphicsEnvironment.isHeadless() returns
- * true.
+ * @throws NullPointerException if frame is null
* @throws SecurityException if this thread is not allowed to initiate a
* print job request
* @see java.awt.GraphicsEnvironment#isHeadless
@@ -1201,12 +1198,9 @@
* job. The attributes will be updated to reflect the user's
* choices as outlined in the PageAttributes documentation. May be
* null.
- *
* @return a <code>PrintJob</code> object, or <code>null</code> if the
* user cancelled the print job.
- * @throws NullPointerException if frame is null and either jobAttributes
- * is null or jobAttributes.getDialog() returns
- * JobAttributes.DialogType.NATIVE.
+ * @throws NullPointerException if frame is null
* @throws IllegalArgumentException if pageAttributes specifies differing
* cross feed and feed resolutions. Also if this thread has
* access to the file system and jobAttributes specifies
@@ -1218,9 +1212,6 @@
* opportunity to select a file and proceed with printing.
* The dialog will ensure that the selected output file
* is valid before returning from this method.
- * <p>
- * This exception is always thrown when GraphicsEnvironment.isHeadless()
- * returns true.
* @throws SecurityException if this thread is not allowed to initiate a
* print job request, or if jobAttributes specifies print to file,
* and this thread is not allowed to access the file system
@@ -1236,10 +1227,6 @@
PageAttributes pageAttributes) {
// Override to add printing support with new job/page control classes
- if (GraphicsEnvironment.isHeadless()) {
- throw new IllegalArgumentException();
- }
-
if (this != Toolkit.getDefaultToolkit()) {
return Toolkit.getDefaultToolkit().getPrintJob(frame, jobtitle,
jobAttributes,
--- a/jdk/src/share/classes/java/awt/image/BandedSampleModel.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/awt/image/BandedSampleModel.java Sun Apr 10 10:23:28 2011 -0700
@@ -408,7 +408,12 @@
*/
public int[] getPixels(int x, int y, int w, int h,
int iArray[], DataBuffer data) {
- if ((x < 0) || (y < 0) || (x + w > width) || (y + h > height)) {
+ int x1 = x + w;
+ int y1 = y + h;
+
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
throw new ArrayIndexOutOfBoundsException
("Coordinate out of bounds!");
}
@@ -690,7 +695,12 @@
*/
public void setPixels(int x, int y, int w, int h,
int iArray[], DataBuffer data) {
- if ((x < 0) || (y < 0) || (x + w > width) || (y + h > height)) {
+ int x1 = x + w;
+ int y1 = y + h;
+
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
throw new ArrayIndexOutOfBoundsException
("Coordinate out of bounds!");
}
--- a/jdk/src/share/classes/java/awt/image/ComponentSampleModel.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/awt/image/ComponentSampleModel.java Sun Apr 10 10:23:28 2011 -0700
@@ -739,7 +739,12 @@
*/
public int[] getPixels(int x, int y, int w, int h,
int iArray[], DataBuffer data) {
- if ((x < 0) || (y < 0) || (x + w > width) || (y + h > height)) {
+ int x1 = x + w;
+ int y1 = y + h;
+
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || y > height || y1 < 0 || y1 > height)
+ {
throw new ArrayIndexOutOfBoundsException
("Coordinate out of bounds!");
}
@@ -1025,7 +1030,12 @@
*/
public void setPixels(int x, int y, int w, int h,
int iArray[], DataBuffer data) {
- if ((x < 0) || (y < 0) || (x + w > width) || (y + h > height)) {
+ int x1 = x + w;
+ int y1 = y + h;
+
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
throw new ArrayIndexOutOfBoundsException
("Coordinate out of bounds!");
}
--- a/jdk/src/share/classes/java/awt/image/SampleModel.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/awt/image/SampleModel.java Sun Apr 10 10:23:28 2011 -0700
@@ -361,8 +361,8 @@
int x1 = x + w;
int y1 = y + h;
- if (x < 0 || x1 < x || x1 > width ||
- y < 0 || y1 < y || y1 > height)
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
{
throw new ArrayIndexOutOfBoundsException("Invalid coordinates.");
}
@@ -588,6 +588,15 @@
int type = getTransferType();
int numDataElems = getNumDataElements();
+ int x1 = x + w;
+ int y1 = y + h;
+
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
+ throw new ArrayIndexOutOfBoundsException("Invalid coordinates.");
+ }
+
switch(type) {
case DataBuffer.TYPE_BYTE:
@@ -595,8 +604,8 @@
byte[] barray = (byte[])obj;
byte[] btemp = new byte[numDataElems];
- for (int i=y; i<y+h; i++) {
- for (int j=x; j<x+w; j++) {
+ for (int i=y; i<y1; i++) {
+ for (int j=x; j<x1; j++) {
for (int k=0; k<numDataElems; k++) {
btemp[k] = barray[cnt++];
}
@@ -612,8 +621,8 @@
short[] sarray = (short[])obj;
short[] stemp = new short[numDataElems];
- for (int i=y; i<y+h; i++) {
- for (int j=x; j<x+w; j++) {
+ for (int i=y; i<y1; i++) {
+ for (int j=x; j<x1; j++) {
for (int k=0; k<numDataElems; k++) {
stemp[k] = sarray[cnt++];
}
@@ -628,8 +637,8 @@
int[] iArray = (int[])obj;
int[] itemp = new int[numDataElems];
- for (int i=y; i<y+h; i++) {
- for (int j=x; j<x+w; j++) {
+ for (int i=y; i<y1; i++) {
+ for (int j=x; j<x1; j++) {
for (int k=0; k<numDataElems; k++) {
itemp[k] = iArray[cnt++];
}
@@ -644,8 +653,8 @@
float[] fArray = (float[])obj;
float[] ftemp = new float[numDataElems];
- for (int i=y; i<y+h; i++) {
- for (int j=x; j<x+w; j++) {
+ for (int i=y; i<y1; i++) {
+ for (int j=x; j<x1; j++) {
for (int k=0; k<numDataElems; k++) {
ftemp[k] = fArray[cnt++];
}
@@ -660,8 +669,8 @@
double[] dArray = (double[])obj;
double[] dtemp = new double[numDataElems];
- for (int i=y; i<y+h; i++) {
- for (int j=x; j<x+w; j++) {
+ for (int i=y; i<y1; i++) {
+ for (int j=x; j<x1; j++) {
for (int k=0; k<numDataElems; k++) {
dtemp[k] = dArray[cnt++];
}
@@ -759,14 +768,22 @@
int pixels[];
int Offset=0;
+ int x1 = x + w;
+ int y1 = y + h;
+
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
+ throw new ArrayIndexOutOfBoundsException("Invalid coordinates.");
+ }
if (iArray != null)
pixels = iArray;
else
pixels = new int[numBands * w * h];
- for (int i=y; i<(h+y); i++) {
- for (int j=x; j<(w+x); j++) {
+ for (int i=y; i<y1; i++) {
+ for (int j=x; j<x1; j++) {
for(int k=0; k<numBands; k++) {
pixels[Offset++] = getSample(j, i, k, data);
}
@@ -799,14 +816,22 @@
float pixels[];
int Offset = 0;
+ int x1 = x + w;
+ int y1 = y + h;
+
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
+ throw new ArrayIndexOutOfBoundsException("Invalid coordinates.");
+ }
if (fArray != null)
pixels = fArray;
else
pixels = new float[numBands * w * h];
- for (int i=y; i<(h+y); i++) {
- for(int j=x; j<(w+x); j++) {
+ for (int i=y; i<y1; i++) {
+ for(int j=x; j<x1; j++) {
for(int k=0; k<numBands; k++) {
pixels[Offset++] = getSampleFloat(j, i, k, data);
}
@@ -838,6 +863,14 @@
double dArray[], DataBuffer data) {
double pixels[];
int Offset = 0;
+ int x1 = x + w;
+ int y1 = y + h;
+
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
+ throw new ArrayIndexOutOfBoundsException("Invalid coordinates.");
+ }
if (dArray != null)
pixels = dArray;
@@ -845,8 +878,8 @@
pixels = new double[numBands * w * h];
// Fix 4217412
- for (int i=y; i<(h+y); i++) {
- for (int j=x; j<(w+x); j++) {
+ for (int i=y; i<y1; i++) {
+ for (int j=x; j<x1; j++) {
for (int k=0; k<numBands; k++) {
pixels[Offset++] = getSampleDouble(j, i, k, data);
}
@@ -1146,9 +1179,17 @@
public void setPixels(int x, int y, int w, int h,
int iArray[], DataBuffer data) {
int Offset=0;
+ int x1 = x + w;
+ int y1 = y + h;
- for (int i=y; i<(y+h); i++) {
- for (int j=x; j<(x+w); j++) {
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
+ throw new ArrayIndexOutOfBoundsException("Invalid coordinates.");
+ }
+
+ for (int i=y; i<y1; i++) {
+ for (int j=x; j<x1; j++) {
for (int k=0; k<numBands; k++) {
setSample(j, i, k, iArray[Offset++], data);
}
@@ -1176,9 +1217,17 @@
public void setPixels(int x, int y, int w, int h,
float fArray[], DataBuffer data) {
int Offset=0;
+ int x1 = x + w;
+ int y1 = y + h;
- for (int i=y; i<(y+h); i++) {
- for (int j=x; j<(x+w); j++) {
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
+ throw new ArrayIndexOutOfBoundsException("Invalid coordinates.");
+ }
+
+ for (int i=y; i<y1; i++) {
+ for (int j=x; j<x1; j++) {
for(int k=0; k<numBands; k++) {
setSample(j, i, k, fArray[Offset++], data);
}
@@ -1206,9 +1255,17 @@
public void setPixels(int x, int y, int w, int h,
double dArray[], DataBuffer data) {
int Offset=0;
+ int x1 = x + w;
+ int y1 = y + h;
- for (int i=y; i<(y+h); i++) {
- for (int j=x; j<(x+w); j++) {
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
+ throw new ArrayIndexOutOfBoundsException("Invalid coordinates.");
+ }
+
+ for (int i=y; i<y1; i++) {
+ for (int j=x; j<x1; j++) {
for (int k=0; k<numBands; k++) {
setSample(j, i, k, dArray[Offset++], data);
}
@@ -1315,9 +1372,16 @@
int iArray[], DataBuffer data) {
int Offset=0;
+ int x1 = x + w;
+ int y1 = y + h;
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
+ throw new ArrayIndexOutOfBoundsException("Invalid coordinates.");
+ }
- for (int i=y; i<(y+h); i++) {
- for (int j=x; j<(x+w); j++) {
+ for (int i=y; i<y1; i++) {
+ for (int j=x; j<x1; j++) {
setSample(j, i, b, iArray[Offset++], data);
}
}
@@ -1345,9 +1409,17 @@
public void setSamples(int x, int y, int w, int h, int b,
float fArray[], DataBuffer data) {
int Offset=0;
+ int x1 = x + w;
+ int y1 = y + h;
- for (int i=y; i<(y+h); i++) {
- for (int j=x; j<(x+w); j++) {
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
+ throw new ArrayIndexOutOfBoundsException("Invalid coordinates.");
+ }
+
+ for (int i=y; i<y1; i++) {
+ for (int j=x; j<x1; j++) {
setSample(j, i, b, fArray[Offset++], data);
}
}
@@ -1375,9 +1447,18 @@
public void setSamples(int x, int y, int w, int h, int b,
double dArray[], DataBuffer data) {
int Offset=0;
+ int x1 = x + w;
+ int y1 = y + h;
- for (int i=y; i<(y+h); i++) {
- for (int j=x; j<(x+w); j++) {
+
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
+ throw new ArrayIndexOutOfBoundsException("Invalid coordinates.");
+ }
+
+ for (int i=y; i<y1; i++) {
+ for (int j=x; j<x1; j++) {
setSample(j, i, b, dArray[Offset++], data);
}
}
--- a/jdk/src/share/classes/java/awt/image/SinglePixelPackedSampleModel.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/awt/image/SinglePixelPackedSampleModel.java Sun Apr 10 10:23:28 2011 -0700
@@ -461,7 +461,12 @@
*/
public int[] getPixels(int x, int y, int w, int h,
int iArray[], DataBuffer data) {
- if ((x < 0) || (y < 0) || (x + w > width) || (y + h > height)) {
+ int x1 = x + w;
+ int y1 = y + h;
+
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
throw new ArrayIndexOutOfBoundsException
("Coordinate out of bounds!");
}
@@ -659,7 +664,12 @@
*/
public void setPixels(int x, int y, int w, int h,
int iArray[], DataBuffer data) {
- if ((x < 0) || (y < 0) || (x + w > width) || (y + h > height)) {
+ int x1 = x + w;
+ int y1 = y + h;
+
+ if (x < 0 || x >= width || w > width || x1 < 0 || x1 > width ||
+ y < 0 || y >= height || h > height || y1 < 0 || y1 > height)
+ {
throw new ArrayIndexOutOfBoundsException
("Coordinate out of bounds!");
}
--- a/jdk/src/share/classes/java/lang/ArithmeticException.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/lang/ArithmeticException.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -30,15 +30,18 @@
* example, an integer "divide by zero" throws an
* instance of this class.
*
+ * {@code ArithmeticException} objects may be constructed by the
+ * virtual machine as if {@linkplain Throwable#Throwable(String,
+ * Throwable, boolean) suppression were disabled}.
+ *
* @author unascribed
* @since JDK1.0
*/
-public
-class ArithmeticException extends RuntimeException {
+public class ArithmeticException extends RuntimeException {
private static final long serialVersionUID = 2256477558314496007L;
/**
- * Constructs an <code>ArithmeticException</code> with no detail
+ * Constructs an {@code ArithmeticException} with no detail
* message.
*/
public ArithmeticException() {
@@ -46,7 +49,7 @@
}
/**
- * Constructs an <code>ArithmeticException</code> with the specified
+ * Constructs an {@code ArithmeticException} with the specified
* detail message.
*
* @param s the detail message.
--- a/jdk/src/share/classes/java/lang/CharSequence.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/lang/CharSequence.java Sun Apr 10 10:23:28 2011 -0700
@@ -66,7 +66,7 @@
* indexing. </p>
*
* <p>If the <code>char</code> value specified by the index is a
- * <a href="Character.html#unicode">surrogate</a>, the surrogate
+ * <a href="{@docRoot}/java/lang/Character.html#unicode">surrogate</a>, the surrogate
* value is returned.
*
* @param index the index of the <code>char</code> value to be returned
--- a/jdk/src/share/classes/java/lang/Character.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/lang/Character.java Sun Apr 10 10:23:28 2011 -0700
@@ -31,10 +31,10 @@
import java.util.Locale;
/**
- * The <code>Character</code> class wraps a value of the primitive
- * type <code>char</code> in an object. An object of type
- * <code>Character</code> contains a single field whose type is
- * <code>char</code>.
+ * The {@code Character} class wraps a value of the primitive
+ * type {@code char} in an object. An object of type
+ * {@code Character} contains a single field whose type is
+ * {@code char}.
* <p>
* In addition, this class provides several methods for determining
* a character's category (lowercase letter, digit, etc.) and for converting
@@ -42,7 +42,7 @@
* <p>
* Character information is based on the Unicode Standard, version 6.0.0.
* <p>
- * The methods and data of class <code>Character</code> are defined by
+ * The methods and data of class {@code Character} are defined by
* the information in the <i>UnicodeData</i> file that is part of the
* Unicode Character Database maintained by the Unicode
* Consortium. This file specifies various properties including name
@@ -56,8 +56,8 @@
*
* <h4><a name="unicode">Unicode Character Representations</a></h4>
*
- * <p>The <code>char</code> data type (and therefore the value that a
- * <code>Character</code> object encapsulates) are based on the
+ * <p>The {@code char} data type (and therefore the value that a
+ * {@code Character} object encapsulates) are based on the
* original Unicode specification, which defined characters as
* fixed-width 16-bit entities. The Unicode standard has since been
* changed to allow for characters whose representation requires more
@@ -72,43 +72,43 @@
* sometimes referred to as the <em>Basic Multilingual Plane (BMP)</em>.
* <a name="supplementary">Characters</a> whose code points are greater
* than U+FFFF are called <em>supplementary character</em>s. The Java
- * platform uses the UTF-16 representation in <code>char</code> arrays and
- * in the <code>String</code> and <code>StringBuffer</code> classes. In
+ * platform uses the UTF-16 representation in {@code char} arrays and
+ * in the {@code String} and {@code StringBuffer} classes. In
* this representation, supplementary characters are represented as a pair
- * of <code>char</code> values, the first from the <em>high-surrogates</em>
+ * of {@code char} values, the first from the <em>high-surrogates</em>
* range, (\uD800-\uDBFF), the second from the
* <em>low-surrogates</em> range (\uDC00-\uDFFF).
*
- * <p>A <code>char</code> value, therefore, represents Basic
+ * <p>A {@code char} value, therefore, represents Basic
* Multilingual Plane (BMP) code points, including the surrogate
* code points, or code units of the UTF-16 encoding. An
- * <code>int</code> value represents all Unicode code points,
+ * {@code int} value represents all Unicode code points,
* including supplementary code points. The lower (least significant)
- * 21 bits of <code>int</code> are used to represent Unicode code
+ * 21 bits of {@code int} are used to represent Unicode code
* points and the upper (most significant) 11 bits must be zero.
* Unless otherwise specified, the behavior with respect to
- * supplementary characters and surrogate <code>char</code> values is
+ * supplementary characters and surrogate {@code char} values is
* as follows:
*
* <ul>
- * <li>The methods that only accept a <code>char</code> value cannot support
- * supplementary characters. They treat <code>char</code> values from the
+ * <li>The methods that only accept a {@code char} value cannot support
+ * supplementary characters. They treat {@code char} values from the
* surrogate ranges as undefined characters. For example,
- * <code>Character.isLetter('\uD840')</code> returns <code>false</code>, even though
+ * {@code Character.isLetter('\u005CuD840')} returns {@code false}, even though
* this specific value if followed by any low-surrogate value in a string
* would represent a letter.
*
- * <li>The methods that accept an <code>int</code> value support all
+ * <li>The methods that accept an {@code int} value support all
* Unicode characters, including supplementary characters. For
- * example, <code>Character.isLetter(0x2F81A)</code> returns
- * <code>true</code> because the code point value represents a letter
+ * example, {@code Character.isLetter(0x2F81A)} returns
+ * {@code true} because the code point value represents a letter
* (a CJK ideograph).
* </ul>
*
* <p>In the Java SE API documentation, <em>Unicode code point</em> is
* used for character values in the range between U+0000 and U+10FFFF,
* and <em>Unicode code unit</em> is used for 16-bit
- * <code>char</code> values that are code units of the <em>UTF-16</em>
+ * {@code char} values that are code units of the <em>UTF-16</em>
* encoding. For more information on Unicode terminology, refer to the
* <a href="http://www.unicode.org/glossary/">Unicode Glossary</a>.
*
@@ -125,9 +125,8 @@
* The minimum radix available for conversion to and from strings.
* The constant value of this field is the smallest value permitted
* for the radix argument in radix-conversion methods such as the
- * <code>digit</code> method, the <code>forDigit</code>
- * method, and the <code>toString</code> method of class
- * <code>Integer</code>.
+ * {@code digit} method, the {@code forDigit} method, and the
+ * {@code toString} method of class {@code Integer}.
*
* @see Character#digit(char, int)
* @see Character#forDigit(int, int)
@@ -140,9 +139,8 @@
* The maximum radix available for conversion to and from strings.
* The constant value of this field is the largest value permitted
* for the radix argument in radix-conversion methods such as the
- * <code>digit</code> method, the <code>forDigit</code>
- * method, and the <code>toString</code> method of class
- * <code>Integer</code>.
+ * {@code digit} method, the {@code forDigit} method, and the
+ * {@code toString} method of class {@code Integer}.
*
* @see Character#digit(char, int)
* @see Character#forDigit(int, int)
@@ -153,7 +151,7 @@
/**
* The constant value of this field is the smallest value of type
- * <code>char</code>, <code>'\u0000'</code>.
+ * {@code char}, {@code '\u005Cu0000'}.
*
* @since 1.0.2
*/
@@ -161,15 +159,15 @@
/**
* The constant value of this field is the largest value of type
- * <code>char</code>, <code>'\uFFFF'</code>.
+ * {@code char}, {@code '\u005CuFFFF'}.
*
* @since 1.0.2
*/
public static final char MAX_VALUE = '\uFFFF';
/**
- * The <code>Class</code> instance representing the primitive type
- * <code>char</code>.
+ * The {@code Class} instance representing the primitive type
+ * {@code char}.
*
* @since 1.1
*/
@@ -371,7 +369,7 @@
/**
- * Undefined bidirectional character type. Undefined <code>char</code>
+ * Undefined bidirectional character type. Undefined {@code char}
* values have undefined directionality in the Unicode specification.
* @since 1.4
*/
@@ -495,7 +493,7 @@
* The minimum value of a
* <a href="http://www.unicode.org/glossary/#high_surrogate_code_unit">
* Unicode high-surrogate code unit</a>
- * in the UTF-16 encoding, constant <code>'\uD800'</code>.
+ * in the UTF-16 encoding, constant {@code '\u005CuD800'}.
* A high-surrogate is also known as a <i>leading-surrogate</i>.
*
* @since 1.5
@@ -506,7 +504,7 @@
* The maximum value of a
* <a href="http://www.unicode.org/glossary/#high_surrogate_code_unit">
* Unicode high-surrogate code unit</a>
- * in the UTF-16 encoding, constant <code>'\uDBFF'</code>.
+ * in the UTF-16 encoding, constant {@code '\u005CuDBFF'}.
* A high-surrogate is also known as a <i>leading-surrogate</i>.
*
* @since 1.5
@@ -517,7 +515,7 @@
* The minimum value of a
* <a href="http://www.unicode.org/glossary/#low_surrogate_code_unit">
* Unicode low-surrogate code unit</a>
- * in the UTF-16 encoding, constant <code>'\uDC00'</code>.
+ * in the UTF-16 encoding, constant {@code '\u005CuDC00'}.
* A low-surrogate is also known as a <i>trailing-surrogate</i>.
*
* @since 1.5
@@ -528,7 +526,7 @@
* The maximum value of a
* <a href="http://www.unicode.org/glossary/#low_surrogate_code_unit">
* Unicode low-surrogate code unit</a>
- * in the UTF-16 encoding, constant <code>'\uDFFF'</code>.
+ * in the UTF-16 encoding, constant {@code '\u005CuDFFF'}.
* A low-surrogate is also known as a <i>trailing-surrogate</i>.
*
* @since 1.5
@@ -537,7 +535,7 @@
/**
* The minimum value of a Unicode surrogate code unit in the
- * UTF-16 encoding, constant <code>'\uD800'</code>.
+ * UTF-16 encoding, constant {@code '\u005CuD800'}.
*
* @since 1.5
*/
@@ -545,7 +543,7 @@
/**
* The maximum value of a Unicode surrogate code unit in the
- * UTF-16 encoding, constant <code>'\uDFFF'</code>.
+ * UTF-16 encoding, constant {@code '\u005CuDFFF'}.
*
* @since 1.5
*/
@@ -582,7 +580,7 @@
/**
* Instances of this class represent particular subsets of the Unicode
* character set. The only family of subsets defined in the
- * <code>Character</code> class is {@link Character.UnicodeBlock}.
+ * {@code Character} class is {@link Character.UnicodeBlock}.
* Other portions of the Java API may define other subsets for their
* own purposes.
*
@@ -593,10 +591,10 @@
private String name;
/**
- * Constructs a new <code>Subset</code> instance.
+ * Constructs a new {@code Subset} instance.
*
* @param name The name of this subset
- * @exception NullPointerException if name is <code>null</code>
+ * @exception NullPointerException if name is {@code null}
*/
protected Subset(String name) {
if (name == null) {
@@ -606,10 +604,10 @@
}
/**
- * Compares two <code>Subset</code> objects for equality.
- * This method returns <code>true</code> if and only if
- * <code>this</code> and the argument refer to the same
- * object; since this method is <code>final</code>, this
+ * Compares two {@code Subset} objects for equality.
+ * This method returns {@code true} if and only if
+ * {@code this} and the argument refer to the same
+ * object; since this method is {@code final}, this
* guarantee holds for all subclasses.
*/
public final boolean equals(Object obj) {
@@ -618,9 +616,9 @@
/**
* Returns the standard hash code as defined by the
- * <code>{@link Object#hashCode}</code> method. This method
- * is <code>final</code> in order to ensure that the
- * <code>equals</code> and <code>hashCode</code> methods will
+ * {@link Object#hashCode} method. This method
+ * is {@code final} in order to ensure that the
+ * {@code equals} and {@code hashCode} methods will
* be consistent in all subclasses.
*/
public final int hashCode() {
@@ -2960,7 +2958,7 @@
/**
* Returns the object representing the Unicode block containing the
- * given character, or <code>null</code> if the character is not a
+ * given character, or {@code null} if the character is not a
* member of a defined block.
*
* <p><b>Note:</b> This method cannot handle
@@ -2969,9 +2967,9 @@
* supplementary characters, use the {@link #of(int)} method.
*
* @param c The character in question
- * @return The <code>UnicodeBlock</code> instance representing the
+ * @return The {@code UnicodeBlock} instance representing the
* Unicode block of which this character is a member, or
- * <code>null</code> if the character is not a member of any
+ * {@code null} if the character is not a member of any
* Unicode block
*/
public static UnicodeBlock of(char c) {
@@ -2981,16 +2979,16 @@
/**
* Returns the object representing the Unicode block
* containing the given character (Unicode code point), or
- * <code>null</code> if the character is not a member of a
+ * {@code null} if the character is not a member of a
* defined block.
*
* @param codePoint the character (Unicode code point) in question.
- * @return The <code>UnicodeBlock</code> instance representing the
+ * @return The {@code UnicodeBlock} instance representing the
* Unicode block of which this character is a member, or
- * <code>null</code> if the character is not a member of any
+ * {@code null} if the character is not a member of any
* Unicode block
* @exception IllegalArgumentException if the specified
- * <code>codePoint</code> is an invalid Unicode code point.
+ * {@code codePoint} is an invalid Unicode code point.
* @see Character#isValidCodePoint(int)
* @since 1.5
*/
@@ -3044,12 +3042,12 @@
* If the Unicode Standard changes block names, both the previous and
* current names will be accepted.
*
- * @param blockName A <code>UnicodeBlock</code> name.
- * @return The <code>UnicodeBlock</code> instance identified
- * by <code>blockName</code>
- * @throws IllegalArgumentException if <code>blockName</code> is an
+ * @param blockName A {@code UnicodeBlock} name.
+ * @return The {@code UnicodeBlock} instance identified
+ * by {@code blockName}
+ * @throws IllegalArgumentException if {@code blockName} is an
* invalid name
- * @throws NullPointerException if <code>blockName</code> is null
+ * @throws NullPointerException if {@code blockName} is null
* @since 1.5
*/
public static final UnicodeBlock forName(String blockName) {
@@ -4280,11 +4278,11 @@
* the given character (Unicode code point) is assigned to.
*
* @param codePoint the character (Unicode code point) in question.
- * @return The <code>UnicodeScript</code> constant representing the
+ * @return The {@code UnicodeScript} constant representing the
* Unicode script of which this character is assigned to.
*
* @exception IllegalArgumentException if the specified
- * <code>codePoint</code> is an invalid Unicode code point.
+ * {@code codePoint} is an invalid Unicode code point.
* @see Character#isValidCodePoint(int)
*
*/
@@ -4315,12 +4313,12 @@
* case-insensitive string comparisons for script name validation.
* <p>
*
- * @param scriptName A <code>UnicodeScript</code> name.
- * @return The <code>UnicodeScript</code> constant identified
- * by <code>scriptName</code>
- * @throws IllegalArgumentException if <code>scriptName</code> is an
+ * @param scriptName A {@code UnicodeScript} name.
+ * @return The {@code UnicodeScript} constant identified
+ * by {@code scriptName}
+ * @throws IllegalArgumentException if {@code scriptName} is an
* invalid name
- * @throws NullPointerException if <code>scriptName</code> is null
+ * @throws NullPointerException if {@code scriptName} is null
*/
public static final UnicodeScript forName(String scriptName) {
scriptName = scriptName.toUpperCase(Locale.ENGLISH);
@@ -4333,7 +4331,7 @@
}
/**
- * The value of the <code>Character</code>.
+ * The value of the {@code Character}.
*
* @serial
*/
@@ -4343,11 +4341,11 @@
private static final long serialVersionUID = 3786198910865385080L;
/**
- * Constructs a newly allocated <code>Character</code> object that
- * represents the specified <code>char</code> value.
+ * Constructs a newly allocated {@code Character} object that
+ * represents the specified {@code char} value.
*
* @param value the value to be represented by the
- * <code>Character</code> object.
+ * {@code Character} object.
*/
public Character(char value) {
this.value = value;
@@ -4374,7 +4372,7 @@
* frequently requested values.
*
* This method will always cache values in the range {@code
- * '\u005Cu0000'} to {@code '\u005Cu007f'}, inclusive, and may
+ * '\u005Cu0000'} to {@code '\u005Cu007F'}, inclusive, and may
* cache other values outside of this range.
*
* @param c a char value.
@@ -4389,8 +4387,8 @@
}
/**
- * Returns the value of this <code>Character</code> object.
- * @return the primitive <code>char</code> value represented by
+ * Returns the value of this {@code Character} object.
+ * @return the primitive {@code char} value represented by
* this object.
*/
public char charValue() {
@@ -4409,13 +4407,13 @@
/**
* Compares this object against the specified object.
- * The result is <code>true</code> if and only if the argument is not
- * <code>null</code> and is a <code>Character</code> object that
- * represents the same <code>char</code> value as this object.
+ * The result is {@code true} if and only if the argument is not
+ * {@code null} and is a {@code Character} object that
+ * represents the same {@code char} value as this object.
*
* @param obj the object to compare with.
- * @return <code>true</code> if the objects are the same;
- * <code>false</code> otherwise.
+ * @return {@code true} if the objects are the same;
+ * {@code false} otherwise.
*/
public boolean equals(Object obj) {
if (obj instanceof Character) {
@@ -4425,11 +4423,11 @@
}
/**
- * Returns a <code>String</code> object representing this
- * <code>Character</code>'s value. The result is a string of
+ * Returns a {@code String} object representing this
+ * {@code Character}'s value. The result is a string of
* length 1 whose sole component is the primitive
- * <code>char</code> value represented by this
- * <code>Character</code> object.
+ * {@code char} value represented by this
+ * {@code Character} object.
*
* @return a string representation of this object.
*/
@@ -4439,12 +4437,12 @@
}
/**
- * Returns a <code>String</code> object representing the
- * specified <code>char</code>. The result is a string of length
- * 1 consisting solely of the specified <code>char</code>.
- *
- * @param c the <code>char</code> to be converted
- * @return the string representation of the specified <code>char</code>
+ * Returns a {@code String} object representing the
+ * specified {@code char}. The result is a string of length
+ * 1 consisting solely of the specified {@code char}.
+ *
+ * @param c the {@code char} to be converted
+ * @return the string representation of the specified {@code char}
* @since 1.4
*/
public static String toString(char c) {
@@ -4578,7 +4576,7 @@
}
/**
- * Determines whether the specified pair of <code>char</code>
+ * Determines whether the specified pair of {@code char}
* values is a valid
* <a href="http://www.unicode.org/glossary/#surrogate_pair">
* Unicode surrogate pair</a>.
@@ -4590,9 +4588,9 @@
*
* @param high the high-surrogate code value to be tested
* @param low the low-surrogate code value to be tested
- * @return <code>true</code> if the specified high and
+ * @return {@code true} if the specified high and
* low-surrogate code values represent a valid surrogate pair;
- * <code>false</code> otherwise.
+ * {@code false} otherwise.
* @since 1.5
*/
public static boolean isSurrogatePair(char high, char low) {
@@ -4600,7 +4598,7 @@
}
/**
- * Determines the number of <code>char</code> values needed to
+ * Determines the number of {@code char} values needed to
* represent the specified character (Unicode code point). If the
* specified character is equal to or greater than 0x10000, then
* the method returns 2. Otherwise, the method returns 1.
@@ -4643,23 +4641,23 @@
/**
* Returns the code point at the given index of the
- * <code>CharSequence</code>. If the <code>char</code> value at
- * the given index in the <code>CharSequence</code> is in the
+ * {@code CharSequence}. If the {@code char} value at
+ * the given index in the {@code CharSequence} is in the
* high-surrogate range, the following index is less than the
- * length of the <code>CharSequence</code>, and the
- * <code>char</code> value at the following index is in the
+ * length of the {@code CharSequence}, and the
+ * {@code char} value at the following index is in the
* low-surrogate range, then the supplementary code point
* corresponding to this surrogate pair is returned. Otherwise,
- * the <code>char</code> value at the given index is returned.
- *
- * @param seq a sequence of <code>char</code> values (Unicode code
+ * the {@code char} value at the given index is returned.
+ *
+ * @param seq a sequence of {@code char} values (Unicode code
* units)
- * @param index the index to the <code>char</code> values (Unicode
- * code units) in <code>seq</code> to be converted
+ * @param index the index to the {@code char} values (Unicode
+ * code units) in {@code seq} to be converted
* @return the Unicode code point at the given index
- * @exception NullPointerException if <code>seq</code> is null.
+ * @exception NullPointerException if {@code seq} is null.
* @exception IndexOutOfBoundsException if the value
- * <code>index</code> is negative or not less than
+ * {@code index} is negative or not less than
* {@link CharSequence#length() seq.length()}.
* @since 1.5
*/
@@ -4678,23 +4676,23 @@
/**
* Returns the code point at the given index of the
- * <code>char</code> array. If the <code>char</code> value at
- * the given index in the <code>char</code> array is in the
+ * {@code char} array. If the {@code char} value at
+ * the given index in the {@code char} array is in the
* high-surrogate range, the following index is less than the
- * length of the <code>char</code> array, and the
- * <code>char</code> value at the following index is in the
+ * length of the {@code char} array, and the
+ * {@code char} value at the following index is in the
* low-surrogate range, then the supplementary code point
* corresponding to this surrogate pair is returned. Otherwise,
- * the <code>char</code> value at the given index is returned.
- *
- * @param a the <code>char</code> array
- * @param index the index to the <code>char</code> values (Unicode
- * code units) in the <code>char</code> array to be converted
+ * the {@code char} value at the given index is returned.
+ *
+ * @param a the {@code char} array
+ * @param index the index to the {@code char} values (Unicode
+ * code units) in the {@code char} array to be converted
* @return the Unicode code point at the given index
- * @exception NullPointerException if <code>a</code> is null.
+ * @exception NullPointerException if {@code a} is null.
* @exception IndexOutOfBoundsException if the value
- * <code>index</code> is negative or not less than
- * the length of the <code>char</code> array.
+ * {@code index} is negative or not less than
+ * the length of the {@code char} array.
* @since 1.5
*/
public static int codePointAt(char[] a, int index) {
@@ -4703,27 +4701,27 @@
/**
* Returns the code point at the given index of the
- * <code>char</code> array, where only array elements with
- * <code>index</code> less than <code>limit</code> can be used. If
- * the <code>char</code> value at the given index in the
- * <code>char</code> array is in the high-surrogate range, the
- * following index is less than the <code>limit</code>, and the
- * <code>char</code> value at the following index is in the
+ * {@code char} array, where only array elements with
+ * {@code index} less than {@code limit} can be used. If
+ * the {@code char} value at the given index in the
+ * {@code char} array is in the high-surrogate range, the
+ * following index is less than the {@code limit}, and the
+ * {@code char} value at the following index is in the
* low-surrogate range, then the supplementary code point
* corresponding to this surrogate pair is returned. Otherwise,
- * the <code>char</code> value at the given index is returned.
- *
- * @param a the <code>char</code> array
- * @param index the index to the <code>char</code> values (Unicode
- * code units) in the <code>char</code> array to be converted
- * @param limit the index after the last array element that can be used in the
- * <code>char</code> array
+ * the {@code char} value at the given index is returned.
+ *
+ * @param a the {@code char} array
+ * @param index the index to the {@code char} values (Unicode
+ * code units) in the {@code char} array to be converted
+ * @param limit the index after the last array element that
+ * can be used in the {@code char} array
* @return the Unicode code point at the given index
- * @exception NullPointerException if <code>a</code> is null.
- * @exception IndexOutOfBoundsException if the <code>index</code>
- * argument is negative or not less than the <code>limit</code>
- * argument, or if the <code>limit</code> argument is negative or
- * greater than the length of the <code>char</code> array.
+ * @exception NullPointerException if {@code a} is null.
+ * @exception IndexOutOfBoundsException if the {@code index}
+ * argument is negative or not less than the {@code limit}
+ * argument, or if the {@code limit} argument is negative or
+ * greater than the length of the {@code char} array.
* @since 1.5
*/
public static int codePointAt(char[] a, int index, int limit) {
@@ -4749,21 +4747,21 @@
/**
* Returns the code point preceding the given index of the
- * <code>CharSequence</code>. If the <code>char</code> value at
- * <code>(index - 1)</code> in the <code>CharSequence</code> is in
- * the low-surrogate range, <code>(index - 2)</code> is not
- * negative, and the <code>char</code> value at <code>(index -
- * 2)</code> in the <code>CharSequence</code> is in the
+ * {@code CharSequence}. If the {@code char} value at
+ * {@code (index - 1)} in the {@code CharSequence} is in
+ * the low-surrogate range, {@code (index - 2)} is not
+ * negative, and the {@code char} value at {@code (index - 2)}
+ * in the {@code CharSequence} is in the
* high-surrogate range, then the supplementary code point
* corresponding to this surrogate pair is returned. Otherwise,
- * the <code>char</code> value at <code>(index - 1)</code> is
+ * the {@code char} value at {@code (index - 1)} is
* returned.
*
- * @param seq the <code>CharSequence</code> instance
+ * @param seq the {@code CharSequence} instance
* @param index the index following the code point that should be returned
* @return the Unicode code point value before the given index.
- * @exception NullPointerException if <code>seq</code> is null.
- * @exception IndexOutOfBoundsException if the <code>index</code>
+ * @exception NullPointerException if {@code seq} is null.
+ * @exception IndexOutOfBoundsException if the {@code index}
* argument is less than 1 or greater than {@link
* CharSequence#length() seq.length()}.
* @since 1.5
@@ -4783,23 +4781,23 @@
/**
* Returns the code point preceding the given index of the
- * <code>char</code> array. If the <code>char</code> value at
- * <code>(index - 1)</code> in the <code>char</code> array is in
- * the low-surrogate range, <code>(index - 2)</code> is not
- * negative, and the <code>char</code> value at <code>(index -
- * 2)</code> in the <code>char</code> array is in the
+ * {@code char} array. If the {@code char} value at
+ * {@code (index - 1)} in the {@code char} array is in
+ * the low-surrogate range, {@code (index - 2)} is not
+ * negative, and the {@code char} value at {@code (index - 2)}
+ * in the {@code char} array is in the
* high-surrogate range, then the supplementary code point
* corresponding to this surrogate pair is returned. Otherwise,
- * the <code>char</code> value at <code>(index - 1)</code> is
+ * the {@code char} value at {@code (index - 1)} is
* returned.
*
- * @param a the <code>char</code> array
+ * @param a the {@code char} array
* @param index the index following the code point that should be returned
* @return the Unicode code point value before the given index.
- * @exception NullPointerException if <code>a</code> is null.
- * @exception IndexOutOfBoundsException if the <code>index</code>
+ * @exception NullPointerException if {@code a} is null.
+ * @exception IndexOutOfBoundsException if the {@code index}
* argument is less than 1 or greater than the length of the
- * <code>char</code> array
+ * {@code char} array
* @since 1.5
*/
public static int codePointBefore(char[] a, int index) {
@@ -4808,29 +4806,29 @@
/**
* Returns the code point preceding the given index of the
- * <code>char</code> array, where only array elements with
- * <code>index</code> greater than or equal to <code>start</code>
- * can be used. If the <code>char</code> value at <code>(index -
- * 1)</code> in the <code>char</code> array is in the
- * low-surrogate range, <code>(index - 2)</code> is not less than
- * <code>start</code>, and the <code>char</code> value at
- * <code>(index - 2)</code> in the <code>char</code> array is in
+ * {@code char} array, where only array elements with
+ * {@code index} greater than or equal to {@code start}
+ * can be used. If the {@code char} value at {@code (index - 1)}
+ * in the {@code char} array is in the
+ * low-surrogate range, {@code (index - 2)} is not less than
+ * {@code start}, and the {@code char} value at
+ * {@code (index - 2)} in the {@code char} array is in
* the high-surrogate range, then the supplementary code point
* corresponding to this surrogate pair is returned. Otherwise,
- * the <code>char</code> value at <code>(index - 1)</code> is
+ * the {@code char} value at {@code (index - 1)} is
* returned.
*
- * @param a the <code>char</code> array
+ * @param a the {@code char} array
* @param index the index following the code point that should be returned
* @param start the index of the first array element in the
- * <code>char</code> array
+ * {@code char} array
* @return the Unicode code point value before the given index.
- * @exception NullPointerException if <code>a</code> is null.
- * @exception IndexOutOfBoundsException if the <code>index</code>
- * argument is not greater than the <code>start</code> argument or
- * is greater than the length of the <code>char</code> array, or
- * if the <code>start</code> argument is negative or not less than
- * the length of the <code>char</code> array.
+ * @exception NullPointerException if {@code a} is null.
+ * @exception IndexOutOfBoundsException if the {@code index}
+ * argument is not greater than the {@code start} argument or
+ * is greater than the length of the {@code char} array, or
+ * if the {@code start} argument is negative or not less than
+ * the length of the {@code char} array.
* @since 1.5
*/
public static int codePointBefore(char[] a, int index, int start) {
@@ -4915,31 +4913,31 @@
* Converts the specified character (Unicode code point) to its
* UTF-16 representation. If the specified code point is a BMP
* (Basic Multilingual Plane or Plane 0) value, the same value is
- * stored in <code>dst[dstIndex]</code>, and 1 is returned. If the
+ * stored in {@code dst[dstIndex]}, and 1 is returned. If the
* specified code point is a supplementary character, its
- * surrogate values are stored in <code>dst[dstIndex]</code>
- * (high-surrogate) and <code>dst[dstIndex+1]</code>
+ * surrogate values are stored in {@code dst[dstIndex]}
+ * (high-surrogate) and {@code dst[dstIndex+1]}
* (low-surrogate), and 2 is returned.
*
* @param codePoint the character (Unicode code point) to be converted.
- * @param dst an array of <code>char</code> in which the
- * <code>codePoint</code>'s UTF-16 value is stored.
- * @param dstIndex the start index into the <code>dst</code>
+ * @param dst an array of {@code char} in which the
+ * {@code codePoint}'s UTF-16 value is stored.
+ * @param dstIndex the start index into the {@code dst}
* array where the converted value is stored.
* @return 1 if the code point is a BMP code point, 2 if the
* code point is a supplementary code point.
* @exception IllegalArgumentException if the specified
- * <code>codePoint</code> is not a valid Unicode code point.
- * @exception NullPointerException if the specified <code>dst</code> is null.
- * @exception IndexOutOfBoundsException if <code>dstIndex</code>
- * is negative or not less than <code>dst.length</code>, or if
- * <code>dst</code> at <code>dstIndex</code> doesn't have enough
- * array element(s) to store the resulting <code>char</code>
- * value(s). (If <code>dstIndex</code> is equal to
- * <code>dst.length-1</code> and the specified
- * <code>codePoint</code> is a supplementary character, the
+ * {@code codePoint} is not a valid Unicode code point.
+ * @exception NullPointerException if the specified {@code dst} is null.
+ * @exception IndexOutOfBoundsException if {@code dstIndex}
+ * is negative or not less than {@code dst.length}, or if
+ * {@code dst} at {@code dstIndex} doesn't have enough
+ * array element(s) to store the resulting {@code char}
+ * value(s). (If {@code dstIndex} is equal to
+ * {@code dst.length-1} and the specified
+ * {@code codePoint} is a supplementary character, the
* high-surrogate value is not stored in
- * <code>dst[dstIndex]</code>.)
+ * {@code dst[dstIndex]}.)
* @since 1.5
*/
public static int toChars(int codePoint, char[] dst, int dstIndex) {
@@ -4956,18 +4954,18 @@
/**
* Converts the specified character (Unicode code point) to its
- * UTF-16 representation stored in a <code>char</code> array. If
+ * UTF-16 representation stored in a {@code char} array. If
* the specified code point is a BMP (Basic Multilingual Plane or
- * Plane 0) value, the resulting <code>char</code> array has
- * the same value as <code>codePoint</code>. If the specified code
+ * Plane 0) value, the resulting {@code char} array has
+ * the same value as {@code codePoint}. If the specified code
* point is a supplementary code point, the resulting
- * <code>char</code> array has the corresponding surrogate pair.
+ * {@code char} array has the corresponding surrogate pair.
*
* @param codePoint a Unicode code point
- * @return a <code>char</code> array having
- * <code>codePoint</code>'s UTF-16 representation.
+ * @return a {@code char} array having
+ * {@code codePoint}'s UTF-16 representation.
* @exception IllegalArgumentException if the specified
- * <code>codePoint</code> is not a valid Unicode code point.
+ * {@code codePoint} is not a valid Unicode code point.
* @since 1.5
*/
public static char[] toChars(int codePoint) {
@@ -4991,24 +4989,24 @@
/**
* Returns the number of Unicode code points in the text range of
* the specified char sequence. The text range begins at the
- * specified <code>beginIndex</code> and extends to the
- * <code>char</code> at index <code>endIndex - 1</code>. Thus the
- * length (in <code>char</code>s) of the text range is
- * <code>endIndex-beginIndex</code>. Unpaired surrogates within
+ * specified {@code beginIndex} and extends to the
+ * {@code char} at index {@code endIndex - 1}. Thus the
+ * length (in {@code char}s) of the text range is
+ * {@code endIndex-beginIndex}. Unpaired surrogates within
* the text range count as one code point each.
*
* @param seq the char sequence
- * @param beginIndex the index to the first <code>char</code> of
+ * @param beginIndex the index to the first {@code char} of
* the text range.
- * @param endIndex the index after the last <code>char</code> of
+ * @param endIndex the index after the last {@code char} of
* the text range.
* @return the number of Unicode code points in the specified text
* range
- * @exception NullPointerException if <code>seq</code> is null.
+ * @exception NullPointerException if {@code seq} is null.
* @exception IndexOutOfBoundsException if the
- * <code>beginIndex</code> is negative, or <code>endIndex</code>
+ * {@code beginIndex} is negative, or {@code endIndex}
* is larger than the length of the given sequence, or
- * <code>beginIndex</code> is larger than <code>endIndex</code>.
+ * {@code beginIndex} is larger than {@code endIndex}.
* @since 1.5
*/
public static int codePointCount(CharSequence seq, int beginIndex, int endIndex) {
@@ -5029,21 +5027,21 @@
/**
* Returns the number of Unicode code points in a subarray of the
- * <code>char</code> array argument. The <code>offset</code>
- * argument is the index of the first <code>char</code> of the
- * subarray and the <code>count</code> argument specifies the
- * length of the subarray in <code>char</code>s. Unpaired
+ * {@code char} array argument. The {@code offset}
+ * argument is the index of the first {@code char} of the
+ * subarray and the {@code count} argument specifies the
+ * length of the subarray in {@code char}s. Unpaired
* surrogates within the subarray count as one code point each.
*
- * @param a the <code>char</code> array
- * @param offset the index of the first <code>char</code> in the
- * given <code>char</code> array
- * @param count the length of the subarray in <code>char</code>s
+ * @param a the {@code char} array
+ * @param offset the index of the first {@code char} in the
+ * given {@code char} array
+ * @param count the length of the subarray in {@code char}s
* @return the number of Unicode code points in the specified subarray
- * @exception NullPointerException if <code>a</code> is null.
- * @exception IndexOutOfBoundsException if <code>offset</code> or
- * <code>count</code> is negative, or if <code>offset +
- * count</code> is larger than the length of the given array.
+ * @exception NullPointerException if {@code a} is null.
+ * @exception IndexOutOfBoundsException if {@code offset} or
+ * {@code count} is negative, or if {@code offset +
+ * count} is larger than the length of the given array.
* @since 1.5
*/
public static int codePointCount(char[] a, int offset, int count) {
@@ -5068,24 +5066,24 @@
/**
* Returns the index within the given char sequence that is offset
- * from the given <code>index</code> by <code>codePointOffset</code>
+ * from the given {@code index} by {@code codePointOffset}
* code points. Unpaired surrogates within the text range given by
- * <code>index</code> and <code>codePointOffset</code> count as
+ * {@code index} and {@code codePointOffset} count as
* one code point each.
*
* @param seq the char sequence
* @param index the index to be offset
* @param codePointOffset the offset in code points
* @return the index within the char sequence
- * @exception NullPointerException if <code>seq</code> is null.
- * @exception IndexOutOfBoundsException if <code>index</code>
+ * @exception NullPointerException if {@code seq} is null.
+ * @exception IndexOutOfBoundsException if {@code index}
* is negative or larger then the length of the char sequence,
- * or if <code>codePointOffset</code> is positive and the
- * subsequence starting with <code>index</code> has fewer than
- * <code>codePointOffset</code> code points, or if
- * <code>codePointOffset</code> is negative and the subsequence
- * before <code>index</code> has fewer than the absolute value
- * of <code>codePointOffset</code> code points.
+ * or if {@code codePointOffset} is positive and the
+ * subsequence starting with {@code index} has fewer than
+ * {@code codePointOffset} code points, or if
+ * {@code codePointOffset} is negative and the subsequence
+ * before {@code index} has fewer than the absolute value
+ * of {@code codePointOffset} code points.
* @since 1.5
*/
public static int offsetByCodePoints(CharSequence seq, int index,
@@ -5123,36 +5121,36 @@
}
/**
- * Returns the index within the given <code>char</code> subarray
- * that is offset from the given <code>index</code> by
- * <code>codePointOffset</code> code points. The
- * <code>start</code> and <code>count</code> arguments specify a
- * subarray of the <code>char</code> array. Unpaired surrogates
- * within the text range given by <code>index</code> and
- * <code>codePointOffset</code> count as one code point each.
- *
- * @param a the <code>char</code> array
- * @param start the index of the first <code>char</code> of the
+ * Returns the index within the given {@code char} subarray
+ * that is offset from the given {@code index} by
+ * {@code codePointOffset} code points. The
+ * {@code start} and {@code count} arguments specify a
+ * subarray of the {@code char} array. Unpaired surrogates
+ * within the text range given by {@code index} and
+ * {@code codePointOffset} count as one code point each.
+ *
+ * @param a the {@code char} array
+ * @param start the index of the first {@code char} of the
* subarray
- * @param count the length of the subarray in <code>char</code>s
+ * @param count the length of the subarray in {@code char}s
* @param index the index to be offset
* @param codePointOffset the offset in code points
* @return the index within the subarray
- * @exception NullPointerException if <code>a</code> is null.
+ * @exception NullPointerException if {@code a} is null.
* @exception IndexOutOfBoundsException
- * if <code>start</code> or <code>count</code> is negative,
- * or if <code>start + count</code> is larger than the length of
+ * if {@code start} or {@code count} is negative,
+ * or if {@code start + count} is larger than the length of
* the given array,
- * or if <code>index</code> is less than <code>start</code> or
- * larger then <code>start + count</code>,
- * or if <code>codePointOffset</code> is positive and the text range
- * starting with <code>index</code> and ending with <code>start
- * + count - 1</code> has fewer than <code>codePointOffset</code> code
+ * or if {@code index} is less than {@code start} or
+ * larger then {@code start + count},
+ * or if {@code codePointOffset} is positive and the text range
+ * starting with {@code index} and ending with {@code start + count - 1}
+ * has fewer than {@code codePointOffset} code
* points,
- * or if <code>codePointOffset</code> is negative and the text range
- * starting with <code>start</code> and ending with <code>index
- * - 1</code> has fewer than the absolute value of
- * <code>codePointOffset</code> code points.
+ * or if {@code codePointOffset} is negative and the text range
+ * starting with {@code start} and ending with {@code index - 1}
+ * has fewer than the absolute value of
+ * {@code codePointOffset} code points.
* @since 1.5
*/
public static int offsetByCodePoints(char[] a, int start, int count,
@@ -5198,8 +5196,8 @@
* Determines if the specified character is a lowercase character.
* <p>
* A character is lowercase if its general category type, provided
- * by <code>Character.getType(ch)</code>, is
- * <code>LOWERCASE_LETTER</code>.
+ * by {@code Character.getType(ch)}, is
+ * {@code LOWERCASE_LETTER}.
* <p>
* The following are examples of lowercase characters:
* <p><blockquote><pre>
@@ -5217,8 +5215,8 @@
* the {@link #isLowerCase(int)} method.
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character is lowercase;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is lowercase;
+ * {@code false} otherwise.
* @see Character#isLowerCase(char)
* @see Character#isTitleCase(char)
* @see Character#toLowerCase(char)
@@ -5234,7 +5232,7 @@
* <p>
* A character is lowercase if its general category type, provided
* by {@link Character#getType getType(codePoint)}, is
- * <code>LOWERCASE_LETTER</code>.
+ * {@code LOWERCASE_LETTER}.
* <p>
* The following are examples of lowercase characters:
* <p><blockquote><pre>
@@ -5247,8 +5245,8 @@
* <p> Many other Unicode characters are lowercase too.
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character is lowercase;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is lowercase;
+ * {@code false} otherwise.
* @see Character#isLowerCase(int)
* @see Character#isTitleCase(int)
* @see Character#toLowerCase(int)
@@ -5263,7 +5261,7 @@
* Determines if the specified character is an uppercase character.
* <p>
* A character is uppercase if its general category type, provided by
- * <code>Character.getType(ch)</code>, is <code>UPPERCASE_LETTER</code>.
+ * {@code Character.getType(ch)}, is {@code UPPERCASE_LETTER}.
* <p>
* The following are examples of uppercase characters:
* <p><blockquote><pre>
@@ -5281,8 +5279,8 @@
* the {@link #isUpperCase(int)} method.
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character is uppercase;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is uppercase;
+ * {@code false} otherwise.
* @see Character#isLowerCase(char)
* @see Character#isTitleCase(char)
* @see Character#toUpperCase(char)
@@ -5297,7 +5295,7 @@
* Determines if the specified character (Unicode code point) is an uppercase character.
* <p>
* A character is uppercase if its general category type, provided by
- * {@link Character#getType(int) getType(codePoint)}, is <code>UPPERCASE_LETTER</code>.
+ * {@link Character#getType(int) getType(codePoint)}, is {@code UPPERCASE_LETTER}.
* <p>
* The following are examples of uppercase characters:
* <p><blockquote><pre>
@@ -5310,8 +5308,8 @@
* <p> Many other Unicode characters are uppercase too.<p>
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character is uppercase;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is uppercase;
+ * {@code false} otherwise.
* @see Character#isLowerCase(int)
* @see Character#isTitleCase(int)
* @see Character#toUpperCase(int)
@@ -5326,8 +5324,8 @@
* Determines if the specified character is a titlecase character.
* <p>
* A character is a titlecase character if its general
- * category type, provided by <code>Character.getType(ch)</code>,
- * is <code>TITLECASE_LETTER</code>.
+ * category type, provided by {@code Character.getType(ch)},
+ * is {@code TITLECASE_LETTER}.
* <p>
* Some characters look like pairs of Latin letters. For example, there
* is an uppercase letter that looks like "LJ" and has a corresponding
@@ -5336,12 +5334,12 @@
* with initial capitals, as for a book title.
* <p>
* These are some of the Unicode characters for which this method returns
- * <code>true</code>:
+ * {@code true}:
* <ul>
- * <li><code>LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON</code>
- * <li><code>LATIN CAPITAL LETTER L WITH SMALL LETTER J</code>
- * <li><code>LATIN CAPITAL LETTER N WITH SMALL LETTER J</code>
- * <li><code>LATIN CAPITAL LETTER D WITH SMALL LETTER Z</code>
+ * <li>{@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON}
+ * <li>{@code LATIN CAPITAL LETTER L WITH SMALL LETTER J}
+ * <li>{@code LATIN CAPITAL LETTER N WITH SMALL LETTER J}
+ * <li>{@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z}
* </ul>
* <p> Many other Unicode characters are titlecase too.<p>
*
@@ -5351,8 +5349,8 @@
* the {@link #isTitleCase(int)} method.
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character is titlecase;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is titlecase;
+ * {@code false} otherwise.
* @see Character#isLowerCase(char)
* @see Character#isUpperCase(char)
* @see Character#toTitleCase(char)
@@ -5368,7 +5366,7 @@
* <p>
* A character is a titlecase character if its general
* category type, provided by {@link Character#getType(int) getType(codePoint)},
- * is <code>TITLECASE_LETTER</code>.
+ * is {@code TITLECASE_LETTER}.
* <p>
* Some characters look like pairs of Latin letters. For example, there
* is an uppercase letter that looks like "LJ" and has a corresponding
@@ -5377,18 +5375,18 @@
* with initial capitals, as for a book title.
* <p>
* These are some of the Unicode characters for which this method returns
- * <code>true</code>:
+ * {@code true}:
* <ul>
- * <li><code>LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON</code>
- * <li><code>LATIN CAPITAL LETTER L WITH SMALL LETTER J</code>
- * <li><code>LATIN CAPITAL LETTER N WITH SMALL LETTER J</code>
- * <li><code>LATIN CAPITAL LETTER D WITH SMALL LETTER Z</code>
+ * <li>{@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON}
+ * <li>{@code LATIN CAPITAL LETTER L WITH SMALL LETTER J}
+ * <li>{@code LATIN CAPITAL LETTER N WITH SMALL LETTER J}
+ * <li>{@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z}
* </ul>
* <p> Many other Unicode characters are titlecase too.<p>
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character is titlecase;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is titlecase;
+ * {@code false} otherwise.
* @see Character#isLowerCase(int)
* @see Character#isUpperCase(int)
* @see Character#toTitleCase(int)
@@ -5403,20 +5401,20 @@
* Determines if the specified character is a digit.
* <p>
* A character is a digit if its general category type, provided
- * by <code>Character.getType(ch)</code>, is
- * <code>DECIMAL_DIGIT_NUMBER</code>.
+ * by {@code Character.getType(ch)}, is
+ * {@code DECIMAL_DIGIT_NUMBER}.
* <p>
* Some Unicode character ranges that contain digits:
* <ul>
- * <li><code>'\u0030'</code> through <code>'\u0039'</code>,
- * ISO-LATIN-1 digits (<code>'0'</code> through <code>'9'</code>)
- * <li><code>'\u0660'</code> through <code>'\u0669'</code>,
+ * <li>{@code '\u005Cu0030'} through {@code '\u005Cu0039'},
+ * ISO-LATIN-1 digits ({@code '0'} through {@code '9'})
+ * <li>{@code '\u005Cu0660'} through {@code '\u005Cu0669'},
* Arabic-Indic digits
- * <li><code>'\u06F0'</code> through <code>'\u06F9'</code>,
+ * <li>{@code '\u005Cu06F0'} through {@code '\u005Cu06F9'},
* Extended Arabic-Indic digits
- * <li><code>'\u0966'</code> through <code>'\u096F'</code>,
+ * <li>{@code '\u005Cu0966'} through {@code '\u005Cu096F'},
* Devanagari digits
- * <li><code>'\uFF10'</code> through <code>'\uFF19'</code>,
+ * <li>{@code '\u005CuFF10'} through {@code '\u005CuFF19'},
* Fullwidth digits
* </ul>
*
@@ -5428,8 +5426,8 @@
* the {@link #isDigit(int)} method.
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character is a digit;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is a digit;
+ * {@code false} otherwise.
* @see Character#digit(char, int)
* @see Character#forDigit(int, int)
* @see Character#getType(char)
@@ -5443,27 +5441,27 @@
* <p>
* A character is a digit if its general category type, provided
* by {@link Character#getType(int) getType(codePoint)}, is
- * <code>DECIMAL_DIGIT_NUMBER</code>.
+ * {@code DECIMAL_DIGIT_NUMBER}.
* <p>
* Some Unicode character ranges that contain digits:
* <ul>
- * <li><code>'\u0030'</code> through <code>'\u0039'</code>,
- * ISO-LATIN-1 digits (<code>'0'</code> through <code>'9'</code>)
- * <li><code>'\u0660'</code> through <code>'\u0669'</code>,
+ * <li>{@code '\u005Cu0030'} through {@code '\u005Cu0039'},
+ * ISO-LATIN-1 digits ({@code '0'} through {@code '9'})
+ * <li>{@code '\u005Cu0660'} through {@code '\u005Cu0669'},
* Arabic-Indic digits
- * <li><code>'\u06F0'</code> through <code>'\u06F9'</code>,
+ * <li>{@code '\u005Cu06F0'} through {@code '\u005Cu06F9'},
* Extended Arabic-Indic digits
- * <li><code>'\u0966'</code> through <code>'\u096F'</code>,
+ * <li>{@code '\u005Cu0966'} through {@code '\u005Cu096F'},
* Devanagari digits
- * <li><code>'\uFF10'</code> through <code>'\uFF19'</code>,
+ * <li>{@code '\u005CuFF10'} through {@code '\u005CuFF19'},
* Fullwidth digits
* </ul>
*
* Many other character ranges contain digits as well.
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character is a digit;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is a digit;
+ * {@code false} otherwise.
* @see Character#forDigit(int, int)
* @see Character#getType(int)
* @since 1.5
@@ -5487,8 +5485,8 @@
* the {@link #isDefined(int)} method.
*
* @param ch the character to be tested
- * @return <code>true</code> if the character has a defined meaning
- * in Unicode; <code>false</code> otherwise.
+ * @return {@code true} if the character has a defined meaning
+ * in Unicode; {@code false} otherwise.
* @see Character#isDigit(char)
* @see Character#isLetter(char)
* @see Character#isLetterOrDigit(char)
@@ -5511,8 +5509,8 @@
* </ul>
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character has a defined meaning
- * in Unicode; <code>false</code> otherwise.
+ * @return {@code true} if the character has a defined meaning
+ * in Unicode; {@code false} otherwise.
* @see Character#isDigit(int)
* @see Character#isLetter(int)
* @see Character#isLetterOrDigit(int)
@@ -5529,14 +5527,14 @@
* Determines if the specified character is a letter.
* <p>
* A character is considered to be a letter if its general
- * category type, provided by <code>Character.getType(ch)</code>,
+ * category type, provided by {@code Character.getType(ch)},
* is any of the following:
* <ul>
- * <li> <code>UPPERCASE_LETTER</code>
- * <li> <code>LOWERCASE_LETTER</code>
- * <li> <code>TITLECASE_LETTER</code>
- * <li> <code>MODIFIER_LETTER</code>
- * <li> <code>OTHER_LETTER</code>
+ * <li> {@code UPPERCASE_LETTER}
+ * <li> {@code LOWERCASE_LETTER}
+ * <li> {@code TITLECASE_LETTER}
+ * <li> {@code MODIFIER_LETTER}
+ * <li> {@code OTHER_LETTER}
* </ul>
*
* Not all letters have case. Many characters are
@@ -5548,8 +5546,8 @@
* the {@link #isLetter(int)} method.
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character is a letter;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is a letter;
+ * {@code false} otherwise.
* @see Character#isDigit(char)
* @see Character#isJavaIdentifierStart(char)
* @see Character#isJavaLetter(char)
@@ -5571,19 +5569,19 @@
* category type, provided by {@link Character#getType(int) getType(codePoint)},
* is any of the following:
* <ul>
- * <li> <code>UPPERCASE_LETTER</code>
- * <li> <code>LOWERCASE_LETTER</code>
- * <li> <code>TITLECASE_LETTER</code>
- * <li> <code>MODIFIER_LETTER</code>
- * <li> <code>OTHER_LETTER</code>
+ * <li> {@code UPPERCASE_LETTER}
+ * <li> {@code LOWERCASE_LETTER}
+ * <li> {@code TITLECASE_LETTER}
+ * <li> {@code MODIFIER_LETTER}
+ * <li> {@code OTHER_LETTER}
* </ul>
*
* Not all letters have case. Many characters are
* letters but are neither uppercase nor lowercase nor titlecase.
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character is a letter;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is a letter;
+ * {@code false} otherwise.
* @see Character#isDigit(int)
* @see Character#isJavaIdentifierStart(int)
* @see Character#isLetterOrDigit(int)
@@ -5606,9 +5604,9 @@
* Determines if the specified character is a letter or digit.
* <p>
* A character is considered to be a letter or digit if either
- * <code>Character.isLetter(char ch)</code> or
- * <code>Character.isDigit(char ch)</code> returns
- * <code>true</code> for the character.
+ * {@code Character.isLetter(char ch)} or
+ * {@code Character.isDigit(char ch)} returns
+ * {@code true} for the character.
*
* <p><b>Note:</b> This method cannot handle <a
* href="#supplementary"> supplementary characters</a>. To support
@@ -5616,8 +5614,8 @@
* the {@link #isLetterOrDigit(int)} method.
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character is a letter or digit;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is a letter or digit;
+ * {@code false} otherwise.
* @see Character#isDigit(char)
* @see Character#isJavaIdentifierPart(char)
* @see Character#isJavaLetter(char)
@@ -5636,11 +5634,11 @@
* A character is considered to be a letter or digit if either
* {@link #isLetter(int) isLetter(codePoint)} or
* {@link #isDigit(int) isDigit(codePoint)} returns
- * <code>true</code> for the character.
+ * {@code true} for the character.
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character is a letter or digit;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is a letter or digit;
+ * {@code false} otherwise.
* @see Character#isDigit(int)
* @see Character#isJavaIdentifierPart(int)
* @see Character#isLetter(int)
@@ -5664,15 +5662,15 @@
* A character may start a Java identifier if and only if
* one of the following is true:
* <ul>
- * <li> {@link #isLetter(char) isLetter(ch)} returns <code>true</code>
- * <li> {@link #getType(char) getType(ch)} returns <code>LETTER_NUMBER</code>
- * <li> ch is a currency symbol (such as "$")
- * <li> ch is a connecting punctuation character (such as "_").
+ * <li> {@link #isLetter(char) isLetter(ch)} returns {@code true}
+ * <li> {@link #getType(char) getType(ch)} returns {@code LETTER_NUMBER}
+ * <li> {@code ch} is a currency symbol (such as {@code '$'})
+ * <li> {@code ch} is a connecting punctuation character (such as {@code '_'}).
* </ul>
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character may start a Java
- * identifier; <code>false</code> otherwise.
+ * @return {@code true} if the character may start a Java
+ * identifier; {@code false} otherwise.
* @see Character#isJavaLetterOrDigit(char)
* @see Character#isJavaIdentifierStart(char)
* @see Character#isJavaIdentifierPart(char)
@@ -5695,19 +5693,19 @@
* of the following are true:
* <ul>
* <li> it is a letter
- * <li> it is a currency symbol (such as <code>'$'</code>)
- * <li> it is a connecting punctuation character (such as <code>'_'</code>)
+ * <li> it is a currency symbol (such as {@code '$'})
+ * <li> it is a connecting punctuation character (such as {@code '_'})
* <li> it is a digit
* <li> it is a numeric letter (such as a Roman numeral character)
* <li> it is a combining mark
* <li> it is a non-spacing mark
- * <li> <code>isIdentifierIgnorable</code> returns
- * <code>true</code> for the character.
+ * <li> {@code isIdentifierIgnorable} returns
+ * {@code true} for the character.
* </ul>
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character may be part of a
- * Java identifier; <code>false</code> otherwise.
+ * @return {@code true} if the character may be part of a
+ * Java identifier; {@code false} otherwise.
* @see Character#isJavaLetter(char)
* @see Character#isJavaIdentifierStart(char)
* @see Character#isJavaIdentifierPart(char)
@@ -5730,10 +5728,10 @@
* A character may start a Java identifier if and only if
* one of the following conditions is true:
* <ul>
- * <li> {@link #isLetter(char) isLetter(ch)} returns <code>true</code>
- * <li> {@link #getType(char) getType(ch)} returns <code>LETTER_NUMBER</code>
- * <li> ch is a currency symbol (such as "$")
- * <li> ch is a connecting punctuation character (such as "_").
+ * <li> {@link #isLetter(char) isLetter(ch)} returns {@code true}
+ * <li> {@link #getType(char) getType(ch)} returns {@code LETTER_NUMBER}
+ * <li> {@code ch} is a currency symbol (such as {@code '$'})
+ * <li> {@code ch} is a connecting punctuation character (such as {@code '_'}).
* </ul>
*
* <p><b>Note:</b> This method cannot handle <a
@@ -5742,8 +5740,8 @@
* the {@link #isJavaIdentifierStart(int)} method.
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character may start a Java identifier;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character may start a Java identifier;
+ * {@code false} otherwise.
* @see Character#isJavaIdentifierPart(char)
* @see Character#isLetter(char)
* @see Character#isUnicodeIdentifierStart(char)
@@ -5762,17 +5760,17 @@
* one of the following conditions is true:
* <ul>
* <li> {@link #isLetter(int) isLetter(codePoint)}
- * returns <code>true</code>
+ * returns {@code true}
* <li> {@link #getType(int) getType(codePoint)}
- * returns <code>LETTER_NUMBER</code>
- * <li> the referenced character is a currency symbol (such as "$")
+ * returns {@code LETTER_NUMBER}
+ * <li> the referenced character is a currency symbol (such as {@code '$'})
* <li> the referenced character is a connecting punctuation character
- * (such as "_").
+ * (such as {@code '_'}).
* </ul>
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character may start a Java identifier;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character may start a Java identifier;
+ * {@code false} otherwise.
* @see Character#isJavaIdentifierPart(int)
* @see Character#isLetter(int)
* @see Character#isUnicodeIdentifierStart(int)
@@ -5791,14 +5789,14 @@
* are true:
* <ul>
* <li> it is a letter
- * <li> it is a currency symbol (such as <code>'$'</code>)
- * <li> it is a connecting punctuation character (such as <code>'_'</code>)
+ * <li> it is a currency symbol (such as {@code '$'})
+ * <li> it is a connecting punctuation character (such as {@code '_'})
* <li> it is a digit
* <li> it is a numeric letter (such as a Roman numeral character)
* <li> it is a combining mark
* <li> it is a non-spacing mark
- * <li> <code>isIdentifierIgnorable</code> returns
- * <code>true</code> for the character
+ * <li> {@code isIdentifierIgnorable} returns
+ * {@code true} for the character
* </ul>
*
* <p><b>Note:</b> This method cannot handle <a
@@ -5807,8 +5805,8 @@
* the {@link #isJavaIdentifierPart(int)} method.
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character may be part of a
- * Java identifier; <code>false</code> otherwise.
+ * @return {@code true} if the character may be part of a
+ * Java identifier; {@code false} otherwise.
* @see Character#isIdentifierIgnorable(char)
* @see Character#isJavaIdentifierStart(char)
* @see Character#isLetterOrDigit(char)
@@ -5828,20 +5826,20 @@
* are true:
* <ul>
* <li> it is a letter
- * <li> it is a currency symbol (such as <code>'$'</code>)
- * <li> it is a connecting punctuation character (such as <code>'_'</code>)
+ * <li> it is a currency symbol (such as {@code '$'})
+ * <li> it is a connecting punctuation character (such as {@code '_'})
* <li> it is a digit
* <li> it is a numeric letter (such as a Roman numeral character)
* <li> it is a combining mark
* <li> it is a non-spacing mark
* <li> {@link #isIdentifierIgnorable(int)
- * isIdentifierIgnorable(codePoint)} returns <code>true</code> for
+ * isIdentifierIgnorable(codePoint)} returns {@code true} for
* the character
* </ul>
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character may be part of a
- * Java identifier; <code>false</code> otherwise.
+ * @return {@code true} if the character may be part of a
+ * Java identifier; {@code false} otherwise.
* @see Character#isIdentifierIgnorable(int)
* @see Character#isJavaIdentifierStart(int)
* @see Character#isLetterOrDigit(int)
@@ -5860,9 +5858,9 @@
* A character may start a Unicode identifier if and only if
* one of the following conditions is true:
* <ul>
- * <li> {@link #isLetter(char) isLetter(ch)} returns <code>true</code>
+ * <li> {@link #isLetter(char) isLetter(ch)} returns {@code true}
* <li> {@link #getType(char) getType(ch)} returns
- * <code>LETTER_NUMBER</code>.
+ * {@code LETTER_NUMBER}.
* </ul>
*
* <p><b>Note:</b> This method cannot handle <a
@@ -5871,8 +5869,8 @@
* the {@link #isUnicodeIdentifierStart(int)} method.
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character may start a Unicode
- * identifier; <code>false</code> otherwise.
+ * @return {@code true} if the character may start a Unicode
+ * identifier; {@code false} otherwise.
* @see Character#isJavaIdentifierStart(char)
* @see Character#isLetter(char)
* @see Character#isUnicodeIdentifierPart(char)
@@ -5890,13 +5888,13 @@
* one of the following conditions is true:
* <ul>
* <li> {@link #isLetter(int) isLetter(codePoint)}
- * returns <code>true</code>
+ * returns {@code true}
* <li> {@link #getType(int) getType(codePoint)}
- * returns <code>LETTER_NUMBER</code>.
+ * returns {@code LETTER_NUMBER}.
* </ul>
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character may start a Unicode
- * identifier; <code>false</code> otherwise.
+ * @return {@code true} if the character may start a Unicode
+ * identifier; {@code false} otherwise.
* @see Character#isJavaIdentifierStart(int)
* @see Character#isLetter(int)
* @see Character#isUnicodeIdentifierPart(int)
@@ -5914,13 +5912,13 @@
* one of the following statements is true:
* <ul>
* <li> it is a letter
- * <li> it is a connecting punctuation character (such as <code>'_'</code>)
+ * <li> it is a connecting punctuation character (such as {@code '_'})
* <li> it is a digit
* <li> it is a numeric letter (such as a Roman numeral character)
* <li> it is a combining mark
* <li> it is a non-spacing mark
- * <li> <code>isIdentifierIgnorable</code> returns
- * <code>true</code> for this character.
+ * <li> {@code isIdentifierIgnorable} returns
+ * {@code true} for this character.
* </ul>
*
* <p><b>Note:</b> This method cannot handle <a
@@ -5929,8 +5927,8 @@
* the {@link #isUnicodeIdentifierPart(int)} method.
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character may be part of a
- * Unicode identifier; <code>false</code> otherwise.
+ * @return {@code true} if the character may be part of a
+ * Unicode identifier; {@code false} otherwise.
* @see Character#isIdentifierIgnorable(char)
* @see Character#isJavaIdentifierPart(char)
* @see Character#isLetterOrDigit(char)
@@ -5949,17 +5947,17 @@
* one of the following statements is true:
* <ul>
* <li> it is a letter
- * <li> it is a connecting punctuation character (such as <code>'_'</code>)
+ * <li> it is a connecting punctuation character (such as {@code '_'})
* <li> it is a digit
* <li> it is a numeric letter (such as a Roman numeral character)
* <li> it is a combining mark
* <li> it is a non-spacing mark
- * <li> <code>isIdentifierIgnorable</code> returns
- * <code>true</code> for this character.
+ * <li> {@code isIdentifierIgnorable} returns
+ * {@code true} for this character.
* </ul>
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character may be part of a
- * Unicode identifier; <code>false</code> otherwise.
+ * @return {@code true} if the character may be part of a
+ * Unicode identifier; {@code false} otherwise.
* @see Character#isIdentifierIgnorable(int)
* @see Character#isJavaIdentifierPart(int)
* @see Character#isLetterOrDigit(int)
@@ -5979,12 +5977,12 @@
* <ul>
* <li>ISO control characters that are not whitespace
* <ul>
- * <li><code>'\u0000'</code> through <code>'\u0008'</code>
- * <li><code>'\u000E'</code> through <code>'\u001B'</code>
- * <li><code>'\u007F'</code> through <code>'\u009F'</code>
+ * <li>{@code '\u005Cu0000'} through {@code '\u005Cu0008'}
+ * <li>{@code '\u005Cu000E'} through {@code '\u005Cu001B'}
+ * <li>{@code '\u005Cu007F'} through {@code '\u005Cu009F'}
* </ul>
*
- * <li>all characters that have the <code>FORMAT</code> general
+ * <li>all characters that have the {@code FORMAT} general
* category value
* </ul>
*
@@ -5994,9 +5992,9 @@
* the {@link #isIdentifierIgnorable(int)} method.
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character is an ignorable control
+ * @return {@code true} if the character is an ignorable control
* character that may be part of a Java or Unicode identifier;
- * <code>false</code> otherwise.
+ * {@code false} otherwise.
* @see Character#isJavaIdentifierPart(char)
* @see Character#isUnicodeIdentifierPart(char)
* @since 1.1
@@ -6014,19 +6012,19 @@
* <ul>
* <li>ISO control characters that are not whitespace
* <ul>
- * <li><code>'\u0000'</code> through <code>'\u0008'</code>
- * <li><code>'\u000E'</code> through <code>'\u001B'</code>
- * <li><code>'\u007F'</code> through <code>'\u009F'</code>
+ * <li>{@code '\u005Cu0000'} through {@code '\u005Cu0008'}
+ * <li>{@code '\u005Cu000E'} through {@code '\u005Cu001B'}
+ * <li>{@code '\u005Cu007F'} through {@code '\u005Cu009F'}
* </ul>
*
- * <li>all characters that have the <code>FORMAT</code> general
+ * <li>all characters that have the {@code FORMAT} general
* category value
* </ul>
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character is an ignorable control
+ * @return {@code true} if the character is an ignorable control
* character that may be part of a Java or Unicode identifier;
- * <code>false</code> otherwise.
+ * {@code false} otherwise.
* @see Character#isJavaIdentifierPart(int)
* @see Character#isUnicodeIdentifierPart(int)
* @since 1.5
@@ -6040,16 +6038,16 @@
* mapping information from the UnicodeData file.
* <p>
* Note that
- * <code>Character.isLowerCase(Character.toLowerCase(ch))</code>
- * does not always return <code>true</code> for some ranges of
+ * {@code Character.isLowerCase(Character.toLowerCase(ch))}
+ * does not always return {@code true} for some ranges of
* characters, particularly those that are symbols or ideographs.
*
* <p>In general, {@link String#toLowerCase()} should be used to map
- * characters to lowercase. <code>String</code> case mapping methods
- * have several benefits over <code>Character</code> case mapping methods.
- * <code>String</code> case mapping methods can perform locale-sensitive
+ * characters to lowercase. {@code String} case mapping methods
+ * have several benefits over {@code Character} case mapping methods.
+ * {@code String} case mapping methods can perform locale-sensitive
* mappings, context-sensitive mappings, and 1:M character mappings, whereas
- * the <code>Character</code> case mapping methods cannot.
+ * the {@code Character} case mapping methods cannot.
*
* <p><b>Note:</b> This method cannot handle <a
* href="#supplementary"> supplementary characters</a>. To support
@@ -6072,16 +6070,16 @@
* file.
*
* <p> Note that
- * <code>Character.isLowerCase(Character.toLowerCase(codePoint))</code>
- * does not always return <code>true</code> for some ranges of
+ * {@code Character.isLowerCase(Character.toLowerCase(codePoint))}
+ * does not always return {@code true} for some ranges of
* characters, particularly those that are symbols or ideographs.
*
* <p>In general, {@link String#toLowerCase()} should be used to map
- * characters to lowercase. <code>String</code> case mapping methods
- * have several benefits over <code>Character</code> case mapping methods.
- * <code>String</code> case mapping methods can perform locale-sensitive
+ * characters to lowercase. {@code String} case mapping methods
+ * have several benefits over {@code Character} case mapping methods.
+ * {@code String} case mapping methods can perform locale-sensitive
* mappings, context-sensitive mappings, and 1:M character mappings, whereas
- * the <code>Character</code> case mapping methods cannot.
+ * the {@code Character} case mapping methods cannot.
*
* @param codePoint the character (Unicode code point) to be converted.
* @return the lowercase equivalent of the character (Unicode code
@@ -6100,16 +6098,16 @@
* information from the UnicodeData file.
* <p>
* Note that
- * <code>Character.isUpperCase(Character.toUpperCase(ch))</code>
- * does not always return <code>true</code> for some ranges of
+ * {@code Character.isUpperCase(Character.toUpperCase(ch))}
+ * does not always return {@code true} for some ranges of
* characters, particularly those that are symbols or ideographs.
*
* <p>In general, {@link String#toUpperCase()} should be used to map
- * characters to uppercase. <code>String</code> case mapping methods
- * have several benefits over <code>Character</code> case mapping methods.
- * <code>String</code> case mapping methods can perform locale-sensitive
+ * characters to uppercase. {@code String} case mapping methods
+ * have several benefits over {@code Character} case mapping methods.
+ * {@code String} case mapping methods can perform locale-sensitive
* mappings, context-sensitive mappings, and 1:M character mappings, whereas
- * the <code>Character</code> case mapping methods cannot.
+ * the {@code Character} case mapping methods cannot.
*
* <p><b>Note:</b> This method cannot handle <a
* href="#supplementary"> supplementary characters</a>. To support
@@ -6132,16 +6130,16 @@
* file.
*
* <p>Note that
- * <code>Character.isUpperCase(Character.toUpperCase(codePoint))</code>
- * does not always return <code>true</code> for some ranges of
+ * {@code Character.isUpperCase(Character.toUpperCase(codePoint))}
+ * does not always return {@code true} for some ranges of
* characters, particularly those that are symbols or ideographs.
*
* <p>In general, {@link String#toUpperCase()} should be used to map
- * characters to uppercase. <code>String</code> case mapping methods
- * have several benefits over <code>Character</code> case mapping methods.
- * <code>String</code> case mapping methods can perform locale-sensitive
+ * characters to uppercase. {@code String} case mapping methods
+ * have several benefits over {@code Character} case mapping methods.
+ * {@code String} case mapping methods can perform locale-sensitive
* mappings, context-sensitive mappings, and 1:M character mappings, whereas
- * the <code>Character</code> case mapping methods cannot.
+ * the {@code Character} case mapping methods cannot.
*
* @param codePoint the character (Unicode code point) to be converted.
* @return the uppercase equivalent of the character, if any;
@@ -6161,13 +6159,13 @@
* explicit titlecase mapping and is not itself a titlecase char
* according to UnicodeData, then the uppercase mapping is
* returned as an equivalent titlecase mapping. If the
- * <code>char</code> argument is already a titlecase
- * <code>char</code>, the same <code>char</code> value will be
+ * {@code char} argument is already a titlecase
+ * {@code char}, the same {@code char} value will be
* returned.
* <p>
* Note that
- * <code>Character.isTitleCase(Character.toTitleCase(ch))</code>
- * does not always return <code>true</code> for some ranges of
+ * {@code Character.isTitleCase(Character.toTitleCase(ch))}
+ * does not always return {@code true} for some ranges of
* characters.
*
* <p><b>Note:</b> This method cannot handle <a
@@ -6198,8 +6196,8 @@
* returned.
*
* <p>Note that
- * <code>Character.isTitleCase(Character.toTitleCase(codePoint))</code>
- * does not always return <code>true</code> for some ranges of
+ * {@code Character.isTitleCase(Character.toTitleCase(codePoint))}
+ * does not always return {@code true} for some ranges of
* characters.
*
* @param codePoint the character (Unicode code point) to be converted.
@@ -6215,28 +6213,40 @@
}
/**
- * Returns the numeric value of the character <code>ch</code> in the
+ * Returns the numeric value of the character {@code ch} in the
* specified radix.
* <p>
- * If the radix is not in the range <code>MIN_RADIX</code> <=
- * <code>radix</code> <= <code>MAX_RADIX</code> or if the
- * value of <code>ch</code> is not a valid digit in the specified
- * radix, <code>-1</code> is returned. A character is a valid digit
+ * If the radix is not in the range {@code MIN_RADIX} ≤
+ * {@code radix} ≤ {@code MAX_RADIX} or if the
+ * value of {@code ch} is not a valid digit in the specified
+ * radix, {@code -1} is returned. A character is a valid digit
* if at least one of the following is true:
* <ul>
- * <li>The method <code>isDigit</code> is <code>true</code> of the character
+ * <li>The method {@code isDigit} is {@code true} of the character
* and the Unicode decimal digit value of the character (or its
* single-character decomposition) is less than the specified radix.
* In this case the decimal digit value is returned.
* <li>The character is one of the uppercase Latin letters
- * <code>'A'</code> through <code>'Z'</code> and its code is less than
- * <code>radix + 'A' - 10</code>.
- * In this case, <code>ch - 'A' + 10</code>
+ * {@code 'A'} through {@code 'Z'} and its code is less than
+ * {@code radix + 'A' - 10}.
+ * In this case, {@code ch - 'A' + 10}
* is returned.
* <li>The character is one of the lowercase Latin letters
- * <code>'a'</code> through <code>'z'</code> and its code is less than
- * <code>radix + 'a' - 10</code>.
- * In this case, <code>ch - 'a' + 10</code>
+ * {@code 'a'} through {@code 'z'} and its code is less than
+ * {@code radix + 'a' - 10}.
+ * In this case, {@code ch - 'a' + 10}
+ * is returned.
+ * <li>The character is one of the fullwidth uppercase Latin letters A
+ * ({@code '\u005CuFF21'}) through Z ({@code '\u005CuFF3A'})
+ * and its code is less than
+ * {@code radix + '\u005CuFF21' - 10}.
+ * In this case, {@code ch - '\u005CuFF21' + 10}
+ * is returned.
+ * <li>The character is one of the fullwidth lowercase Latin letters a
+ * ({@code '\u005CuFF41'}) through z ({@code '\u005CuFF5A'})
+ * and its code is less than
+ * {@code radix + '\u005CuFF41' - 10}.
+ * In this case, {@code ch - '\u005CuFF41' + 10}
* is returned.
* </ul>
*
@@ -6260,25 +6270,39 @@
* Returns the numeric value of the specified character (Unicode
* code point) in the specified radix.
*
- * <p>If the radix is not in the range <code>MIN_RADIX</code> <=
- * <code>radix</code> <= <code>MAX_RADIX</code> or if the
+ * <p>If the radix is not in the range {@code MIN_RADIX} ≤
+ * {@code radix} ≤ {@code MAX_RADIX} or if the
* character is not a valid digit in the specified
- * radix, <code>-1</code> is returned. A character is a valid digit
+ * radix, {@code -1} is returned. A character is a valid digit
* if at least one of the following is true:
* <ul>
- * <li>The method {@link #isDigit(int) isDigit(codePoint)} is <code>true</code> of the character
+ * <li>The method {@link #isDigit(int) isDigit(codePoint)} is {@code true} of the character
* and the Unicode decimal digit value of the character (or its
* single-character decomposition) is less than the specified radix.
* In this case the decimal digit value is returned.
* <li>The character is one of the uppercase Latin letters
- * <code>'A'</code> through <code>'Z'</code> and its code is less than
- * <code>radix + 'A' - 10</code>.
- * In this case, <code>ch - 'A' + 10</code>
+ * {@code 'A'} through {@code 'Z'} and its code is less than
+ * {@code radix + 'A' - 10}.
+ * In this case, {@code codePoint - 'A' + 10}
* is returned.
* <li>The character is one of the lowercase Latin letters
- * <code>'a'</code> through <code>'z'</code> and its code is less than
- * <code>radix + 'a' - 10</code>.
- * In this case, <code>ch - 'a' + 10</code>
+ * {@code 'a'} through {@code 'z'} and its code is less than
+ * {@code radix + 'a' - 10}.
+ * In this case, {@code codePoint - 'a' + 10}
+ * is returned.
+ * <li>The character is one of the fullwidth uppercase Latin letters A
+ * ({@code '\u005CuFF21'}) through Z ({@code '\u005CuFF3A'})
+ * and its code is less than
+ * {@code radix + '\u005CuFF21' - 10}.
+ * In this case,
+ * {@code codePoint - '\u005CuFF21' + 10}
+ * is returned.
+ * <li>The character is one of the fullwidth lowercase Latin letters a
+ * ({@code '\u005CuFF41'}) through z ({@code '\u005CuFF5A'})
+ * and its code is less than
+ * {@code radix + '\u005CuFF41'- 10}.
+ * In this case,
+ * {@code codePoint - '\u005CuFF41' + 10}
* is returned.
* </ul>
*
@@ -6295,19 +6319,19 @@
}
/**
- * Returns the <code>int</code> value that the specified Unicode
+ * Returns the {@code int} value that the specified Unicode
* character represents. For example, the character
- * <code>'\u216C'</code> (the roman numeral fifty) will return
+ * {@code '\u005Cu216C'} (the roman numeral fifty) will return
* an int with a value of 50.
* <p>
- * The letters A-Z in their uppercase (<code>'\u0041'</code> through
- * <code>'\u005A'</code>), lowercase
- * (<code>'\u0061'</code> through <code>'\u007A'</code>), and
- * full width variant (<code>'\uFF21'</code> through
- * <code>'\uFF3A'</code> and <code>'\uFF41'</code> through
- * <code>'\uFF5A'</code>) forms have numeric values from 10
+ * The letters A-Z in their uppercase ({@code '\u005Cu0041'} through
+ * {@code '\u005Cu005A'}), lowercase
+ * ({@code '\u005Cu0061'} through {@code '\u005Cu007A'}), and
+ * full width variant ({@code '\u005CuFF21'} through
+ * {@code '\u005CuFF3A'} and {@code '\u005CuFF41'} through
+ * {@code '\u005CuFF5A'}) forms have numeric values from 10
* through 35. This is independent of the Unicode specification,
- * which does not assign numeric values to these <code>char</code>
+ * which does not assign numeric values to these {@code char}
* values.
* <p>
* If the character does not have a numeric value, then -1 is returned.
@@ -6321,7 +6345,7 @@
* the {@link #getNumericValue(int)} method.
*
* @param ch the character to be converted.
- * @return the numeric value of the character, as a nonnegative <code>int</code>
+ * @return the numeric value of the character, as a nonnegative {@code int}
* value; -2 if the character has a numeric value that is not a
* nonnegative integer; -1 if the character has no numeric value.
* @see Character#forDigit(int, int)
@@ -6333,19 +6357,19 @@
}
/**
- * Returns the <code>int</code> value that the specified
+ * Returns the {@code int} value that the specified
* character (Unicode code point) represents. For example, the character
- * <code>'\u216C'</code> (the Roman numeral fifty) will return
- * an <code>int</code> with a value of 50.
+ * {@code '\u005Cu216C'} (the Roman numeral fifty) will return
+ * an {@code int} with a value of 50.
* <p>
- * The letters A-Z in their uppercase (<code>'\u0041'</code> through
- * <code>'\u005A'</code>), lowercase
- * (<code>'\u0061'</code> through <code>'\u007A'</code>), and
- * full width variant (<code>'\uFF21'</code> through
- * <code>'\uFF3A'</code> and <code>'\uFF41'</code> through
- * <code>'\uFF5A'</code>) forms have numeric values from 10
+ * The letters A-Z in their uppercase ({@code '\u005Cu0041'} through
+ * {@code '\u005Cu005A'}), lowercase
+ * ({@code '\u005Cu0061'} through {@code '\u005Cu007A'}), and
+ * full width variant ({@code '\u005CuFF21'} through
+ * {@code '\u005CuFF3A'} and {@code '\u005CuFF41'} through
+ * {@code '\u005CuFF5A'}) forms have numeric values from 10
* through 35. This is independent of the Unicode specification,
- * which does not assign numeric values to these <code>char</code>
+ * which does not assign numeric values to these {@code char}
* values.
* <p>
* If the character does not have a numeric value, then -1 is returned.
@@ -6354,7 +6378,7 @@
* is returned.
*
* @param codePoint the character (Unicode code point) to be converted.
- * @return the numeric value of the character, as a nonnegative <code>int</code>
+ * @return the numeric value of the character, as a nonnegative {@code int}
* value; -2 if the character has a numeric value that is not a
* nonnegative integer; -1 if the character has no numeric value.
* @see Character#forDigit(int, int)
@@ -6367,24 +6391,24 @@
/**
* Determines if the specified character is ISO-LATIN-1 white space.
- * This method returns <code>true</code> for the following five
+ * This method returns {@code true} for the following five
* characters only:
* <table>
- * <tr><td><code>'\t'</code></td> <td><code>U+0009</code></td>
- * <td><code>HORIZONTAL TABULATION</code></td></tr>
- * <tr><td><code>'\n'</code></td> <td><code>U+000A</code></td>
- * <td><code>NEW LINE</code></td></tr>
- * <tr><td><code>'\f'</code></td> <td><code>U+000C</code></td>
- * <td><code>FORM FEED</code></td></tr>
- * <tr><td><code>'\r'</code></td> <td><code>U+000D</code></td>
- * <td><code>CARRIAGE RETURN</code></td></tr>
- * <tr><td><code>' '</code></td> <td><code>U+0020</code></td>
- * <td><code>SPACE</code></td></tr>
+ * <tr><td>{@code '\t'}</td> <td>{@code U+0009}</td>
+ * <td>{@code HORIZONTAL TABULATION}</td></tr>
+ * <tr><td>{@code '\n'}</td> <td>{@code U+000A}</td>
+ * <td>{@code NEW LINE}</td></tr>
+ * <tr><td>{@code '\f'}</td> <td>{@code U+000C}</td>
+ * <td>{@code FORM FEED}</td></tr>
+ * <tr><td>{@code '\r'}</td> <td>{@code U+000D}</td>
+ * <td>{@code CARRIAGE RETURN}</td></tr>
+ * <tr><td>{@code ' '}</td> <td>{@code U+0020}</td>
+ * <td>{@code SPACE}</td></tr>
* </table>
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character is ISO-LATIN-1 white
- * space; <code>false</code> otherwise.
+ * @return {@code true} if the character is ISO-LATIN-1 white
+ * space; {@code false} otherwise.
* @see Character#isSpaceChar(char)
* @see Character#isWhitespace(char)
* @deprecated Replaced by isWhitespace(char).
@@ -6407,9 +6431,9 @@
* method returns true if the character's general category type is any of
* the following:
* <ul>
- * <li> <code>SPACE_SEPARATOR</code>
- * <li> <code>LINE_SEPARATOR</code>
- * <li> <code>PARAGRAPH_SEPARATOR</code>
+ * <li> {@code SPACE_SEPARATOR}
+ * <li> {@code LINE_SEPARATOR}
+ * <li> {@code PARAGRAPH_SEPARATOR}
* </ul>
*
* <p><b>Note:</b> This method cannot handle <a
@@ -6418,8 +6442,8 @@
* the {@link #isSpaceChar(int)} method.
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character is a space character;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is a space character;
+ * {@code false} otherwise.
* @see Character#isWhitespace(char)
* @since 1.1
*/
@@ -6441,8 +6465,8 @@
* </ul>
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character is a space character;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is a space character;
+ * {@code false} otherwise.
* @see Character#isWhitespace(int)
* @since 1.5
*/
@@ -6458,19 +6482,19 @@
* A character is a Java whitespace character if and only if it satisfies
* one of the following criteria:
* <ul>
- * <li> It is a Unicode space character (<code>SPACE_SEPARATOR</code>,
- * <code>LINE_SEPARATOR</code>, or <code>PARAGRAPH_SEPARATOR</code>)
- * but is not also a non-breaking space (<code>'\u00A0'</code>,
- * <code>'\u2007'</code>, <code>'\u202F'</code>).
- * <li> It is <code>'\t'</code>, U+0009 HORIZONTAL TABULATION.
- * <li> It is <code>'\n'</code>, U+000A LINE FEED.
- * <li> It is <code>'\u000B'</code>, U+000B VERTICAL TABULATION.
- * <li> It is <code>'\f'</code>, U+000C FORM FEED.
- * <li> It is <code>'\r'</code>, U+000D CARRIAGE RETURN.
- * <li> It is <code>'\u001C'</code>, U+001C FILE SEPARATOR.
- * <li> It is <code>'\u001D'</code>, U+001D GROUP SEPARATOR.
- * <li> It is <code>'\u001E'</code>, U+001E RECORD SEPARATOR.
- * <li> It is <code>'\u001F'</code>, U+001F UNIT SEPARATOR.
+ * <li> It is a Unicode space character ({@code SPACE_SEPARATOR},
+ * {@code LINE_SEPARATOR}, or {@code PARAGRAPH_SEPARATOR})
+ * but is not also a non-breaking space ({@code '\u005Cu00A0'},
+ * {@code '\u005Cu2007'}, {@code '\u005Cu202F'}).
+ * <li> It is {@code '\u005Ct'}, U+0009 HORIZONTAL TABULATION.
+ * <li> It is {@code '\u005Cn'}, U+000A LINE FEED.
+ * <li> It is {@code '\u005Cu000B'}, U+000B VERTICAL TABULATION.
+ * <li> It is {@code '\u005Cf'}, U+000C FORM FEED.
+ * <li> It is {@code '\u005Cr'}, U+000D CARRIAGE RETURN.
+ * <li> It is {@code '\u005Cu001C'}, U+001C FILE SEPARATOR.
+ * <li> It is {@code '\u005Cu001D'}, U+001D GROUP SEPARATOR.
+ * <li> It is {@code '\u005Cu001E'}, U+001E RECORD SEPARATOR.
+ * <li> It is {@code '\u005Cu001F'}, U+001F UNIT SEPARATOR.
* </ul>
*
* <p><b>Note:</b> This method cannot handle <a
@@ -6479,8 +6503,8 @@
* the {@link #isWhitespace(int)} method.
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character is a Java whitespace
- * character; <code>false</code> otherwise.
+ * @return {@code true} if the character is a Java whitespace
+ * character; {@code false} otherwise.
* @see Character#isSpaceChar(char)
* @since 1.1
*/
@@ -6496,23 +6520,23 @@
* <ul>
* <li> It is a Unicode space character ({@link #SPACE_SEPARATOR},
* {@link #LINE_SEPARATOR}, or {@link #PARAGRAPH_SEPARATOR})
- * but is not also a non-breaking space (<code>'\u00A0'</code>,
- * <code>'\u2007'</code>, <code>'\u202F'</code>).
- * <li> It is <code>'\t'</code>, U+0009 HORIZONTAL TABULATION.
- * <li> It is <code>'\n'</code>, U+000A LINE FEED.
- * <li> It is <code>'\u000B'</code>, U+000B VERTICAL TABULATION.
- * <li> It is <code>'\f'</code>, U+000C FORM FEED.
- * <li> It is <code>'\r'</code>, U+000D CARRIAGE RETURN.
- * <li> It is <code>'\u001C'</code>, U+001C FILE SEPARATOR.
- * <li> It is <code>'\u001D'</code>, U+001D GROUP SEPARATOR.
- * <li> It is <code>'\u001E'</code>, U+001E RECORD SEPARATOR.
- * <li> It is <code>'\u001F'</code>, U+001F UNIT SEPARATOR.
+ * but is not also a non-breaking space ({@code '\u005Cu00A0'},
+ * {@code '\u005Cu2007'}, {@code '\u005Cu202F'}).
+ * <li> It is {@code '\u005Ct'}, U+0009 HORIZONTAL TABULATION.
+ * <li> It is {@code '\u005Cn'}, U+000A LINE FEED.
+ * <li> It is {@code '\u005Cu000B'}, U+000B VERTICAL TABULATION.
+ * <li> It is {@code '\u005Cf'}, U+000C FORM FEED.
+ * <li> It is {@code '\u005Cr'}, U+000D CARRIAGE RETURN.
+ * <li> It is {@code '\u005Cu001C'}, U+001C FILE SEPARATOR.
+ * <li> It is {@code '\u005Cu001D'}, U+001D GROUP SEPARATOR.
+ * <li> It is {@code '\u005Cu001E'}, U+001E RECORD SEPARATOR.
+ * <li> It is {@code '\u005Cu001F'}, U+001F UNIT SEPARATOR.
* </ul>
* <p>
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character is a Java whitespace
- * character; <code>false</code> otherwise.
+ * @return {@code true} if the character is a Java whitespace
+ * character; {@code false} otherwise.
* @see Character#isSpaceChar(int)
* @since 1.5
*/
@@ -6523,9 +6547,9 @@
/**
* Determines if the specified character is an ISO control
* character. A character is considered to be an ISO control
- * character if its code is in the range <code>'\u0000'</code>
- * through <code>'\u001F'</code> or in the range
- * <code>'\u007F'</code> through <code>'\u009F'</code>.
+ * character if its code is in the range {@code '\u005Cu0000'}
+ * through {@code '\u005Cu001F'} or in the range
+ * {@code '\u005Cu007F'} through {@code '\u005Cu009F'}.
*
* <p><b>Note:</b> This method cannot handle <a
* href="#supplementary"> supplementary characters</a>. To support
@@ -6533,8 +6557,8 @@
* the {@link #isISOControl(int)} method.
*
* @param ch the character to be tested.
- * @return <code>true</code> if the character is an ISO control character;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is an ISO control character;
+ * {@code false} otherwise.
*
* @see Character#isSpaceChar(char)
* @see Character#isWhitespace(char)
@@ -6547,13 +6571,13 @@
/**
* Determines if the referenced character (Unicode code point) is an ISO control
* character. A character is considered to be an ISO control
- * character if its code is in the range <code>'\u0000'</code>
- * through <code>'\u001F'</code> or in the range
- * <code>'\u007F'</code> through <code>'\u009F'</code>.
+ * character if its code is in the range {@code '\u005Cu0000'}
+ * through {@code '\u005Cu001F'} or in the range
+ * {@code '\u005Cu007F'} through {@code '\u005Cu009F'}.
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character is an ISO control character;
- * <code>false</code> otherwise.
+ * @return {@code true} if the character is an ISO control character;
+ * {@code false} otherwise.
* @see Character#isSpaceChar(int)
* @see Character#isWhitespace(int)
* @since 1.5
@@ -6575,7 +6599,7 @@
* the {@link #getType(int)} method.
*
* @param ch the character to be tested.
- * @return a value of type <code>int</code> representing the
+ * @return a value of type {@code int} representing the
* character's general category.
* @see Character#COMBINING_SPACING_MARK
* @see Character#CONNECTOR_PUNCTUATION
@@ -6617,7 +6641,7 @@
* Returns a value indicating a character's general category.
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return a value of type <code>int</code> representing the
+ * @return a value of type {@code int} representing the
* character's general category.
* @see Character#COMBINING_SPACING_MARK COMBINING_SPACING_MARK
* @see Character#CONNECTOR_PUNCTUATION CONNECTOR_PUNCTUATION
@@ -6657,23 +6681,23 @@
/**
* Determines the character representation for a specific digit in
- * the specified radix. If the value of <code>radix</code> is not a
- * valid radix, or the value of <code>digit</code> is not a valid
+ * the specified radix. If the value of {@code radix} is not a
+ * valid radix, or the value of {@code digit} is not a valid
* digit in the specified radix, the null character
- * (<code>'\u0000'</code>) is returned.
+ * ({@code '\u005Cu0000'}) is returned.
* <p>
- * The <code>radix</code> argument is valid if it is greater than or
- * equal to <code>MIN_RADIX</code> and less than or equal to
- * <code>MAX_RADIX</code>. The <code>digit</code> argument is valid if
- * <code>0 <=digit < radix</code>.
+ * The {@code radix} argument is valid if it is greater than or
+ * equal to {@code MIN_RADIX} and less than or equal to
+ * {@code MAX_RADIX}. The {@code digit} argument is valid if
+ * {@code 0 <= digit < radix}.
* <p>
* If the digit is less than 10, then
- * <code>'0' + digit</code> is returned. Otherwise, the value
- * <code>'a' + digit - 10</code> is returned.
+ * {@code '0' + digit} is returned. Otherwise, the value
+ * {@code 'a' + digit - 10} is returned.
*
* @param digit the number to convert to a character.
* @param radix the radix.
- * @return the <code>char</code> representation of the specified digit
+ * @return the {@code char} representation of the specified digit
* in the specified radix.
* @see Character#MIN_RADIX
* @see Character#MAX_RADIX
@@ -6696,16 +6720,16 @@
* Returns the Unicode directionality property for the given
* character. Character directionality is used to calculate the
* visual ordering of text. The directionality value of undefined
- * <code>char</code> values is <code>DIRECTIONALITY_UNDEFINED</code>.
+ * {@code char} values is {@code DIRECTIONALITY_UNDEFINED}.
*
* <p><b>Note:</b> This method cannot handle <a
* href="#supplementary"> supplementary characters</a>. To support
* all Unicode characters, including supplementary characters, use
* the {@link #getDirectionality(int)} method.
*
- * @param ch <code>char</code> for which the directionality property
+ * @param ch {@code char} for which the directionality property
* is requested.
- * @return the directionality property of the <code>char</code> value.
+ * @return the directionality property of the {@code char} value.
*
* @see Character#DIRECTIONALITY_UNDEFINED
* @see Character#DIRECTIONALITY_LEFT_TO_RIGHT
@@ -6774,7 +6798,7 @@
* Determines whether the character is mirrored according to the
* Unicode specification. Mirrored characters should have their
* glyphs horizontally mirrored when displayed in text that is
- * right-to-left. For example, <code>'\u0028'</code> LEFT
+ * right-to-left. For example, {@code '\u005Cu0028'} LEFT
* PARENTHESIS is semantically defined to be an <i>opening
* parenthesis</i>. This will appear as a "(" in text that is
* left-to-right but as a ")" in text that is right-to-left.
@@ -6784,9 +6808,9 @@
* all Unicode characters, including supplementary characters, use
* the {@link #isMirrored(int)} method.
*
- * @param ch <code>char</code> for which the mirrored property is requested
- * @return <code>true</code> if the char is mirrored, <code>false</code>
- * if the <code>char</code> is not mirrored or is not defined.
+ * @param ch {@code char} for which the mirrored property is requested
+ * @return {@code true} if the char is mirrored, {@code false}
+ * if the {@code char} is not mirrored or is not defined.
* @since 1.4
*/
public static boolean isMirrored(char ch) {
@@ -6798,13 +6822,13 @@
* is mirrored according to the Unicode specification. Mirrored
* characters should have their glyphs horizontally mirrored when
* displayed in text that is right-to-left. For example,
- * <code>'\u0028'</code> LEFT PARENTHESIS is semantically
+ * {@code '\u005Cu0028'} LEFT PARENTHESIS is semantically
* defined to be an <i>opening parenthesis</i>. This will appear
* as a "(" in text that is left-to-right but as a ")" in text
* that is right-to-left.
*
* @param codePoint the character (Unicode code point) to be tested.
- * @return <code>true</code> if the character is mirrored, <code>false</code>
+ * @return {@code true} if the character is mirrored, {@code false}
* if the character is not mirrored or is not defined.
* @since 1.5
*/
@@ -6813,16 +6837,16 @@
}
/**
- * Compares two <code>Character</code> objects numerically.
- *
- * @param anotherCharacter the <code>Character</code> to be compared.
-
- * @return the value <code>0</code> if the argument <code>Character</code>
- * is equal to this <code>Character</code>; a value less than
- * <code>0</code> if this <code>Character</code> is numerically less
- * than the <code>Character</code> argument; and a value greater than
- * <code>0</code> if this <code>Character</code> is numerically greater
- * than the <code>Character</code> argument (unsigned comparison).
+ * Compares two {@code Character} objects numerically.
+ *
+ * @param anotherCharacter the {@code Character} to be compared.
+
+ * @return the value {@code 0} if the argument {@code Character}
+ * is equal to this {@code Character}; a value less than
+ * {@code 0} if this {@code Character} is numerically less
+ * than the {@code Character} argument; and a value greater than
+ * {@code 0} if this {@code Character} is numerically greater
+ * than the {@code Character} argument (unsigned comparison).
* Note that this is strictly a numerical comparison; it is not
* locale-dependent.
* @since 1.2
@@ -6856,8 +6880,8 @@
*
* @param codePoint the character (Unicode code point) to be converted.
* @return either the uppercase equivalent of the character, if
- * any, or an error flag (<code>Character.ERROR</code>)
- * that indicates that a 1:M <code>char</code> mapping exists.
+ * any, or an error flag ({@code Character.ERROR})
+ * that indicates that a 1:M {@code char} mapping exists.
* @see Character#isLowerCase(char)
* @see Character#isUpperCase(char)
* @see Character#toLowerCase(char)
@@ -6873,11 +6897,11 @@
* Converts the character (Unicode code point) argument to uppercase using case
* mapping information from the SpecialCasing file in the Unicode
* specification. If a character has no explicit uppercase
- * mapping, then the <code>char</code> itself is returned in the
- * <code>char[]</code>.
+ * mapping, then the {@code char} itself is returned in the
+ * {@code char[]}.
*
* @param codePoint the character (Unicode code point) to be converted.
- * @return a <code>char[]</code> with the uppercased character.
+ * @return a {@code char[]} with the uppercased character.
* @since 1.4
*/
static char[] toUpperCaseCharArray(int codePoint) {
@@ -6908,7 +6932,7 @@
/**
* Returns the Unicode name of the specified character
- * <code>codePoint</code>, or null if the code point is
+ * {@code codePoint}, or null if the code point is
* {@link #UNASSIGNED unassigned}.
* <p>
* Note: if the specified character is not assigned a name by
@@ -6916,14 +6940,12 @@
* Database maintained by the Unicode Consortium), the returned
* name is the same as the result of expression
*
- * <blockquote><code>
- * Character.UnicodeBlock.of(codePoint)
- * .toString()
- * .replace('_', ' ')
+ * <blockquote>{@code
+ * Character.UnicodeBlock.of(codePoint).toString().replace('_', ' ')
* + " "
* + Integer.toHexString(codePoint).toUpperCase(Locale.ENGLISH);
*
- * </code></blockquote>
+ * }</blockquote>
*
* @param codePoint the character (Unicode code point)
*
@@ -6931,7 +6953,7 @@
* the code point is unassigned.
*
* @exception IllegalArgumentException if the specified
- * <code>codePoint</code> is not a valid Unicode
+ * {@code codePoint} is not a valid Unicode
* code point.
*
* @since 1.7
--- a/jdk/src/share/classes/java/lang/NullPointerException.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/lang/NullPointerException.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -26,20 +26,24 @@
package java.lang;
/**
- * Thrown when an application attempts to use <code>null</code> in a
+ * Thrown when an application attempts to use {@code null} in a
* case where an object is required. These include:
* <ul>
- * <li>Calling the instance method of a <code>null</code> object.
- * <li>Accessing or modifying the field of a <code>null</code> object.
- * <li>Taking the length of <code>null</code> as if it were an array.
- * <li>Accessing or modifying the slots of <code>null</code> as if it
+ * <li>Calling the instance method of a {@code null} object.
+ * <li>Accessing or modifying the field of a {@code null} object.
+ * <li>Taking the length of {@code null} as if it were an array.
+ * <li>Accessing or modifying the slots of {@code null} as if it
* were an array.
- * <li>Throwing <code>null</code> as if it were a <code>Throwable</code>
+ * <li>Throwing {@code null} as if it were a {@code Throwable}
* value.
* </ul>
* <p>
* Applications should throw instances of this class to indicate
- * other illegal uses of the <code>null</code> object.
+ * other illegal uses of the {@code null} object.
+ *
+ * {@code NullPointerException} objects may be constructed by the
+ * virtual machine as if {@linkplain Throwable#Throwable(String,
+ * Throwable, boolean) suppression were disabled}.
*
* @author unascribed
* @since JDK1.0
@@ -49,14 +53,14 @@
private static final long serialVersionUID = 5162710183389028792L;
/**
- * Constructs a <code>NullPointerException</code> with no detail message.
+ * Constructs a {@code NullPointerException} with no detail message.
*/
public NullPointerException() {
super();
}
/**
- * Constructs a <code>NullPointerException</code> with the specified
+ * Constructs a {@code NullPointerException} with the specified
* detail message.
*
* @param s the detail message.
--- a/jdk/src/share/classes/java/lang/OutOfMemoryError.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/lang/OutOfMemoryError.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -30,22 +30,25 @@
* because it is out of memory, and no more memory could be made
* available by the garbage collector.
*
+ * {@code OutOfMemoryError} objects may be constructed by the virtual
+ * machine as if {@linkplain Throwable#Throwable(String, Throwable,
+ * boolean) suppression were disabled}.
+ *
* @author unascribed
* @since JDK1.0
*/
-public
-class OutOfMemoryError extends VirtualMachineError {
+public class OutOfMemoryError extends VirtualMachineError {
private static final long serialVersionUID = 8228564086184010517L;
/**
- * Constructs an <code>OutOfMemoryError</code> with no detail message.
+ * Constructs an {@code OutOfMemoryError} with no detail message.
*/
public OutOfMemoryError() {
super();
}
/**
- * Constructs an <code>OutOfMemoryError</code> with the specified
+ * Constructs an {@code OutOfMemoryError} with the specified
* detail message.
*
* @param s the detail message.
--- a/jdk/src/share/classes/java/lang/Throwable.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/lang/Throwable.java Sun Apr 10 10:23:28 2011 -0700
@@ -46,13 +46,16 @@
* are freshly created in the context of the exceptional situation so
* as to include relevant information (such as stack trace data).
*
- * <p>A throwable contains a snapshot of the execution stack of its thread at
- * the time it was created. It can also contain a message string that gives
- * more information about the error. Finally, it can contain a <i>cause</i>:
- * another throwable that caused this throwable to get thrown. The cause
- * facility is new in release 1.4. It is also known as the <i>chained
- * exception</i> facility, as the cause can, itself, have a cause, and so on,
- * leading to a "chain" of exceptions, each caused by another.
+ * <p>A throwable contains a snapshot of the execution stack of its
+ * thread at the time it was created. It can also contain a message
+ * string that gives more information about the error. Over time, a
+ * throwable can {@linkplain Throwable#addSuppressed suppress} other
+ * throwables from being propagated. Finally, the throwable can also
+ * contain a <i>cause</i>: another throwable that caused this
+ * throwable to be constructed. The recording of this causal information
+ * is referred to as the <i>chained exception</i> facility, as the
+ * cause can, itself, have a cause, and so on, leading to a "chain" of
+ * exceptions, each caused by another.
*
* <p>One reason that a throwable may have a cause is that the class that
* throws it is built atop a lower layered abstraction, and an operation on
@@ -86,47 +89,12 @@
* {@link #initCause(Throwable)} method. New throwable classes that
* wish to allow causes to be associated with them should provide constructors
* that take a cause and delegate (perhaps indirectly) to one of the
- * {@code Throwable} constructors that takes a cause. For example:
- * <pre>
- * try {
- * lowLevelOp();
- * } catch (LowLevelException le) {
- * throw new HighLevelException(le); // Chaining-aware constructor
- * }
- * </pre>
+ * {@code Throwable} constructors that takes a cause.
+ *
* Because the {@code initCause} method is public, it allows a cause to be
* associated with any throwable, even a "legacy throwable" whose
* implementation predates the addition of the exception chaining mechanism to
- * {@code Throwable}. For example:
- * <pre>
- * try {
- * lowLevelOp();
- * } catch (LowLevelException le) {
- * throw (HighLevelException)
- * new HighLevelException().initCause(le); // Legacy constructor
- * }
- * </pre>
- *
- * <p>Prior to release 1.4, there were many throwables that had their own
- * non-standard exception chaining mechanisms (
- * {@link ExceptionInInitializerError}, {@link ClassNotFoundException},
- * {@link java.lang.reflect.UndeclaredThrowableException},
- * {@link java.lang.reflect.InvocationTargetException},
- * {@link java.io.WriteAbortedException},
- * {@link java.security.PrivilegedActionException},
- * {@link java.awt.print.PrinterIOException},
- * {@link java.rmi.RemoteException} and
- * {@link javax.naming.NamingException}).
- * All of these throwables have been retrofitted to
- * use the standard exception chaining mechanism, while continuing to
- * implement their "legacy" chaining mechanisms for compatibility.
- *
- * <p>Further, as of release 1.4, many general purpose {@code Throwable}
- * classes (for example {@link Exception}, {@link RuntimeException},
- * {@link Error}) have been retrofitted with constructors that take
- * a cause. This was not strictly necessary, due to the existence of the
- * {@code initCause} method, but it is more convenient and expressive to
- * delegate to a constructor that takes a cause.
+ * {@code Throwable}.
*
* <p>By convention, class {@code Throwable} and its subclasses have two
* constructors, one that takes no arguments and one that takes a
@@ -137,14 +105,6 @@
* {@code String} (the detail message) and a {@code Throwable} (the
* cause).
*
- * <p>Also introduced in release 1.4 is the {@link #getStackTrace()} method,
- * which allows programmatic access to the stack trace information that was
- * previously available only in text form, via the various forms of the
- * {@link #printStackTrace()} method. This information has been added to the
- * <i>serialized representation</i> of this class so {@code getStackTrace}
- * and {@code printStackTrace} will operate properly on a throwable that
- * was obtained by deserialization.
- *
* @author unascribed
* @author Josh Bloch (Added exception chaining and programmatic access to
* stack trace in 1.4.)
@@ -323,6 +283,41 @@
}
/**
+ * Constructs a new throwable with the specified detail message,
+ * cause, and {@linkplain #addSuppressed suppression} enabled or
+ * disabled. If suppression is disabled, {@link #getSuppressed}
+ * for this object will return a zero-length array and calls to
+ * {@link #addSuppressed} that would otherwise append an exception
+ * to the suppressed list will have no effect.
+ *
+ * <p>Note that the other constructors of {@code Throwable} treat
+ * suppression as being enabled. Subclasses of {@code Throwable}
+ * should document any conditions under which suppression is
+ * disabled. Disabling of suppression should only occur in
+ * exceptional circumstances where special requirements exist,
+ * such as a virtual machine reusing exception objects under
+ * low-memory situations.
+ *
+ * @param message the detail message.
+ * @param cause the cause. (A {@code null} value is permitted,
+ * and indicates that the cause is nonexistent or unknown.)
+ * @param enableSuppression whether or not suppression is enabled or disabled
+ *
+ * @see OutOfMemoryError
+ * @see NullPointerException
+ * @see ArithmeticException
+ * @since 1.7
+ */
+ protected Throwable(String message, Throwable cause,
+ boolean enableSuppression) {
+ fillInStackTrace();
+ detailMessage = message;
+ this.cause = cause;
+ if (!enableSuppression)
+ suppressedExceptions = null;
+ }
+
+ /**
* Returns the detail message string of this throwable.
*
* @return the detail message string of this {@code Throwable} instance
@@ -870,54 +865,64 @@
* typically called (automatically and implicitly) by the {@code
* try}-with-resources statement.
*
- * If the first exception to be suppressed is {@code null}, that
- * indicates suppressed exception information will <em>not</em> be
- * recorded for this exception. Subsequent calls to this method
- * will not record any suppressed exceptions. Otherwise,
- * attempting to suppress {@code null} after an exception has
- * already been successfully suppressed results in a {@code
- * NullPointerException}.
+ * <p>The suppression behavior is enabled <em>unless</em> disabled
+ * {@linkplain #Throwable(String, Throwable, boolean) via a
+ * constructor}. When suppression is disabled, this method does
+ * nothing other than to validate its argument.
*
* <p>Note that when one exception {@linkplain
* #initCause(Throwable) causes} another exception, the first
* exception is usually caught and then the second exception is
- * thrown in response. In contrast, when one exception suppresses
- * another, two exceptions are thrown in sibling code blocks, such
- * as in a {@code try} block and in its {@code finally} block, and
- * control flow can only continue with one exception so the second
- * is recorded as a suppressed exception of the first.
+ * thrown in response. In other words, there is a causal
+ * connection between the two exceptions.
+ *
+ * In contrast, there are situations where two independent
+ * exceptions can be thrown in sibling code blocks, in particular
+ * in the {@code try} block of a {@code try}-with-resources
+ * statement and the compiler-generated {@code finally} block
+ * which closes the resource.
+ *
+ * In these situations, only one of the thrown exceptions can be
+ * propagated. In the {@code try}-with-resources statement, when
+ * there are two such exceptions, the exception originating from
+ * the {@code try} block is propagated and the exception from the
+ * {@code finally} block is added to the list of exceptions
+ * suppressed by the exception from the {@code try} block. As an
+ * exception unwinds the stack, it can accumulate multiple
+ * suppressed exceptions.
+ *
+ * <p>An exception may have suppressed exceptions while also being
+ * caused by another exception. Whether or not an exception has a
+ * cause is semantically known at the time of its creation, unlike
+ * whether or not an exception will suppress other exceptions
+ * which is typically only determined after an exception is
+ * thrown.
+ *
+ * <p>Note that programmer written code is also able to take
+ * advantage of calling this method in situations where there are
+ * multiple sibling exceptions and only one can be propagated.
*
* @param exception the exception to be added to the list of
* suppressed exceptions
* @throws IllegalArgumentException if {@code exception} is this
* throwable; a throwable cannot suppress itself.
- * @throws NullPointerException if {@code exception} is null and
- * an exception has already been suppressed by this exception
+ * @throws NullPointerException if {@code exception} is {@code null}
* @since 1.7
*/
public final synchronized void addSuppressed(Throwable exception) {
if (exception == this)
throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
- if (exception == null) {
- if (suppressedExceptions == SUPPRESSED_SENTINEL) {
- suppressedExceptions = null; // No suppression information recorded
- return;
- } else
- throw new NullPointerException(NULL_CAUSE_MESSAGE);
- } else {
- assert exception != null && exception != this;
+ if (exception == null)
+ throw new NullPointerException(NULL_CAUSE_MESSAGE);
- if (suppressedExceptions == null) // Suppressed exceptions not recorded
- return;
+ if (suppressedExceptions == null) // Suppressed exceptions not recorded
+ return;
- if (suppressedExceptions == SUPPRESSED_SENTINEL)
- suppressedExceptions = new ArrayList<>(1);
+ if (suppressedExceptions == SUPPRESSED_SENTINEL)
+ suppressedExceptions = new ArrayList<>(1);
- assert suppressedExceptions != SUPPRESSED_SENTINEL;
-
- suppressedExceptions.add(exception);
- }
+ suppressedExceptions.add(exception);
}
private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
@@ -927,7 +932,9 @@
* suppressed, typically by the {@code try}-with-resources
* statement, in order to deliver this exception.
*
- * If no exceptions were suppressed, an empty array is returned.
+ * If no exceptions were suppressed or {@linkplain
+ * Throwable(String, Throwable, boolean) suppression is disabled},
+ * an empty array is returned.
*
* @return an array containing all of the exceptions that were
* suppressed to deliver this exception.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/java/lang/management/BufferPoolMXBean.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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.lang.management;
+
+/**
+ * The management interface for a buffer pool, for example a pool of
+ * {@link java.nio.ByteBuffer#allocateDirect direct} or {@link
+ * java.nio.MappedByteBuffer mapped} buffers.
+ *
+ * <p> A class implementing this interface is an
+ * {@link javax.management.MXBean}. A Java
+ * virtual machine has one or more implementations of this interface. The {@link
+ * java.lang.management.ManagementFactory#getPlatformMXBeans getPlatformMXBeans}
+ * method can be used to obtain the list of {@code BufferPoolMXBean} objects
+ * representing the management interfaces for pools of buffers as follows:
+ * <pre>
+ * List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
+ * </pre>
+ *
+ * <p> The management interfaces are also registered with the platform {@link
+ * javax.management.MBeanServer MBeanServer}. The {@link
+ * javax.management.ObjectName ObjectName} that uniquely identifies the
+ * management interface within the {@code MBeanServer} takes the form:
+ * <pre>
+ * java.nio:type=BufferPool,name=<i>pool name</i>
+ * </pre>
+ * where <em>pool name</em> is the {@link #getName name} of the buffer pool.
+ *
+ * @since 1.7
+ */
+public interface BufferPoolMXBean extends PlatformManagedObject {
+
+ /**
+ * Returns the name representing this buffer pool.
+ *
+ * @return The name of this buffer pool.
+ */
+ String getName();
+
+ /**
+ * Returns an estimate of the number of buffers in the pool.
+ *
+ * @return An estimate of the number of buffers in this pool
+ */
+ long getCount();
+
+ /**
+ * Returns an estimate of the total capacity of the buffers in this pool.
+ * A buffer's capacity is the number of elements it contains and the value
+ * returned by this method is an estimate of the total capacity of buffers
+ * in the pool in bytes.
+ *
+ * @return An estimate of the total capacity of the buffers in this pool
+ * in bytes
+ */
+ long getTotalCapacity();
+
+ /**
+ * Returns an estimate of the memory that the Java virtual machine is using
+ * for this buffer pool. The value returned by this method may differ
+ * from the estimate of the total {@link #getTotalCapacity capacity} of
+ * the buffers in this pool. This difference is explained by alignment,
+ * memory allocator, and other implementation specific reasons.
+ *
+ * @return An estimate of the memory that the Java virtual machine is using
+ * for this buffer pool in bytes, or {@code -1L} if an estimate of
+ * the memory usage is not available
+ */
+ long getMemoryUsed();
+}
--- a/jdk/src/share/classes/java/lang/management/ManagementFactory.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/lang/management/ManagementFactory.java Sun Apr 10 10:23:28 2011 -0700
@@ -40,8 +40,9 @@
import javax.management.StandardEmitterMBean;
import javax.management.StandardMBean;
import java.util.Collections;
-import java.util.ArrayList;
import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
import java.security.AccessController;
import java.security.Permission;
import java.security.PrivilegedAction;
@@ -51,37 +52,63 @@
import sun.management.ManagementFactoryHelper;
/**
- * The <tt>ManagementFactory</tt> class is a factory class for getting
+ * The {@code ManagementFactory} class is a factory class for getting
* managed beans for the Java platform.
* This class consists of static methods each of which returns
- * one or more <a href="#MXBean">platform MXBean(s)</a> representing
+ * one or more <i>platform MXBeans</i> representing
* the management interface of a component of the Java virtual
* machine.
+ * <p>
+ * <h4><a name="MXBean">Platform MXBeans</a></h4>
+ * <p>
+ * A platform MXBean is a <i>managed bean</i> that
+ * conforms to the <a href="../../../javax/management/package-summary.html">JMX</a>
+ * Instrumentation Specification and only uses a set of basic data types.
+ * A JMX management application and the {@linkplain
+ * #getPlatformMBeanServer platform MBeanServer}
+ * can interoperate without requiring classes for MXBean specific
+ * data types.
+ * The data types being transmitted between the JMX connector
+ * server and the connector client are
+ * {@linkplain javax.management.openmbean.OpenType open types}
+ * and this allows interoperation across versions.
+ * See <a href="../../../javax/management/MXBean.html#MXBean-spec">
+ * the specification of MXBeans</a> for details.
+ *
+ * <a name="MXBeanNames"></a>
+ * <p>Each platform MXBean is a {@link PlatformManagedObject}
+ * and it has a unique
+ * {@link javax.management.ObjectName ObjectName} for
+ * registration in the platform {@code MBeanServer} as returned by
+ * by the {@link PlatformManagedObject#getObjectName getObjectName}
+ * method.
*
* <p>
* An application can access a platform MXBean in the following ways:
+ * <h5>1. Direct access to an MXBean interface</h5>
+ * <blockquote>
* <ul>
- * <li><i>Direct access to an MXBean interface</i>
- * <ol type="a">
- * <li>Get the MXBean instance through the static factory method,
- * or the {@link #getPlatformMXBeans(Class)} method
- * and access the MXBean locally of the running
+ * <li>Get an MXBean instance by calling the
+ * {@link #getPlatformMXBean(Class) getPlatformMXBean} or
+ * {@link #getPlatformMXBeans(Class) getPlatformMXBeans} method
+ * and access the MXBean locally in the running
* virtual machine.
* </li>
* <li>Construct an MXBean proxy instance that forwards the
* method calls to a given {@link MBeanServer MBeanServer} by calling
- * the {@link #newPlatformMXBeanProxy newPlatformMXBeanProxy} method
- * or the {@link #getPlatformMXBeans(MBeanServerConnection, Class)}
- * method.
+ * the {@link #getPlatformMXBean(MBeanServerConnection, Class)} or
+ * {@link #getPlatformMXBeans(MBeanServerConnection, Class)} method.
+ * The {@link #newPlatformMXBeanProxy newPlatformMXBeanProxy} method
+ * can also be used to construct an MXBean proxy instance of
+ * a given {@code ObjectName}.
* A proxy is typically constructed to remotely access
* an MXBean of another running virtual machine.
* </li>
- * </ol></li>
- * <li><i>Indirect access to an MXBean interface via MBeanServer</i>
- * <ol type="a">
- * <li>Go through the {@link #getPlatformMBeanServer
- * platform MBeanServer} to access MXBeans locally or
- * a specific <tt>MBeanServerConnection</tt> to access
+ * </ul>
+ * <h5>2. Indirect access to an MXBean interface via MBeanServer</h5>
+ * <ul>
+ * <li>Go through the platform {@code MBeanServer} to access MXBeans
+ * locally or a specific <tt>MBeanServerConnection</tt> to access
* MXBeans remotely.
* The attributes and operations of an MXBean use only
* <em>JMX open types</em> which include basic data types,
@@ -89,133 +116,19 @@
* and {@link javax.management.openmbean.TabularData TabularData}
* defined in
* {@link javax.management.openmbean.OpenType OpenType}.
- * The mapping is specified below.
+ * The mapping is specified in
+ * the {@linkplain javax.management.MXBean MXBean} specification
+ * for details.
* </li>
- * </ol></li>
* </ul>
- *
- * <h4><a name="MXBean">Platform MXBeans</a></h4>
- * A platform MXBean is a <i>managed bean</i> that conforms to
- * the JMX Instrumentation Specification and only uses
- * a set of basic data types described below.
- * See <a href="../../../javax/management/MXBean.html#MXBean-spec">
- * the specification of MXBeans</a> for details.
- * All platform MXBean interfaces extend {@link PlatformManagedObject}s
- * and new methods may be added in these interfaces
- * in future Java SE releases.
- * <p>
- * A JMX management application and the platform <tt>MBeanServer</tt>
- * can interoperate without requiring classes for MXBean specific
- * data types.
- * The data types being transmitted between the JMX connector
- * server and the connector client are
- * {@linkplain javax.management.openmbean.OpenType open types}
- * and this allows interoperation across versions.
- * <p>
- * The platform MXBean interfaces use only the following data types:
- * <ul>
- * <li>Primitive types such as <tt>int</tt>, <tt>long</tt>,
- * <tt>boolean</tt>, etc</li>
- * <li>Wrapper classes for primitive types such as
- * {@link java.lang.Integer Integer}, {@link java.lang.Long Long},
- * {@link java.lang.Boolean Boolean}, etc and
- * {@link java.lang.String String}</li>
- * <li>{@link java.lang.Enum Enum} classes</li>
- * <li>Classes that define only getter methods and define a static
- * <tt>from</tt> method with a
- * {@link javax.management.openmbean.CompositeData CompositeData}
- * argument to convert from an input <tt>CompositeData</tt> to
- * an instance of that class
- * </li>
- * <li>{@link java.util.List List<E>}
- * where <tt>E</tt> is a primitive type, a wrapper class,
- * an enum class, or a class supporting conversion from a
- * <tt>CompositeData</tt> to its class
- * </li>
- * <li>{@link java.util.Map Map<K,V>}
- * where <tt>K</tt> and <tt>V</tt> are
- * a primitive type, a wrapper class,
- * an enum class, or a class supporting conversion from a
- * <tt>CompositeData</tt> to its class
- * </li>
- * </ul>
+ * </blockquote>
*
* <p>
- * When an attribute or operation of a platform MXBean
- * is accessed via an <tt>MBeanServer</tt>, the data types are mapped
- * as follows:
- * <ul>
- * <li>A primitive type or a wrapper class is mapped
- * to the same type.
- * </li>
- * <li>An {@link Enum} is mapped to
- * <tt>String</tt> whose value is the name of the enum constant.
- * <li>A class that defines only getter methods and a static
- * <tt>from</tt> method with a
- * {@link javax.management.openmbean.CompositeData CompositeData}
- * argument is mapped to
- * {@link javax.management.openmbean.CompositeData CompositeData}.
- * </li>
- * <li><tt>Map<K,V></tt> is mapped to
- * {@link javax.management.openmbean.TabularData TabularData}
- * whose row type is a
- * {@link javax.management.openmbean.CompositeType CompositeType} with
- * two items whose names are <i>"key"</i> and <i>"value"</i>
- * and the item types are
- * the corresponding mapped type of <tt>K</tt> and <tt>V</tt>
- * respectively and the <i>"key"</i> is the index.
- * </li>
- * <li><tt>List<E></tt> is mapped to an array with the mapped
- * type of <tt>E</tt> as the element type.
- * </li>
- * <li>An array of element type <tt>E</tt> is mapped to
- * an array of the same dimenions with the mapped type of <tt>E</tt>
- * as the element type.</li>
- * </ul>
- *
- * The {@link javax.management.MBeanInfo MBeanInfo}
- * for a platform MXBean
- * describes the data types of the attributes and operations
- * as primitive or open types mapped as specified above.
- *
+ * The {@link #getPlatformManagementInterfaces getPlatformManagementInterfaces}
+ * method returns all management interfaces supported in the Java virtual machine
+ * including the standard management interfaces listed in the tables
+ * below as well as the management interfaces extended by the JDK implementation.
* <p>
- * For example, the {@link MemoryMXBean}
- * interface has the following <i>getter</i> and <i>setter</i> methods:
- *
- * <blockquote><pre>
- * public MemoryUsage getHeapMemoryUsage();
- * public boolean isVerbose();
- * public void setVerbose(boolean value);
- * </pre></blockquote>
- *
- * These attributes in the <tt>MBeanInfo</tt>
- * of the <tt>MemoryMXBean</tt> have the following names and types:
- *
- * <blockquote>
- * <table border>
- * <tr>
- * <th>Attribute Name</th>
- * <th>Type</th>
- * </tr>
- * <tr>
- * <td><tt>HeapMemoryUsage</tt></td>
- * <td>{@link MemoryUsage#from
- * CompositeData representing MemoryUsage}</td>
- * </tr>
- * <tr>
- * <td><tt>Verbose</tt></td>
- * <td><tt>boolean</tt></td>
- * </tr>
- * </table>
- * </blockquote>
- *
- * <h4><a name="MXBeanNames">MXBean Names</a></h4>
- * Each platform MXBean for a Java virtual machine has a unique
- * {@link javax.management.ObjectName ObjectName} for
- * registration in the platform <tt>MBeanServer</tt> that can
- * be obtained by calling the {@link PlatformManagedObject#getObjectName}
- * method.
- *
* A Java virtual machine has a single instance of the following management
* interfaces:
*
@@ -228,27 +141,32 @@
* <tr>
* <td> {@link ClassLoadingMXBean} </td>
* <td> {@link #CLASS_LOADING_MXBEAN_NAME
- * <tt>java.lang:type=ClassLoading</tt>}</td>
+ * java.lang:type=ClassLoading}</td>
* </tr>
* <tr>
* <td> {@link MemoryMXBean} </td>
* <td> {@link #MEMORY_MXBEAN_NAME
- * <tt>java.lang:type=Memory</tt>}</td>
+ * java.lang:type=Memory}</td>
* </tr>
* <tr>
* <td> {@link ThreadMXBean} </td>
* <td> {@link #THREAD_MXBEAN_NAME
- * <tt>java.lang:type=Threading</tt>}</td>
+ * java.lang:type=Threading}</td>
* </tr>
* <tr>
* <td> {@link RuntimeMXBean} </td>
* <td> {@link #RUNTIME_MXBEAN_NAME
- * <tt>java.lang:type=Runtime</tt>}</td>
+ * java.lang:type=Runtime}</td>
* </tr>
* <tr>
* <td> {@link OperatingSystemMXBean} </td>
* <td> {@link #OPERATING_SYSTEM_MXBEAN_NAME
- * <tt>java.lang:type=OperatingSystem</tt>}</td>
+ * java.lang:type=OperatingSystem}</td>
+ * </tr>
+ * <tr>
+ * <td> {@link PlatformLoggingMXBean} </td>
+ * <td> {@link java.util.logging.LogManager#LOGGING_MXBEAN_NAME
+ * java.util.logging:type=Logging}</td>
* </tr>
* </table>
* </blockquote>
@@ -266,7 +184,7 @@
* <tr>
* <td> {@link CompilationMXBean} </td>
* <td> {@link #COMPILATION_MXBEAN_NAME
- * <tt>java.lang:type=Compilation</tt>}</td>
+ * java.lang:type=Compilation}</td>
* </tr>
* </table>
* </blockquote>
@@ -283,17 +201,21 @@
* <tr>
* <td> {@link GarbageCollectorMXBean} </td>
* <td> {@link #GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE
- * <tt>java.lang:type=GarbageCollector</tt>}<tt>,name=</tt><i>collector's name</i></td>
+ * java.lang:type=GarbageCollector}<tt>,name=</tt><i>collector's name</i></td>
* </tr>
* <tr>
* <td> {@link MemoryManagerMXBean} </td>
* <td> {@link #MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE
- * <tt>java.lang:type=MemoryManager</tt>}<tt>,name=</tt><i>manager's name</i></td>
+ * java.lang:type=MemoryManager}<tt>,name=</tt><i>manager's name</i></td>
* </tr>
* <tr>
* <td> {@link MemoryPoolMXBean} </td>
* <td> {@link #MEMORY_POOL_MXBEAN_DOMAIN_TYPE
- * <tt>java.lang:type=MemoryPool</tt>}<tt>,name=</tt><i>pool's name</i></td>
+ * java.lang:type=MemoryPool}<tt>,name=</tt><i>pool's name</i></td>
+ * </tr>
+ * <tr>
+ * <td> {@link BufferPoolMXBean} </td>
+ * <td> {@code java.nio:type=BufferPool,name=}<i>pool name</i></td>
* </tr>
* </table>
* </blockquote>
@@ -302,7 +224,6 @@
* JMX Specification</a>
* @see <a href="package-summary.html#examples">
* Ways to Access Management Metrics</a>
- * @see java.util.logging.LoggingMXBean
* @see javax.management.MXBean
*
* @author Mandy Chung
@@ -496,35 +417,35 @@
/**
* Returns the platform {@link javax.management.MBeanServer MBeanServer}.
* On the first call to this method, it first creates the platform
- * <tt>MBeanServer</tt> by calling the
+ * {@code MBeanServer} by calling the
* {@link javax.management.MBeanServerFactory#createMBeanServer
* MBeanServerFactory.createMBeanServer}
- * method and registers the platform MXBeans in this platform
- * <tt>MBeanServer</tt> using the <a href="#MXBeanNames">MXBean names</a>
- * defined in the class description.
+ * method and registers each platform MXBean in this platform
+ * {@code MBeanServer} with its
+ * {@link PlatformManagedObject#getObjectName ObjectName}.
* This method, in subsequent calls, will simply return the
- * initially created platform <tt>MBeanServer</tt>.
+ * initially created platform {@code MBeanServer}.
* <p>
* MXBeans that get created and destroyed dynamically, for example,
* memory {@link MemoryPoolMXBean pools} and
* {@link MemoryManagerMXBean managers},
* will automatically be registered and deregistered into the platform
- * <tt>MBeanServer</tt>.
+ * {@code MBeanServer}.
* <p>
- * If the system property <tt>javax.management.builder.initial</tt>
- * is set, the platform <tt>MBeanServer</tt> creation will be done
+ * If the system property {@code javax.management.builder.initial}
+ * is set, the platform {@code MBeanServer} creation will be done
* by the specified {@link javax.management.MBeanServerBuilder}.
* <p>
* It is recommended that this platform MBeanServer also be used
* to register other application managed beans
* besides the platform MXBeans.
* This will allow all MBeans to be published through the same
- * <tt>MBeanServer</tt> and hence allow for easier network publishing
+ * {@code MBeanServer} and hence allow for easier network publishing
* and discovery.
* Name conflicts with the platform MXBeans should be avoided.
*
- * @return the platform <tt>MBeanServer</tt>; the platform
- * MXBeans are registered into the platform <tt>MBeanServer</tt>
+ * @return the platform {@code MBeanServer}; the platform
+ * MXBeans are registered into the platform {@code MBeanServer}
* at the first time this method is called.
*
* @exception SecurityException if there is a security manager
@@ -671,7 +592,9 @@
try {
final ObjectName objName = new ObjectName(mxbeanName);
- if (!connection.isInstanceOf(objName, interfaceClass.getName())) {
+ // skip the isInstanceOf check for LoggingMXBean
+ String intfName = interfaceClass.getName();
+ if (!connection.isInstanceOf(objName, intfName)) {
throw new IllegalArgumentException(mxbeanName +
" is not an instance of " + interfaceClass);
}
@@ -683,55 +606,128 @@
// create an MXBean proxy
return JMX.newMXBeanProxy(connection, objName, mxbeanInterface,
emitter);
- } catch (InstanceNotFoundException e) {
- final IllegalArgumentException iae =
- new IllegalArgumentException(mxbeanName +
- " not found in the connection.");
- iae.initCause(e);
- throw iae;
- } catch (MalformedObjectNameException e) {
- final IllegalArgumentException iae =
- new IllegalArgumentException(mxbeanName +
- " is not a valid ObjectName format.");
- iae.initCause(e);
- throw iae;
+ } catch (InstanceNotFoundException|MalformedObjectNameException e) {
+ throw new IllegalArgumentException(e);
}
}
/**
- * Returns the list of platform MXBeans that implement
- * the given {@code mxbeanInterface} in the running Java
+ * Returns the platform MXBean implementing
+ * the given {@code mxbeanInterface} which is specified
+ * to have one single instance in the Java virtual machine.
+ * This method may return {@code null} if the management interface
+ * is not implemented in the Java virtual machine (for example,
+ * a Java virtual machine with no compilation system does not
+ * implement {@link CompilationMXBean});
+ * otherwise, this method is equivalent to calling:
+ * <pre>
+ * {@link #getPlatformMXBeans(Class)
+ * getPlatformMXBeans(mxbeanInterface)}.get(0);
+ * </pre>
+ *
+ * @param mxbeanInterface a management interface for a platform
+ * MXBean with one single instance in the Java virtual machine
+ * if implemented.
+ *
+ * @return the platform MXBean that implements
+ * {@code mxbeanInterface}, or {@code null} if not exist.
+ *
+ * @throws IllegalArgumentException if {@code mxbeanInterface}
+ * is not a platform management interface or
+ * not a singleton platform MXBean.
+ *
+ * @since 1.7
+ */
+ public static <T extends PlatformManagedObject>
+ T getPlatformMXBean(Class<T> mxbeanInterface) {
+ PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface);
+ if (pc == null)
+ throw new IllegalArgumentException(mxbeanInterface.getName() +
+ " is not a platform management interface");
+ if (!pc.isSingleton())
+ throw new IllegalArgumentException(mxbeanInterface.getName() +
+ " can have zero or more than one instances");
+
+ return pc.getSingletonMXBean(mxbeanInterface);
+ }
+
+ /**
+ * Returns the list of platform MXBeans implementing
+ * the given {@code mxbeanInterface} in the Java
* virtual machine.
* The returned list may contain zero, one, or more instances.
* The number of instances in the returned list is defined
* in the specification of the given management interface.
+ * The order is undefined and there is no guarantee that
+ * the list returned is in the same order as previous invocations.
*
* @param mxbeanInterface a management interface for a platform
* MXBean
*
- * @return the list of platform MXBeans that implements
+ * @return the list of platform MXBeans that implement
* {@code mxbeanInterface}.
*
* @throws IllegalArgumentException if {@code mxbeanInterface}
- * is not a management interface for the platform.
+ * is not a platform management interface.
*
* @since 1.7
*/
public static <T extends PlatformManagedObject> List<T>
getPlatformMXBeans(Class<T> mxbeanInterface) {
- String className = mxbeanInterface.getName();
- for (PlatformComponent component: PlatformComponent.values()) {
- // comparing the class name first instead of the Class instance
- // to avoid causing unnecessary class loading of
- // the other MXBean interfaces
- if (className.equals(component.getMXBeanInterfaceName())) {
- if (component.getMXBeanInterface() == mxbeanInterface) {
- return component.getMXBeans(mxbeanInterface);
- }
- }
- }
- throw new IllegalArgumentException(mxbeanInterface.getName() +
- " is not implemented by any of the platform MXBeans.");
+ PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface);
+ if (pc == null)
+ throw new IllegalArgumentException(mxbeanInterface.getName() +
+ " is not a platform management interface");
+ return Collections.unmodifiableList(pc.getMXBeans(mxbeanInterface));
+ }
+
+ /**
+ * Returns the platform MXBean proxy for
+ * {@code mxbeanInterface} which is specified to have one single
+ * instance in a Java virtual machine and the proxy will
+ * forward the method calls through the given {@code MBeanServerConnection}.
+ * This method may return {@code null} if the management interface
+ * is not implemented in the Java virtual machine being monitored
+ * (for example, a Java virtual machine with no compilation system
+ * does not implement {@link CompilationMXBean});
+ * otherwise, this method is equivalent to calling:
+ * <pre>
+ * {@link #getPlatformMXBeans(MBeanServerConnection, Class)
+ * getPlatformMXBeans(connection, mxbeanInterface)}.get(0);
+ * </pre>
+ *
+ * @param connection the {@code MBeanServerConnection} to forward to.
+ * @param mxbeanInterface a management interface for a platform
+ * MXBean with one single instance in the Java virtual machine
+ * being monitored, if implemented.
+ *
+ * @return the platform MXBean proxy for
+ * forwarding the method calls of the {@code mxbeanInterface}
+ * through the given {@code MBeanServerConnection},
+ * or {@code null} if not exist.
+ *
+ * @throws IllegalArgumentException if {@code mxbeanInterface}
+ * is not a platform management interface or
+ * not a singleton platform MXBean.
+ * @throws java.io.IOException if a communication problem
+ * occurred when accessing the {@code MBeanServerConnection}.
+ *
+ * @see #newPlatformMXBeanProxy
+ * @since 1.7
+ */
+ public static <T extends PlatformManagedObject>
+ T getPlatformMXBean(MBeanServerConnection connection,
+ Class<T> mxbeanInterface)
+ throws java.io.IOException
+ {
+ PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface);
+ if (pc == null)
+ throw new IllegalArgumentException(mxbeanInterface.getName() +
+ " is not a platform management interface");
+ if (!pc.isSingleton())
+ throw new IllegalArgumentException(mxbeanInterface.getName() +
+ " can have zero or more than one instances");
+ return pc.getSingletonMXBean(connection, mxbeanInterface);
}
/**
@@ -741,6 +737,8 @@
* The returned list may contain zero, one, or more instances.
* The number of instances in the returned list is defined
* in the specification of the given management interface.
+ * The order is undefined and there is no guarantee that
+ * the list returned is in the same order as previous invocations.
*
* @param connection the {@code MBeanServerConnection} to forward to.
* @param mxbeanInterface a management interface for a platform
@@ -751,54 +749,49 @@
* through the given {@code MBeanServerConnection}.
*
* @throws IllegalArgumentException if {@code mxbeanInterface}
- * is not a management interface for the platform.
+ * is not a platform management interface.
*
* @throws java.io.IOException if a communication problem
* occurred when accessing the {@code MBeanServerConnection}.
*
+ * @see #newPlatformMXBeanProxy
* @since 1.7
*/
public static <T extends PlatformManagedObject>
- List<T> getPlatformMXBeans(MBeanServerConnection connection,
- Class<T> mxbeanInterface)
+ List<T> getPlatformMXBeans(MBeanServerConnection connection,
+ Class<T> mxbeanInterface)
throws java.io.IOException
{
- String className = mxbeanInterface.getName();
- for (PlatformComponent component: PlatformComponent.values()) {
- // comparing the class name first instead of the Class instance
- // to avoid causing unnecessary class loading of
- // the other MXBean interfaces
- if (className.equals(component.getMXBeanInterfaceName())) {
- if (component.getMXBeanInterface() == mxbeanInterface) {
- return component.getMXBeans(connection,
- mxbeanInterface);
- }
- }
+ PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface);
+ if (pc == null) {
+ throw new IllegalArgumentException(mxbeanInterface.getName() +
+ " is not a platform management interface");
}
- throw new IllegalArgumentException(mxbeanInterface.getName() +
- " is not implemented by any of the platform MXBeans.");
+ return Collections.unmodifiableList(pc.getMXBeans(connection, mxbeanInterface));
}
/**
- * Returns a list of {@code Class} objects, subinterface of
+ * Returns the set of {@code Class} objects, subinterface of
* {@link PlatformManagedObject}, representing
* all management interfaces for
* monitoring and managing the Java platform.
*
- * @return a list of {@code Class} objects, subinterface of
+ * @return the set of {@code Class} objects, subinterface of
* {@link PlatformManagedObject} representing
* the management interfaces for
* monitoring and managing the Java platform.
*
* @since 1.7
*/
- public static List<Class<? extends PlatformManagedObject>> getAllPlatformMXBeanInterfaces() {
- List<Class<? extends PlatformManagedObject>> result =
- new ArrayList<>();
+ public static Set<Class<? extends PlatformManagedObject>>
+ getPlatformManagementInterfaces()
+ {
+ Set<Class<? extends PlatformManagedObject>> result =
+ new TreeSet<>();
for (PlatformComponent component: PlatformComponent.values()) {
result.add(component.getMXBeanInterface());
}
- return result;
+ return Collections.unmodifiableSet(result);
}
private static final String NOTIF_EMITTER =
@@ -810,7 +803,9 @@
private static void addMXBean(final MBeanServer mbs, final PlatformManagedObject pmo) {
// Make DynamicMBean out of MXBean by wrapping it with a StandardMBean
final DynamicMBean dmbean;
- if (pmo instanceof NotificationEmitter) {
+ if (pmo instanceof DynamicMBean) {
+ dmbean = DynamicMBean.class.cast(pmo);
+ } else if (pmo instanceof NotificationEmitter) {
dmbean = new StandardEmitterMBean(pmo, null, true, (NotificationEmitter) pmo);
} else {
dmbean = new StandardMBean(pmo, null, true);
--- a/jdk/src/share/classes/java/lang/management/PlatformComponent.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/lang/management/PlatformComponent.java Sun Apr 10 10:23:28 2011 -0700
@@ -29,9 +29,9 @@
import java.util.Collections;
import java.util.List;
import java.util.HashSet;
+import java.util.HashMap;
+import java.util.Map;
import java.util.Set;
-import java.util.logging.PlatformLoggingMXBean;
-import java.nio.BufferPoolMXBean;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
@@ -66,6 +66,7 @@
CLASS_LOADING(
"java.lang.management.ClassLoadingMXBean",
"java.lang", "ClassLoading", defaultKeyProperties(),
+ true, // singleton
new MXBeanFetcher<ClassLoadingMXBean>() {
public List<ClassLoadingMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getClassLoadingMXBean());
@@ -78,6 +79,7 @@
COMPILATION(
"java.lang.management.CompilationMXBean",
"java.lang", "Compilation", defaultKeyProperties(),
+ true, // singleton
new MXBeanFetcher<CompilationMXBean>() {
public List<CompilationMXBean> getMXBeans() {
CompilationMXBean m = ManagementFactoryHelper.getCompilationMXBean();
@@ -95,6 +97,7 @@
MEMORY(
"java.lang.management.MemoryMXBean",
"java.lang", "Memory", defaultKeyProperties(),
+ true, // singleton
new MXBeanFetcher<MemoryMXBean>() {
public List<MemoryMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getMemoryMXBean());
@@ -107,6 +110,7 @@
GARBAGE_COLLECTOR(
"java.lang.management.GarbageCollectorMXBean",
"java.lang", "GarbageCollector", keyProperties("name"),
+ false, // zero or more instances
new MXBeanFetcher<GarbageCollectorMXBean>() {
public List<GarbageCollectorMXBean> getMXBeans() {
return ManagementFactoryHelper.
@@ -120,6 +124,7 @@
MEMORY_MANAGER(
"java.lang.management.MemoryManagerMXBean",
"java.lang", "MemoryManager", keyProperties("name"),
+ false, // zero or more instances
new MXBeanFetcher<MemoryManagerMXBean>() {
public List<MemoryManagerMXBean> getMXBeans() {
return ManagementFactoryHelper.getMemoryManagerMXBeans();
@@ -133,6 +138,7 @@
MEMORY_POOL(
"java.lang.management.MemoryPoolMXBean",
"java.lang", "MemoryPool", keyProperties("name"),
+ false, // zero or more instances
new MXBeanFetcher<MemoryPoolMXBean>() {
public List<MemoryPoolMXBean> getMXBeans() {
return ManagementFactoryHelper.getMemoryPoolMXBeans();
@@ -145,6 +151,7 @@
OPERATING_SYSTEM(
"java.lang.management.OperatingSystemMXBean",
"java.lang", "OperatingSystem", defaultKeyProperties(),
+ true, // singleton
new MXBeanFetcher<OperatingSystemMXBean>() {
public List<OperatingSystemMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getOperatingSystemMXBean());
@@ -157,6 +164,7 @@
RUNTIME(
"java.lang.management.RuntimeMXBean",
"java.lang", "Runtime", defaultKeyProperties(),
+ true, // singleton
new MXBeanFetcher<RuntimeMXBean>() {
public List<RuntimeMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getRuntimeMXBean());
@@ -169,6 +177,7 @@
THREADING(
"java.lang.management.ThreadMXBean",
"java.lang", "Threading", defaultKeyProperties(),
+ true, // singleton
new MXBeanFetcher<ThreadMXBean>() {
public List<ThreadMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getThreadMXBean());
@@ -180,11 +189,17 @@
* Logging facility.
*/
LOGGING(
- "java.util.logging.PlatformLoggingMXBean",
+ "java.lang.management.PlatformLoggingMXBean",
"java.util.logging", "Logging", defaultKeyProperties(),
+ true, // singleton
new MXBeanFetcher<PlatformLoggingMXBean>() {
public List<PlatformLoggingMXBean> getMXBeans() {
- return ManagementFactoryHelper.getLoggingMXBean();
+ PlatformLoggingMXBean m = ManagementFactoryHelper.getPlatformLoggingMXBean();
+ if (m == null) {
+ return Collections.emptyList();
+ } else {
+ return Collections.singletonList(m);
+ }
}
}),
@@ -192,8 +207,9 @@
* Buffer pools.
*/
BUFFER_POOL(
- "java.nio.BufferPoolMXBean",
+ "java.lang.management.BufferPoolMXBean",
"java.nio", "BufferPool", keyProperties("name"),
+ false, // zero or more instances
new MXBeanFetcher<BufferPoolMXBean>() {
public List<BufferPoolMXBean> getMXBeans() {
return ManagementFactoryHelper.getBufferPoolMXBeans();
@@ -209,6 +225,7 @@
SUN_GARBAGE_COLLECTOR(
"com.sun.management.GarbageCollectorMXBean",
"java.lang", "GarbageCollector", keyProperties("name"),
+ false, // zero or more instances
new MXBeanFetcher<com.sun.management.GarbageCollectorMXBean>() {
public List<com.sun.management.GarbageCollectorMXBean> getMXBeans() {
return getGcMXBeanList(com.sun.management.GarbageCollectorMXBean.class);
@@ -222,6 +239,7 @@
SUN_OPERATING_SYSTEM(
"com.sun.management.OperatingSystemMXBean",
"java.lang", "OperatingSystem", defaultKeyProperties(),
+ true, // singleton
new MXBeanFetcher<com.sun.management.OperatingSystemMXBean>() {
public List<com.sun.management.OperatingSystemMXBean> getMXBeans() {
return getOSMXBeanList(com.sun.management.OperatingSystemMXBean.class);
@@ -234,6 +252,7 @@
SUN_UNIX_OPERATING_SYSTEM(
"com.sun.management.UnixOperatingSystemMXBean",
"java.lang", "OperatingSystem", defaultKeyProperties(),
+ true, // singleton
new MXBeanFetcher<UnixOperatingSystemMXBean>() {
public List<UnixOperatingSystemMXBean> getMXBeans() {
return getOSMXBeanList(com.sun.management.UnixOperatingSystemMXBean.class);
@@ -246,6 +265,7 @@
HOTSPOT_DIAGNOSTIC(
"com.sun.management.HotSpotDiagnosticMXBean",
"com.sun.management", "HotSpotDiagnostic", defaultKeyProperties(),
+ true, // singleton
new MXBeanFetcher<HotSpotDiagnosticMXBean>() {
public List<HotSpotDiagnosticMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getDiagnosticMXBean());
@@ -296,27 +316,19 @@
private final Set<String> keyProperties;
private final MXBeanFetcher fetcher;
private final PlatformComponent[] subComponents;
+ private final boolean singleton;
private PlatformComponent(String intfName,
String domain, String type,
Set<String> keyProperties,
- MXBeanFetcher fetcher) {
- this.mxbeanInterfaceName = intfName;
- this.domain = domain;
- this.type = type;
- this.keyProperties = keyProperties;
- this.fetcher = fetcher;
- this.subComponents = new PlatformComponent[0];
- }
- private PlatformComponent(String intfName,
- String domain, String type,
- Set<String> keyProperties,
+ boolean singleton,
MXBeanFetcher fetcher,
PlatformComponent... subComponents) {
this.mxbeanInterfaceName = intfName;
this.domain = domain;
this.type = type;
this.keyProperties = keyProperties;
+ this.singleton = singleton;
this.fetcher = fetcher;
this.subComponents = subComponents;
}
@@ -338,6 +350,10 @@
return set;
}
+ boolean isSingleton() {
+ return singleton;
+ }
+
String getMXBeanInterfaceName() {
return mxbeanInterfaceName;
}
@@ -360,8 +376,35 @@
return fetcher.getMXBeans();
}
+ <T extends PlatformManagedObject> T getSingletonMXBean(Class<T> mxbeanInterface)
+ {
+ if (!singleton)
+ throw new IllegalArgumentException(mxbeanInterfaceName +
+ " can have zero or more than one instances");
+
+ List<T> list = fetcher.getMXBeans();
+ assert list.size() == 1;
+ return list.isEmpty() ? null : list.get(0);
+ }
+
<T extends PlatformManagedObject>
- List<T> getMXBeans(MBeanServerConnection mbs, Class<T> mxbeanInterface)
+ T getSingletonMXBean(MBeanServerConnection mbs, Class<T> mxbeanInterface)
+ throws java.io.IOException
+ {
+ if (!singleton)
+ throw new IllegalArgumentException(mxbeanInterfaceName +
+ " can have zero or more than one instances");
+
+ // ObjectName of a singleton MXBean contains only domain and type
+ assert keyProperties.size() == 1;
+ String on = domain + ":type=" + type;
+ return ManagementFactory.newPlatformMXBeanProxy(mbs,
+ on,
+ mxbeanInterface);
+ }
+
+ <T extends PlatformManagedObject>
+ List<T> getMXBeans(MBeanServerConnection mbs, Class<T> mxbeanInterface)
throws java.io.IOException
{
List<T> result = new ArrayList<>();
@@ -391,5 +434,34 @@
return set;
}
+ // a map from MXBean interface name to PlatformComponent
+ private static Map<String, PlatformComponent> enumMap;
+ private static synchronized void ensureInitialized() {
+ if (enumMap == null) {
+ enumMap = new HashMap<>();
+ for (PlatformComponent pc: PlatformComponent.values()) {
+ // Use String as the key rather than Class<?> to avoid
+ // causing unnecessary class loading of management interface
+ enumMap.put(pc.getMXBeanInterfaceName(), pc);
+ }
+ }
+ }
+
+ static boolean isPlatformMXBean(String cn) {
+ ensureInitialized();
+ return enumMap.containsKey(cn);
+ }
+
+ static <T extends PlatformManagedObject>
+ PlatformComponent getPlatformComponent(Class<T> mxbeanInterface)
+ {
+ ensureInitialized();
+ String cn = mxbeanInterface.getName();
+ PlatformComponent pc = enumMap.get(cn);
+ if (pc != null && pc.getMXBeanInterface() == mxbeanInterface)
+ return pc;
+ return null;
+ }
+
private static final long serialVersionUID = 6992337162326171013L;
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/java/lang/management/PlatformLoggingMXBean.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute 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.lang.management;
+
+/**
+ * The management interface for the {@linkplain java.util.logging logging} facility.
+ *
+ * <p>There is a single global instance of the <tt>PlatformLoggingMXBean</tt>.
+ * The {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class)
+ * ManagementFactory.getPlatformMXBean} method can be used to obtain
+ * the {@code PlatformLoggingMXBean} object as follows:
+ * <pre>
+ * PlatformLoggingMXBean logging = ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class);
+ * </pre>
+ * The {@code PlatformLoggingMXBean} object is also registered with the
+ * platform {@linkplain java.lang.management.ManagementFactory#getPlatformMBeanServer
+ * MBeanServer}.
+ * The {@link javax.management.ObjectName ObjectName} for uniquely
+ * identifying the {@code PlatformLoggingMXBean} within an MBeanServer is:
+ * <pre>
+ * {@link java.util.logging.LogManager#LOGGING_MXBEAN_NAME java.util.logging:type=Logging}
+ * </pre>
+ *
+ * <p>The instance registered in the platform <tt>MBeanServer</tt> with
+ * this {@code ObjectName} implements all attributes defined by
+ * {@link java.util.logging.LoggingMXBean}.
+ *
+ * @since 1.7
+ */
+public interface PlatformLoggingMXBean extends PlatformManagedObject {
+
+ /**
+ * Returns the list of the currently registered
+ * {@linkplain java.util.logging.Logger logger} names. This method
+ * calls {@link java.util.logging.LogManager#getLoggerNames} and
+ * returns a list of the logger names.
+ *
+ * @return A list of {@code String} each of which is a
+ * currently registered {@code Logger} name.
+ */
+ java.util.List<String> getLoggerNames();
+
+ /**
+ * Gets the name of the log {@linkplain java.util.logging.Logger#getLevel
+ * level} associated with the specified logger.
+ * If the specified logger does not exist, {@code null}
+ * is returned.
+ * This method first finds the logger of the given name and
+ * then returns the name of the log level by calling:
+ * <blockquote>
+ * {@link java.util.logging.Logger#getLevel
+ * Logger.getLevel()}.{@link java.util.logging.Level#getName getName()};
+ * </blockquote>
+ *
+ * <p>
+ * If the {@code Level} of the specified logger is {@code null},
+ * which means that this logger's effective level is inherited
+ * from its parent, an empty string will be returned.
+ *
+ * @param loggerName The name of the {@code Logger} to be retrieved.
+ *
+ * @return The name of the log level of the specified logger; or
+ * an empty string if the log level of the specified logger
+ * is {@code null}. If the specified logger does not
+ * exist, {@code null} is returned.
+ *
+ * @see java.util.logging.Logger#getLevel
+ */
+ String getLoggerLevel(String loggerName);
+
+ /**
+ * Sets the specified logger to the specified new
+ * {@linkplain java.util.logging.Logger#setLevel level}.
+ * If the {@code levelName} is not {@code null}, the level
+ * of the specified logger is set to the parsed
+ * {@link java.util.logging.Level Level}
+ * matching the {@code levelName}.
+ * If the {@code levelName} is {@code null}, the level
+ * of the specified logger is set to {@code null} and
+ * the effective level of the logger is inherited from
+ * its nearest ancestor with a specific (non-null) level value.
+ *
+ * @param loggerName The name of the {@code Logger} to be set.
+ * Must be non-null.
+ * @param levelName The name of the level to set on the specified logger,
+ * or {@code null} if setting the level to inherit
+ * from its nearest ancestor.
+ *
+ * @throws IllegalArgumentException if the specified logger
+ * does not exist, or {@code levelName} is not a valid level name.
+ *
+ * @throws SecurityException if a security manager exists and if
+ * the caller does not have LoggingPermission("control").
+ *
+ * @see java.util.logging.Logger#setLevel
+ */
+ void setLoggerLevel(String loggerName, String levelName);
+
+ /**
+ * Returns the name of the
+ * {@linkplain java.util.logging.Logger#getParent parent}
+ * for the specified logger.
+ * If the specified logger does not exist, {@code null} is returned.
+ * If the specified logger is the root {@code Logger} in the namespace,
+ * the result will be an empty string.
+ *
+ * @param loggerName The name of a {@code Logger}.
+ *
+ * @return the name of the nearest existing parent logger;
+ * an empty string if the specified logger is the root logger.
+ * If the specified logger does not exist, {@code null}
+ * is returned.
+ */
+ String getParentLoggerName(String loggerName);
+}
--- a/jdk/src/share/classes/java/lang/management/PlatformManagedObject.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/lang/management/PlatformManagedObject.java Sun Apr 10 10:23:28 2011 -0700
@@ -46,7 +46,7 @@
* intended for the management interfaces for the platform to extend but
* not for applications.
*
- * @see <a href="ManagementFactory.html#MXBean">Platform MXBeans</a>
+ * @see ManagementFactory
* @since 1.7
*/
public interface PlatformManagedObject {
--- a/jdk/src/share/classes/java/lang/management/package.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/lang/management/package.html Sun Apr 10 10:23:28 2011 -0700
@@ -27,160 +27,124 @@
<html>
<body bgcolor="white">
-Provides the management interface for monitoring and management of the
-Java virtual machine as well as the operating system on which the
-Java virtual machine is running. It allows both local and remote
-monitoring and management of the running Java virtual machine.
-
-<h4>Platform MXBeans</h4>
-
-This package defines the management interface of the following
-components:
+Provides the management interfaces for monitoring and management of the
+Java virtual machine and other components in the Java runtime.
+It allows both local and remote
+monitoring and management of the running Java virtual machine.
+<p>
-<blockquote>
-<table cellspacing=1 summary="Description of the MBeans">
-<tr>
-<th><p align="left">Management Interface</p></th>
-<th><p align="left">Description</p></th>
-</tr>
-<tr>
-<td> <tt>{@link java.lang.management.ClassLoadingMXBean}</tt> </td>
-<td> Class loading system of the Java virtual machine.</td>
-</tr>
-<tr>
-<td> <tt>{@link java.lang.management.CompilationMXBean}</tt> </td>
-<td> Compilation system of the Java virtual machine.</td>
-</tr>
-<tr>
-<td> <tt>{@link java.lang.management.MemoryMXBean}</tt> </td>
-<td> Memory system of the Java virtual machine.</td>
-</tr>
-<tr>
-<td> <tt>{@link java.lang.management.ThreadMXBean}</tt> </td>
-<td> Threads system of the Java virtual machine.</td>
-</tr>
-<tr>
-<td> <tt>{@link java.lang.management.RuntimeMXBean}</tt> </td>
-<td> Runtime system of the Java virtual machine.</td>
-</tr>
-<tr>
-<td> <tt>{@link java.lang.management.OperatingSystemMXBean}</tt> </td>
-<td> Operating system on which the Java virtual machine is running.</td>
-</tr>
-<tr>
-<td> <tt>{@link java.lang.management.GarbageCollectorMXBean}</tt> </td>
-<td> Garbage collector in the Java virtual machine.</td>
-</tr>
-<tr>
-<td> <tt>{@link java.lang.management.MemoryManagerMXBean}</tt> </td>
-<td> Memory manager in the Java virtual machine.</td>
-</tr>
-<tr>
-<td> <tt>{@link java.lang.management.MemoryPoolMXBean}</tt> </td>
-<td> Memory pool in the Java virtual machine.</td>
-</tr>
-</table>
-</blockquote>
-
+<h4><a name="MXBean">Platform MXBean</a></h4>
<p>
-A platform MXBean is a <i>managed bean</i> that defines the management
-interface for one component for the platform and is specified in the
-<a href="ManagementFactory.html#MXBean">
-ManagementFactory</a> class.
-
-<p>An application can monitor the instrumentation of the
-Java virtual machine and manage certain characteristics in
-the following ways:
-<ul>
-<li><i>Direct access to an MXBean interface</i>
- <ol type="a">
- <li>Get the MXBean instance through the static factory method
- and access the MXBean interface locally of the running
- virtual machine.</li>
- <li>Construct an MXBean proxy instance that
- forwards the method calls to a given
- {@link javax.management.MBeanServer MBeanServer}
- by calling
- {@link java.lang.management.ManagementFactory#newPlatformMXBeanProxy
- ManagementFactory.newPlatformMXBeanProxy}.
- A proxy is typically constructed to remotely access
- an MXBean of another running virtual machine.</li>
- </ol></li>
-<li><i>Indirect access via {@link javax.management.MBeanServer MBeanServer}
- interface</i>
- <ol type="a">
- <li>Go through the
- {@link java.lang.management.ManagementFactory#getPlatformMBeanServer
- platform MBeanServer} to access MXBeans locally or
- a specific <tt>MBeanServerConnection</tt> to access
- MXBeans remotely.
- The attributes and operations of an MXBean use only
- <em>JMX open types</em> which include basic data types,
- {@link javax.management.openmbean.CompositeData CompositeData},
- and {@link javax.management.openmbean.TabularData TabularData}
- defined in {@link javax.management.openmbean.OpenType OpenType}.
- </li>
- </ol></li>
-</ul>
-
-Below shows a few <a href="#examples">examples</a> of different
-ways to access MXBeans.
-
+A platform MXBean is a <i>managed bean</i> that
+conforms to the <a href="../../../javax/management/package-summary.html">JMX</a>
+Instrumentation Specification and only uses a set of basic data types.
+Each platform MXBean is a {@link java.lang.management.PlatformManagedObject}
+with a unique
+{@linkplain java.lang.management.PlatformManagedObject#getObjectName name}.
+<p>
<h4>ManagementFactory</h4>
-The {@link java.lang.management.ManagementFactory} class is the management
-factory class for the Java platform. This class provides a set of
+<p>The {@link java.lang.management.ManagementFactory} class is the management
+factory class for the Java platform. This class provides a set of
static factory methods to obtain the MXBeans for the Java platform
to allow an application to access the MXBeans directly.
<p>A <em>platform MBeanServer</em> can be accessed with the
{@link java.lang.management.ManagementFactory#getPlatformMBeanServer
getPlatformMBeanServer} method. On the first call to this method,
-it creates the platform MBeanServer and registers all platform MXBeans
-including platform MXBeans defined in other packages such as
-{@link java.util.logging.LoggingMXBean}.
-Each platform MXBean is registered with a unique name defined in the
-{@link java.lang.management.ManagementFactory ManagementFactory} class
-for constructing {@link javax.management.ObjectName ObjectName}.
-This is a single MBeanServer that can be shared by different managed
+it creates the platform MBeanServer and registers all platform MXBeans
+including {@linkplain java.lang.management.PlatformManagedObject
+platform MXBeans}.
+Each platform MXBean is registered with a unique name defined in
+the specification of the management interface.
+This is a single MBeanServer that can be shared by different managed
components running within the same Java virtual machine.
-
+
<h4>Interoperability</h4>
-A management application and a platform MBeanServer of a running
-virtual machine can interoperate
+<p>A management application and a platform MBeanServer of a running
+virtual machine can interoperate
without requiring classes used by the platform MXBean interfaces.
The data types being transmitted between the JMX connector
server and the connector client are JMX
-{@link javax.management.openmbean.OpenType open types} and
+{@linkplain javax.management.openmbean.OpenType open types} and
this allows interoperation across versions.
-
-<p>A data type used by the MXBean interfaces are mapped to
-an open type when being accessed via MBeanServer interface.
-The data type mapping is specified in the
-{@link java.lang.management.ManagementFactory ManagementFactory} class.
+A data type used by the MXBean interfaces are mapped to an
+open type when being accessed via MBeanServer interface.
+See the <a href="../../../javax/management/MXBean.html#MXBean-spec">
+MXBean</a> specification for details.
<h4><a name="examples">Ways to Access MXBeans</a></h4>
-There are three different ways to access the management interfaces.
-
+<p>An application can monitor the instrumentation of the
+Java virtual machine and the runtime in the following ways:
<p>
-<ol>
-<li>Call the methods in the MXBean directly within the same
- Java virtual machine.
-<blockquote><pre>
+<b>1. Direct access to an MXBean interface</b>
+<p>
+<ul>
+<li>Get an MXBean instance locally in the running Java virtual machine:<p>
+<pre>
RuntimeMXBean mxbean = ManagementFactory.getRuntimeMXBean();
// Get the standard attribute "VmVendor"
String vendor = mxbean.getVmVendor();
-
</pre>
-</blockquote>
+<p>Or by calling the
+ {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class)
+ getPlatformMXBean} or
+ {@link java.lang.management.ManagementFactory#getPlatformMXBeans(Class)
+ getPlatformMXBeans} method:
+<pre>
+ RuntimeMXBean mxbean = ManagementFactory.getPlatformMXBean(RuntimeMXBean.class);
+
+ // Get the standard attribute "VmVendor"
+ String vendor = mxbean.getVmVendor();
+</pre>
+<p>
</li>
+<li>Construct an MXBean proxy instance that forwards the
+ method calls to a given MBeanServer:<p>
+<pre>
+ MBeanServerConnection mbs;
-<li>Go through a <tt>MBeanServerConnection</tt> connecting
- to the <tt>platform MBeanServer</tt> of a running virtual machine.</li>
-<blockquote><pre>
+ // Connect to a running JVM (or itself) and get MBeanServerConnection
+ // that has the JVM MBeans registered in it
+ ...
+
+ // Get a MBean proxy for RuntimeMXBean interface
+ RuntimeMXBean proxy =
+ {@link java.lang.management.ManagementFactory#getPlatformMXBean(MBeanServerConnection, Class)
+ ManagementFactory.getPlatformMXBean}(mbs,
+ RuntimeMXBean.class);
+ // Get standard attribute "VmVendor"
+ String vendor = proxy.getVmVendor();
+</pre>
+<p>A proxy is typically used to access an MXBean
+ in a remote Java virtual machine.
+ An alternative way to create an MXBean proxy is:
+<pre>
+ RuntimeMXBean proxy =
+ {@link java.lang.management.ManagementFactory#newPlatformMXBeanProxy
+ ManagementFactory.newPlatformMXBeanProxy}(mbs,
+ ManagementFactory.RUNTIME_MXBEAN_NAME,
+ RuntimeMXBean.class);
+</pre>
+</li>
+</ul>
+<p>
+<b>2. Indirect access to an MXBean interface via MBeanServer</b><p>
+<ul>
+<li>Go through the
+ {@link java.lang.management.ManagementFactory#getPlatformMBeanServer
+ platform MBeanServer} to access MXBeans locally or
+ a specific {@code MBeanServerConnection} to access
+ MXBeans remotely.
+ The attributes and operations of an MXBean use only
+ <em>JMX open types</em> which include basic data types,
+ {@link javax.management.openmbean.CompositeData CompositeData},
+ and {@link javax.management.openmbean.TabularData TabularData}
+ defined in {@link javax.management.openmbean.OpenType OpenType}.<p>
+<pre>
MBeanServerConnection mbs;
// Connect to a running JVM (or itself) and get MBeanServerConnection
@@ -190,7 +154,7 @@
try {
// Assuming the RuntimeMXBean has been registered in mbs
ObjectName oname = new ObjectName(ManagementFactory.RUNTIME_MXBEAN_NAME);
-
+
// Get standard attribute "VmVendor"
String vendor = (String) mbs.getAttribute(oname, "VmVendor");
} catch (....) {
@@ -198,36 +162,19 @@
// and MBeanServer.getAttribute method
...
}
-
-</pre></blockquote>
-
-<li>Use MXBean proxy.</li>
-<blockquote><pre>
- MBeanServerConnection mbs;
-
- // Connect to a running JVM (or itself) and get MBeanServerConnection
- // that has the JVM MBeans registered in it
- ...
-
- // Get a MBean proxy for RuntimeMXBean interface
- RuntimeMXBean proxy =
- ManagementFactory.newPlatformMXBeanProxy(mbs,
- ManagementFactory.RUNTIME_MXBEAN_NAME,
- RuntimeMXBean.class);
- // Get standard attribute "VmVendor"
- String vendor = proxy.getVmVendor();
-</pre></blockquote>
-</ol>
+</pre>
+</li>
+</ul>
<h4><a name="extension">Platform Extension</a></h4>
-A Java virtual machine implementation may add its platform extension to
+<p>A Java virtual machine implementation may add its platform extension to
the management interface by defining platform-dependent
interfaces that extend the standard management interfaces to include
-platform-specific metrics and management operations.
+platform-specific metrics and management operations.
The static factory methods in the <tt>ManagementFactory</tt> class will
-return the MBeans with the platform extension.
+return the MXBeans with the platform extension.
<p>
It is recommended to name the platform-specific attributes with
@@ -240,26 +187,30 @@
the applications accessing that vendor-specific attribute would have
to be modified to cope with versioning and compatibility issues.
-<p>Below is an example showing how to access a platform-specific
-attribute from Sun's implementation of the <tt>RuntimeMXBean</tt>.
+<p>Below is an example showing how to access an attribute
+from the platform extension:
<p>
-1) Direct access to the Sun-specific MXBean interface
-<blockquote><pre>
- com.sun.management.RuntimeMXBean mxbean =
- (com.sun.management.RuntimeMXBean) ManagementFactory.getRuntimeMXBean();
+1) Direct access to the Oracle-specific MXBean interface
+<blockquote>
+<pre>
+ List<com.sun.management.GarbageCollectorMXBean> mxbeans =
+ ManagementFactory.getPlatformMXBeans(com.sun.management.GarbageCollectorMXBean.class);
- // Get the standard attribute "VmVendor"
- String vendor = mxbean.getVmVendor();
+ for (com.sun.management.GarbageCollectorMXBean gc : mxbeans) {
+ // Get the standard attribute "CollectionCount"
+ String count = mxbean.getCollectionCount();
- // Get the platform-specific attribute "Bar"
- BarType bar = mxbean.getBar();
-
+ // Get the platform-specific attribute "LastGcInfo"
+ GcInfo gcinfo = gc.getLastGcInfo();
+ ...
+ }
</pre>
</blockquote>
<p>
-2) Access the Sun-specific MXBean interface via <tt>MBeanServer</tt>
+2) Access the Oracle-specific MXBean interface via <tt>MBeanServer</tt>
+ through proxy
<blockquote><pre>
MBeanServerConnection mbs;
@@ -268,24 +219,17 @@
// that has the JVM MXBeans registered in it
...
- try {
- // Assuming the RuntimeMXBean has been registered in mbs
- ObjectName oname = new ObjectName(ManagementFactory.RUNTIME_MXBEAN_NAME);
-
- // Get standard attribute "VmVendor"
- String vendor = (String) mbs.getAttribute(oname, "VmVendor");
+ List<com.sun.management.GarbageCollectorMXBean> mxbeans =
+ ManagementFactory.getPlatformMXBeans(mbs, com.sun.management.GarbageCollectorMXBean.class);
- // Check if this MXBean contains Sun's extension
- if (mbs.isInstanceOf(oname, "com.sun.management.RuntimeMXBean")) {
- // Get platform-specific attribute "Bar"
- BarType bar = (String) mbs.getAttribute(oname, "Bar");
- }
- } catch (....) {
- // Catch the exceptions thrown by ObjectName constructor
- // and MBeanServer methods
+ for (com.sun.management.GarbageCollectorMXBean gc : mxbeans) {
+ // Get the standard attribute "CollectionCount"
+ String count = mxbean.getCollectionCount();
+
+ // Get the platform-specific attribute "LastGcInfo"
+ GcInfo gcinfo = gc.getLastGcInfo();
...
}
-
</pre></blockquote>
<p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
--- a/jdk/src/share/classes/java/lang/reflect/AccessibleObject.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/lang/reflect/AccessibleObject.java Sun Apr 10 10:23:28 2011 -0700
@@ -26,6 +26,7 @@
package java.lang.reflect;
import java.security.AccessController;
+import sun.reflect.Reflection;
import sun.reflect.ReflectionFactory;
import java.lang.annotation.Annotation;
@@ -201,4 +202,73 @@
public Annotation[] getDeclaredAnnotations() {
throw new AssertionError("All subclasses should override this method");
}
+
+
+ // Shared access checking logic.
+
+ // For non-public members or members in package-private classes,
+ // it is necessary to perform somewhat expensive security checks.
+ // If the security check succeeds for a given class, it will
+ // always succeed (it is not affected by the granting or revoking
+ // of permissions); we speed up the check in the common case by
+ // remembering the last Class for which the check succeeded.
+ //
+ // The simple security check for Constructor is to see if
+ // the caller has already been seen, verified, and cached.
+ // (See also Class.newInstance(), which uses a similar method.)
+ //
+ // A more complicated security check cache is needed for Method and Field
+ // The cache can be either null (empty cache), a 2-array of {caller,target},
+ // or a caller (with target implicitly equal to this.clazz).
+ // In the 2-array case, the target is always different from the clazz.
+ volatile Object securityCheckCache;
+
+ void checkAccess(Class<?> caller, Class<?> clazz, Object obj, int modifiers)
+ throws IllegalAccessException
+ {
+ if (caller == clazz) { // quick check
+ return; // ACCESS IS OK
+ }
+ Object cache = securityCheckCache; // read volatile
+ Class<?> targetClass = clazz;
+ if (obj != null
+ && Modifier.isProtected(modifiers)
+ && ((targetClass = obj.getClass()) != clazz)) {
+ // Must match a 2-list of { caller, targetClass }.
+ if (cache instanceof Class[]) {
+ Class<?>[] cache2 = (Class<?>[]) cache;
+ if (cache2[1] == targetClass &&
+ cache2[0] == caller) {
+ return; // ACCESS IS OK
+ }
+ // (Test cache[1] first since range check for [1]
+ // subsumes range check for [0].)
+ }
+ } else if (cache == caller) {
+ // Non-protected case (or obj.class == this.clazz).
+ return; // ACCESS IS OK
+ }
+
+ // If no return, fall through to the slow path.
+ slowCheckMemberAccess(caller, clazz, obj, modifiers, targetClass);
+ }
+
+ // Keep all this slow stuff out of line:
+ void slowCheckMemberAccess(Class<?> caller, Class<?> clazz, Object obj, int modifiers,
+ Class<?> targetClass)
+ throws IllegalAccessException
+ {
+ Reflection.ensureMemberAccess(caller, clazz, obj, modifiers);
+
+ // Success: Update the cache.
+ Object cache = ((targetClass == clazz)
+ ? caller
+ : new Class<?>[] { caller, targetClass });
+
+ // Note: The two cache elements are not volatile,
+ // but they are effectively final. The Java memory model
+ // guarantees that the initializing stores for the cache
+ // elements will occur before the volatile write.
+ securityCheckCache = cache; // write volatile
+ }
}
--- a/jdk/src/share/classes/java/lang/reflect/Constructor.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/lang/reflect/Constructor.java Sun Apr 10 10:23:28 2011 -0700
@@ -74,14 +74,6 @@
private byte[] annotations;
private byte[] parameterAnnotations;
- // For non-public members or members in package-private classes,
- // it is necessary to perform somewhat expensive security checks.
- // If the security check succeeds for a given class, it will
- // always succeed (it is not affected by the granting or revoking
- // of permissions); we speed up the check in the common case by
- // remembering the last Class for which the check succeeded.
- private volatile Class<?> securityCheckCache;
-
// Generics infrastructure
// Accessor for factory
private GenericsFactory getFactory() {
@@ -495,7 +487,7 @@
* this object represents
*
* @exception IllegalAccessException if this {@code Constructor} object
- * enforces Java language access control and the underlying
+ * is enforcing Java language access control and the underlying
* constructor is inaccessible.
* @exception IllegalArgumentException if the number of actual
* and formal parameters differ; if an unwrapping
@@ -518,16 +510,17 @@
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class<?> caller = Reflection.getCallerClass(2);
- if (securityCheckCache != caller) {
- Reflection.ensureMemberAccess(caller, clazz, null, modifiers);
- securityCheckCache = caller;
- }
+
+ checkAccess(caller, clazz, null, modifiers);
}
}
if ((clazz.getModifiers() & Modifier.ENUM) != 0)
throw new IllegalArgumentException("Cannot reflectively create enum objects");
- if (constructorAccessor == null) acquireConstructorAccessor();
- return (T) constructorAccessor.newInstance(initargs);
+ ConstructorAccessor ca = constructorAccessor; // read volatile
+ if (ca == null) {
+ ca = acquireConstructorAccessor();
+ }
+ return (T) ca.newInstance(initargs);
}
/**
@@ -560,18 +553,20 @@
// ConstructorAccessor for a given Constructor. However, avoiding
// synchronization will probably make the implementation more
// scalable.
- private void acquireConstructorAccessor() {
+ private ConstructorAccessor acquireConstructorAccessor() {
// First check to see if one has been created yet, and take it
// if so.
ConstructorAccessor tmp = null;
if (root != null) tmp = root.getConstructorAccessor();
if (tmp != null) {
constructorAccessor = tmp;
- return;
+ } else {
+ // Otherwise fabricate one and propagate it up to the root
+ tmp = reflectionFactory.newConstructorAccessor(this);
+ setConstructorAccessor(tmp);
}
- // Otherwise fabricate one and propagate it up to the root
- tmp = reflectionFactory.newConstructorAccessor(this);
- setConstructorAccessor(tmp);
+
+ return tmp;
}
// Returns ConstructorAccessor for this Constructor object, not
--- a/jdk/src/share/classes/java/lang/reflect/Field.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/lang/reflect/Field.java Sun Apr 10 10:23:28 2011 -0700
@@ -79,11 +79,6 @@
// potentially many Field objects pointing to it.)
private Field root;
- // More complicated security check cache needed here than for
- // Class.newInstance() and Constructor.newInstance()
- private Class<?> securityCheckCache;
- private Class<?> securityCheckTargetClassCache;
-
// Generics infrastructure
private String getGenericSignature() {return signature;}
@@ -340,7 +335,7 @@
* instance of the class or interface declaring the underlying
* field, the method throws an {@code IllegalArgumentException}.
*
- * <p>If this {@code Field} object enforces Java language access control, and
+ * <p>If this {@code Field} object is enforcing Java language access control, and
* the underlying field is inaccessible, the method throws an
* {@code IllegalAccessException}.
* If the underlying field is static, the class that declared the
@@ -360,8 +355,9 @@
* {@code obj}; primitive values are wrapped in an appropriate
* object before being returned
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is inaccessible.
* @exception IllegalArgumentException if the specified object is not an
* instance of the class or interface declaring the underlying
* field (or a subclass or implementor thereof).
@@ -383,8 +379,9 @@
* from
* @return the value of the {@code boolean} field
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is inaccessible.
* @exception IllegalArgumentException if the specified object is not
* an instance of the class or interface declaring the
* underlying field (or a subclass or implementor
@@ -410,8 +407,9 @@
* from
* @return the value of the {@code byte} field
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is inaccessible.
* @exception IllegalArgumentException if the specified object is not
* an instance of the class or interface declaring the
* underlying field (or a subclass or implementor
@@ -439,8 +437,9 @@
* from
* @return the value of the field converted to type {@code char}
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is inaccessible.
* @exception IllegalArgumentException if the specified object is not
* an instance of the class or interface declaring the
* underlying field (or a subclass or implementor
@@ -468,8 +467,9 @@
* from
* @return the value of the field converted to type {@code short}
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is inaccessible.
* @exception IllegalArgumentException if the specified object is not
* an instance of the class or interface declaring the
* underlying field (or a subclass or implementor
@@ -497,8 +497,9 @@
* from
* @return the value of the field converted to type {@code int}
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is inaccessible.
* @exception IllegalArgumentException if the specified object is not
* an instance of the class or interface declaring the
* underlying field (or a subclass or implementor
@@ -526,8 +527,9 @@
* from
* @return the value of the field converted to type {@code long}
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is inaccessible.
* @exception IllegalArgumentException if the specified object is not
* an instance of the class or interface declaring the
* underlying field (or a subclass or implementor
@@ -555,8 +557,9 @@
* from
* @return the value of the field converted to type {@code float}
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is inaccessible.
* @exception IllegalArgumentException if the specified object is not
* an instance of the class or interface declaring the
* underlying field (or a subclass or implementor
@@ -584,8 +587,9 @@
* from
* @return the value of the field converted to type {@code double}
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is inaccessible.
* @exception IllegalArgumentException if the specified object is not
* an instance of the class or interface declaring the
* underlying field (or a subclass or implementor
@@ -621,14 +625,14 @@
* an instance of the class or interface declaring the underlying
* field, the method throws an {@code IllegalArgumentException}.
*
- * <p>If this {@code Field} object enforces Java language access control, and
+ * <p>If this {@code Field} object is enforcing Java language access control, and
* the underlying field is inaccessible, the method throws an
* {@code IllegalAccessException}.
*
* <p>If the underlying field is final, the method throws an
- * {@code IllegalAccessException} unless
- * {@code setAccessible(true)} has succeeded for this field
- * and this field is non-static. Setting a final field in this way
+ * {@code IllegalAccessException} unless {@code setAccessible(true)}
+ * has succeeded for this {@code Field} object
+ * and the field is non-static. Setting a final field in this way
* is meaningful only during deserialization or reconstruction of
* instances of classes with blank final fields, before they are
* made available for access by other parts of a program. Use in
@@ -658,8 +662,9 @@
* @param value the new value for the field of {@code obj}
* being modified
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is either inaccessible or final.
* @exception IllegalArgumentException if the specified object is not an
* instance of the class or interface declaring the underlying
* field (or a subclass or implementor thereof),
@@ -686,8 +691,9 @@
* @param z the new value for the field of {@code obj}
* being modified
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is either inaccessible or final.
* @exception IllegalArgumentException if the specified object is not an
* instance of the class or interface declaring the underlying
* field (or a subclass or implementor thereof),
@@ -715,8 +721,9 @@
* @param b the new value for the field of {@code obj}
* being modified
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is either inaccessible or final.
* @exception IllegalArgumentException if the specified object is not an
* instance of the class or interface declaring the underlying
* field (or a subclass or implementor thereof),
@@ -744,8 +751,9 @@
* @param c the new value for the field of {@code obj}
* being modified
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is either inaccessible or final.
* @exception IllegalArgumentException if the specified object is not an
* instance of the class or interface declaring the underlying
* field (or a subclass or implementor thereof),
@@ -773,8 +781,9 @@
* @param s the new value for the field of {@code obj}
* being modified
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is either inaccessible or final.
* @exception IllegalArgumentException if the specified object is not an
* instance of the class or interface declaring the underlying
* field (or a subclass or implementor thereof),
@@ -802,8 +811,9 @@
* @param i the new value for the field of {@code obj}
* being modified
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is either inaccessible or final.
* @exception IllegalArgumentException if the specified object is not an
* instance of the class or interface declaring the underlying
* field (or a subclass or implementor thereof),
@@ -831,8 +841,9 @@
* @param l the new value for the field of {@code obj}
* being modified
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is either inaccessible or final.
* @exception IllegalArgumentException if the specified object is not an
* instance of the class or interface declaring the underlying
* field (or a subclass or implementor thereof),
@@ -860,8 +871,9 @@
* @param f the new value for the field of {@code obj}
* being modified
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is either inaccessible or final.
* @exception IllegalArgumentException if the specified object is not an
* instance of the class or interface declaring the underlying
* field (or a subclass or implementor thereof),
@@ -889,8 +901,9 @@
* @param d the new value for the field of {@code obj}
* being modified
*
- * @exception IllegalAccessException if the underlying field
- * is inaccessible.
+ * @exception IllegalAccessException if this {@code Field} object
+ * is enforcing Java language access control and the underlying
+ * field is either inaccessible or final.
* @exception IllegalArgumentException if the specified object is not an
* instance of the class or interface declaring the underlying
* field (or a subclass or implementor thereof),
@@ -936,6 +949,7 @@
tmp = reflectionFactory.newFieldAccessor(this, overrideFinalCheck);
setFieldAccessor(tmp, overrideFinalCheck);
}
+
return tmp;
}
@@ -965,21 +979,8 @@
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class<?> caller = Reflection.getCallerClass(4);
- Class<?> targetClass = ((obj == null || !Modifier.isProtected(modifiers))
- ? clazz
- : obj.getClass());
- synchronized (this) {
- if ((securityCheckCache == caller)
- && (securityCheckTargetClassCache == targetClass)) {
- return;
- }
- }
- Reflection.ensureMemberAccess(caller, clazz, obj, modifiers);
- synchronized (this) {
- securityCheckCache = caller;
- securityCheckTargetClassCache = targetClass;
- }
+ checkAccess(caller, clazz, obj, modifiers);
}
}
}
--- a/jdk/src/share/classes/java/lang/reflect/Method.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/lang/reflect/Method.java Sun Apr 10 10:23:28 2011 -0700
@@ -83,11 +83,6 @@
// potentially many Method objects pointing to it.)
private Method root;
- // More complicated security check cache needed here than for
- // Class.newInstance() and Constructor.newInstance()
- private Class<?> securityCheckCache;
- private Class<?> securityCheckTargetClassCache;
-
// Generics infrastructure
private String getGenericSignature() {return signature;}
@@ -402,28 +397,28 @@
*/
public String toString() {
try {
- StringBuffer sb = new StringBuffer();
+ StringBuilder sb = new StringBuilder();
int mod = getModifiers() & Modifier.methodModifiers();
if (mod != 0) {
- sb.append(Modifier.toString(mod) + " ");
+ sb.append(Modifier.toString(mod)).append(' ');
}
- sb.append(Field.getTypeName(getReturnType()) + " ");
- sb.append(Field.getTypeName(getDeclaringClass()) + ".");
- sb.append(getName() + "(");
+ sb.append(Field.getTypeName(getReturnType())).append(' ');
+ sb.append(Field.getTypeName(getDeclaringClass())).append('.');
+ sb.append(getName()).append('(');
Class<?>[] params = parameterTypes; // avoid clone
for (int j = 0; j < params.length; j++) {
sb.append(Field.getTypeName(params[j]));
if (j < (params.length - 1))
- sb.append(",");
+ sb.append(',');
}
- sb.append(")");
+ sb.append(')');
Class<?>[] exceptions = exceptionTypes; // avoid clone
if (exceptions.length > 0) {
sb.append(" throws ");
for (int k = 0; k < exceptions.length; k++) {
sb.append(exceptions[k].getName());
if (k < (exceptions.length - 1))
- sb.append(",");
+ sb.append(',');
}
}
return sb.toString();
@@ -475,15 +470,15 @@
StringBuilder sb = new StringBuilder();
int mod = getModifiers() & Modifier.methodModifiers();
if (mod != 0) {
- sb.append(Modifier.toString(mod) + " ");
+ sb.append(Modifier.toString(mod)).append(' ');
}
TypeVariable<?>[] typeparms = getTypeParameters();
if (typeparms.length > 0) {
boolean first = true;
- sb.append("<");
+ sb.append('<');
for(TypeVariable<?> typeparm: typeparms) {
if (!first)
- sb.append(",");
+ sb.append(',');
// Class objects can't occur here; no need to test
// and call Class.getName().
sb.append(typeparm.toString());
@@ -494,10 +489,11 @@
Type genRetType = getGenericReturnType();
sb.append( ((genRetType instanceof Class<?>)?
- Field.getTypeName((Class<?>)genRetType):genRetType.toString()) + " ");
+ Field.getTypeName((Class<?>)genRetType):genRetType.toString()))
+ .append(' ');
- sb.append(Field.getTypeName(getDeclaringClass()) + ".");
- sb.append(getName() + "(");
+ sb.append(Field.getTypeName(getDeclaringClass())).append('.');
+ sb.append(getName()).append('(');
Type[] params = getGenericParameterTypes();
for (int j = 0; j < params.length; j++) {
String param = (params[j] instanceof Class)?
@@ -507,9 +503,9 @@
param = param.replaceFirst("\\[\\]$", "...");
sb.append(param);
if (j < (params.length - 1))
- sb.append(",");
+ sb.append(',');
}
- sb.append(")");
+ sb.append(')');
Type[] exceptions = getGenericExceptionTypes();
if (exceptions.length > 0) {
sb.append(" throws ");
@@ -518,7 +514,7 @@
((Class)exceptions[k]).getName():
exceptions[k].toString());
if (k < (exceptions.length - 1))
- sb.append(",");
+ sb.append(',');
}
}
return sb.toString();
@@ -565,7 +561,7 @@
* {@code args}
*
* @exception IllegalAccessException if this {@code Method} object
- * enforces Java language access control and the underlying
+ * is enforcing Java language access control and the underlying
* method is inaccessible.
* @exception IllegalArgumentException if the method is an
* instance method and the specified object argument
@@ -591,26 +587,15 @@
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class<?> caller = Reflection.getCallerClass(1);
- Class<?> targetClass = ((obj == null || !Modifier.isProtected(modifiers))
- ? clazz
- : obj.getClass());
- boolean cached;
- synchronized (this) {
- cached = (securityCheckCache == caller)
- && (securityCheckTargetClassCache == targetClass);
- }
- if (!cached) {
- Reflection.ensureMemberAccess(caller, clazz, obj, modifiers);
- synchronized (this) {
- securityCheckCache = caller;
- securityCheckTargetClassCache = targetClass;
- }
- }
+ checkAccess(caller, clazz, obj, modifiers);
}
}
- if (methodAccessor == null) acquireMethodAccessor();
- return methodAccessor.invoke(obj, args);
+ MethodAccessor ma = methodAccessor; // read volatile
+ if (ma == null) {
+ ma = acquireMethodAccessor();
+ }
+ return ma.invoke(obj, args);
}
/**
@@ -654,18 +639,20 @@
// (though not efficient) to generate more than one MethodAccessor
// for a given Method. However, avoiding synchronization will
// probably make the implementation more scalable.
- private void acquireMethodAccessor() {
+ private MethodAccessor acquireMethodAccessor() {
// First check to see if one has been created yet, and take it
// if so
MethodAccessor tmp = null;
if (root != null) tmp = root.getMethodAccessor();
if (tmp != null) {
methodAccessor = tmp;
- return;
+ } else {
+ // Otherwise fabricate one and propagate it up to the root
+ tmp = reflectionFactory.newMethodAccessor(this);
+ setMethodAccessor(tmp);
}
- // Otherwise fabricate one and propagate it up to the root
- tmp = reflectionFactory.newMethodAccessor(this);
- setMethodAccessor(tmp);
+
+ return tmp;
}
// Returns MethodAccessor for this Method object, not looking up
--- a/jdk/src/share/classes/java/nio/BufferPoolMXBean.java Thu Apr 07 15:21:10 2011 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,94 +0,0 @@
-/*
- * Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute 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.nio;
-
-import java.lang.management.PlatformManagedObject;
-
-/**
- * The management interface for a buffer pool.
- *
- * <p> A class implementing this interface is an <a href=
- * "java.lang.management.ManagementFactory.html#MXBean">MXBean</a>. A Java
- * virtual machine has one or more implementations of this interface. The {@link
- * java.lang.management.ManagementFactory#getPlatformMXBeans getPlatformMXBeans}
- * method can be used to obtain the list of {@code BufferPoolMXBean} objects
- * representing the management interfaces for pools of buffers as follows:
- * <pre>
- * List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
- * </pre>
- *
- * <p> The management interfaces are also registered with the platform {@link
- * javax.management.MBeanServer MBeanServer}. The {@link
- * javax.management.ObjectName ObjectName} that uniquely identifies the
- * management interface within the {@code MBeanServer} takes the form:
- * <blockquote>
- * <tt>java.nio:type=BufferPool</tt><tt>,name=</tt><i>pool name</i>
- * </blockquote>
- * where <em>pool name</em> is the {@link #getName name} of the buffer pool.
- *
- * @since 1.7
- */
-
-public interface BufferPoolMXBean extends PlatformManagedObject {
-
- /**
- * Returns the name representing this buffer pool.
- *
- * @return The name of this buffer pool.
- */
- String getName();
-
- /**
- * Returns an estimate of the number of buffers in the pool.
- *
- * @return An estimate of the number of buffers in this pool
- */
- long getCount();
-
- /**
- * Returns an estimate of the total capacity of the buffers in this pool.
- * A buffer's capacity is the number of elements it contains and the value
- * returned by this method is an estimate of the total capacity of buffers
- * in the pool in bytes.
- *
- * @return An estimate of the total capacity of the buffers in this pool
- * in bytes
- */
- long getTotalCapacity();
-
- /**
- * Returns an estimate of the memory that the Java virtual machine is using
- * for this buffer pool. The value returned by this method may differ
- * from the estimate of the total {@link #getTotalCapacity capacity} of
- * the buffers in this pool. This difference is explained by alignment,
- * memory allocator, and other implementation specific reasons.
- *
- * @return An estimate of the memory that the Java virtual machine is using
- * for this buffer pool in bytes, or {@code -1L} if an estimate of
- * the memory usage is not available
- */
- long getMemoryUsed();
-}
--- a/jdk/src/share/classes/java/nio/file/Files.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/nio/file/Files.java Sun Apr 10 10:23:28 2011 -0700
@@ -2067,7 +2067,7 @@
*
* @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 symbolic link or not.
+ * be determined if the file is a symbolic link or not.
*
* @throws SecurityException
* In the case of the default provider, and a security manager is
@@ -2106,7 +2106,7 @@
*
* @return {@code true} if the file is a directory; {@code false} if
* the file does not exist, is not a directory, or it cannot
- * be determined if the file is directory or not.
+ * be determined if the file is a directory or not.
*
* @throws SecurityException
* In the case of the default provider, and a security manager is
@@ -2142,8 +2142,8 @@
* options indicating how symbolic links are handled
*
* @return {@code true} if the file is a regular file; {@code false} if
- * the file does not exist, is not a direcregular filetory, or it
- * cannot be determined if the file is regular file or not.
+ * the file does not exist, is not a regular file, or it
+ * cannot be determined if the file is a regular file or not.
*
* @throws SecurityException
* In the case of the default provider, and a security manager is
--- a/jdk/src/share/classes/java/nio/file/Path.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/nio/file/Path.java Sun Apr 10 10:23:28 2011 -0700
@@ -550,18 +550,21 @@
* <p> If this path is relative then its absolute path is first obtained,
* as if by invoking the {@link #toAbsolutePath toAbsolutePath} method.
*
- * <p> The {@code resolveLinks} parameter specifies if symbolic links
- * should be resolved. This parameter is ignored when symbolic links are
- * not supported. Where supported, and the parameter has the value {@code
- * true} then symbolic links are resolved to their final target. Where the
- * parameter has the value {@code false} then this method does not resolve
- * symbolic links. Some implementations allow special names such as
- * "{@code ..}" to refer to the parent directory. When deriving the <em>real
- * path</em>, and a "{@code ..}" (or equivalent) is preceded by a
- * non-"{@code ..}" name then an implementation will typically causes both
- * names to be removed. When not resolving symbolic links and the preceding
- * name is a symbolic link then the names are only removed if it guaranteed
- * that the resulting path will locate the same file as this path.
+ * <p> The {@code options} array may be used to indicate how symbolic links
+ * are handled. By default, symbolic links are resolved to their final
+ * target. If the option {@link LinkOption#NOFOLLOW_LINKS NOFOLLOW_LINKS} is
+ * present then this method does not resolve symbolic links.
+ *
+ * Some implementations allow special names such as "{@code ..}" to refer to
+ * the parent directory. When deriving the <em>real path</em>, and a
+ * "{@code ..}" (or equivalent) is preceded by a non-"{@code ..}" name then
+ * an implementation will typically cause both names to be removed. When
+ * not resolving symbolic links and the preceding name is a symbolic link
+ * then the names are only removed if it guaranteed that the resulting path
+ * will locate the same file as this path.
+ *
+ * @param options
+ * options indicating how symbolic links are handled
*
* @return an absolute path represent the <em>real</em> path of the file
* located by this object
@@ -576,7 +579,7 @@
* checkPropertyAccess} method is invoked to check access to the
* system property {@code user.dir}
*/
- Path toRealPath(boolean resolveLinks) throws IOException;
+ Path toRealPath(LinkOption... options) throws IOException;
/**
* Returns a {@link File} object representing this path. Where this {@code
--- a/jdk/src/share/classes/java/util/Collections.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/util/Collections.java Sun Apr 10 10:23:28 2011 -0700
@@ -3533,20 +3533,20 @@
}
/**
- * Returns a comparator that imposes the reverse of the <i>natural
- * ordering</i> on a collection of objects that implement the
- * <tt>Comparable</tt> interface. (The natural ordering is the ordering
- * imposed by the objects' own <tt>compareTo</tt> method.) This enables a
+ * Returns a comparator that imposes the reverse of the <em>natural
+ * ordering</em> on a collection of objects that implement the
+ * {@code Comparable} interface. (The natural ordering is the ordering
+ * imposed by the objects' own {@code compareTo} method.) This enables a
* simple idiom for sorting (or maintaining) collections (or arrays) of
- * objects that implement the <tt>Comparable</tt> interface in
- * reverse-natural-order. For example, suppose a is an array of
+ * objects that implement the {@code Comparable} interface in
+ * reverse-natural-order. For example, suppose {@code a} is an array of
* strings. Then: <pre>
* Arrays.sort(a, Collections.reverseOrder());
* </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
*
* The returned comparator is serializable.
*
- * @return a comparator that imposes the reverse of the <i>natural
+ * @return A comparator that imposes the reverse of the <i>natural
* ordering</i> on a collection of objects that implement
* the <tt>Comparable</tt> interface.
* @see Comparable
@@ -3575,16 +3575,18 @@
/**
* Returns a comparator that imposes the reverse ordering of the specified
- * comparator. If the specified comparator is null, this method is
+ * comparator. If the specified comparator is {@code null}, this method is
* equivalent to {@link #reverseOrder()} (in other words, it returns a
- * comparator that imposes the reverse of the <i>natural ordering</i> on a
- * collection of objects that implement the Comparable interface).
+ * comparator that imposes the reverse of the <em>natural ordering</em> on
+ * a collection of objects that implement the Comparable interface).
*
* <p>The returned comparator is serializable (assuming the specified
- * comparator is also serializable or null).
+ * comparator is also serializable or {@code null}).
*
- * @return a comparator that imposes the reverse ordering of the
- * specified comparator
+ * @param cmp a comparator who's ordering is to be reversed by the returned
+ * comparator or {@code null}
+ * @return A comparator that imposes the reverse ordering of the
+ * specified comparator.
* @since 1.5
*/
public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {
--- a/jdk/src/share/classes/java/util/ComparableTimSort.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/util/ComparableTimSort.java Sun Apr 10 10:23:28 2011 -0700
@@ -241,7 +241,7 @@
* pivot < all in [left, start), so pivot belongs at left. Note
* that if there are elements equal to pivot, left points to the
* first slot after them -- that's why this sort is stable.
- * Slide elements over to make room to make room for pivot.
+ * Slide elements over to make room for pivot.
*/
int n = start - left; // The number of elements to move
// Switch is just an optimization for arraycopy in default case
--- a/jdk/src/share/classes/java/util/SortedMap.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/util/SortedMap.java Sun Apr 10 10:23:28 2011 -0700
@@ -26,69 +26,70 @@
package java.util;
/**
- * A {@link Map} that further provides a <i>total ordering</i> on its keys.
+ * A {@link Map} that further provides a <em>total ordering</em> on its keys.
* The map is ordered according to the {@linkplain Comparable natural
* ordering} of its keys, or by a {@link Comparator} typically
* provided at sorted map creation time. This order is reflected when
* iterating over the sorted map's collection views (returned by the
- * <tt>entrySet</tt>, <tt>keySet</tt> and <tt>values</tt> methods).
+ * {@code entrySet}, {@code keySet} and {@code values} methods).
* Several additional operations are provided to take advantage of the
- * ordering. (This interface is the map analogue of {@link
- * SortedSet}.)
+ * ordering. (This interface is the map analogue of {@link SortedSet}.)
*
- * <p>All keys inserted into a sorted map must implement the <tt>Comparable</tt>
+ * <p>All keys inserted into a sorted map must implement the {@code Comparable}
* interface (or be accepted by the specified comparator). Furthermore, all
- * such keys must be <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> (or
- * <tt>comparator.compare(k1, k2)</tt>) must not throw a
- * <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> in
+ * such keys must be <em>mutually comparable</em>: {@code k1.compareTo(k2)} (or
+ * {@code comparator.compare(k1, k2)}) must not throw a
+ * {@code ClassCastException} for any keys {@code k1} and {@code k2} in
* the sorted map. Attempts to violate this restriction will cause the
* offending method or constructor invocation to throw a
- * <tt>ClassCastException</tt>.
+ * {@code ClassCastException}.
*
* <p>Note that the ordering maintained by a sorted map (whether or not an
- * explicit comparator is provided) must be <i>consistent with equals</i> if
- * the sorted map is to correctly implement the <tt>Map</tt> interface. (See
- * the <tt>Comparable</tt> interface or <tt>Comparator</tt> interface for a
- * precise definition of <i>consistent with equals</i>.) This is so because
- * the <tt>Map</tt> interface is defined in terms of the <tt>equals</tt>
+ * explicit comparator is provided) must be <em>consistent with equals</em> if
+ * the sorted map is to correctly implement the {@code Map} interface. (See
+ * the {@code Comparable} interface or {@code Comparator} interface for a
+ * precise definition of <em>consistent with equals</em>.) This is so because
+ * the {@code Map} interface is defined in terms of the {@code equals}
* operation, but a sorted map performs all key comparisons using its
- * <tt>compareTo</tt> (or <tt>compare</tt>) method, so two keys that are
+ * {@code compareTo} (or {@code compare}) method, so two keys that are
* deemed equal by this method are, from the standpoint of the sorted map,
- * equal. The behavior of a tree map <i>is</i> well-defined even if its
+ * equal. The behavior of a tree map <em>is</em> well-defined even if its
* ordering is inconsistent with equals; it just fails to obey the general
- * contract of the <tt>Map</tt> interface.
+ * contract of the {@code Map} interface.
*
- * <p>All general-purpose sorted map implementation classes should
- * provide four "standard" constructors: 1) A void (no arguments)
- * constructor, which creates an empty sorted map sorted according to
- * the natural ordering of its keys. 2) A constructor with a
- * single argument of type <tt>Comparator</tt>, which creates an empty
- * sorted map sorted according to the specified comparator. 3) A
- * constructor with a single argument of type <tt>Map</tt>, which
- * creates a new map with the same key-value mappings as its argument,
- * sorted according to the keys' natural ordering. 4) A constructor
- * with a single argument of type <tt>SortedMap</tt>,
- * which creates a new sorted map with the same key-value mappings and
- * the same ordering as the input sorted map. There is no way to
- * enforce this recommendation, as interfaces cannot contain
- * constructors.
+ * <p>All general-purpose sorted map implementation classes should provide four
+ * "standard" constructors. It is not possible to enforce this recommendation
+ * though as required constructors cannot be specified by interfaces. The
+ * expected "standard" constructors for all sorted map implementations are:
+ * <ol>
+ * <li>A void (no arguments) constructor, which creates an empty sorted map
+ * sorted according to the natural ordering of its keys.</li>
+ * <li>A constructor with a single argument of type {@code Comparator}, which
+ * creates an empty sorted map sorted according to the specified comparator.</li>
+ * <li>A constructor with a single argument of type {@code Map}, which creates
+ * a new map with the same key-value mappings as its argument, sorted
+ * according to the keys' natural ordering.</li>
+ * <li>A constructor with a single argument of type {@code SortedMap}, which
+ * creates a new sorted map with the same key-value mappings and the same
+ * ordering as the input sorted map.</li>
+ * </ol>
*
- * <p>Note: several methods return submaps with restricted key ranges.
- * Such ranges are <i>half-open</i>, that is, they include their low
+ * <p><strong>Note</strong>: several methods return submaps with restricted key
+ * ranges. Such ranges are <em>half-open</em>, that is, they include their low
* endpoint but not their high endpoint (where applicable). If you need a
- * <i>closed range</i> (which includes both endpoints), and the key type
+ * <em>closed range</em> (which includes both endpoints), and the key type
* allows for calculation of the successor of a given key, merely request
- * the subrange from <tt>lowEndpoint</tt> to
- * <tt>successor(highEndpoint)</tt>. For example, suppose that <tt>m</tt>
+ * the subrange from {@code lowEndpoint} to
+ * {@code successor(highEndpoint)}. For example, suppose that {@code m}
* is a map whose keys are strings. The following idiom obtains a view
- * containing all of the key-value mappings in <tt>m</tt> whose keys are
- * between <tt>low</tt> and <tt>high</tt>, inclusive:<pre>
+ * containing all of the key-value mappings in {@code m} whose keys are
+ * between {@code low} and {@code high}, inclusive:<pre>
* SortedMap<String, V> sub = m.subMap(low, high+"\0");</pre>
*
- * A similar technique can be used to generate an <i>open range</i>
+ * A similar technique can be used to generate an <em>open range</em>
* (which contains neither endpoint). The following idiom obtains a
- * view containing all of the key-value mappings in <tt>m</tt> whose keys
- * are between <tt>low</tt> and <tt>high</tt>, exclusive:<pre>
+ * view containing all of the key-value mappings in {@code m} whose keys
+ * are between {@code low} and {@code high}, exclusive:<pre>
* SortedMap<String, V> sub = m.subMap(low+"\0", high);</pre>
*
* <p>This interface is a member of the
@@ -112,96 +113,96 @@
public interface SortedMap<K,V> extends Map<K,V> {
/**
* Returns the comparator used to order the keys in this map, or
- * <tt>null</tt> if this map uses the {@linkplain Comparable
+ * {@code null} if this map uses the {@linkplain Comparable
* natural ordering} of its keys.
*
* @return the comparator used to order the keys in this map,
- * or <tt>null</tt> if this map uses the natural ordering
+ * or {@code null} if this map uses the natural ordering
* of its keys
*/
Comparator<? super K> comparator();
/**
* Returns a view of the portion of this map whose keys range from
- * <tt>fromKey</tt>, inclusive, to <tt>toKey</tt>, exclusive. (If
- * <tt>fromKey</tt> and <tt>toKey</tt> are equal, the returned map
+ * {@code fromKey}, inclusive, to {@code toKey}, exclusive. (If
+ * {@code fromKey} and {@code toKey} are equal, the returned map
* is empty.) The returned map is backed by this map, so changes
* in the returned map are reflected in this map, and vice-versa.
* The returned map supports all optional map operations that this
* map supports.
*
- * <p>The returned map will throw an <tt>IllegalArgumentException</tt>
+ * <p>The returned map will throw an {@code IllegalArgumentException}
* on an attempt to insert a key outside its range.
*
* @param fromKey low endpoint (inclusive) of the keys in the returned map
* @param toKey high endpoint (exclusive) of the keys in the returned map
* @return a view of the portion of this map whose keys range from
- * <tt>fromKey</tt>, inclusive, to <tt>toKey</tt>, exclusive
- * @throws ClassCastException if <tt>fromKey</tt> and <tt>toKey</tt>
+ * {@code fromKey}, inclusive, to {@code toKey}, exclusive
+ * @throws ClassCastException if {@code fromKey} and {@code toKey}
* cannot be compared to one another using this map's comparator
* (or, if the map has no comparator, using natural ordering).
* Implementations may, but are not required to, throw this
- * exception if <tt>fromKey</tt> or <tt>toKey</tt>
+ * exception if {@code fromKey} or {@code toKey}
* cannot be compared to keys currently in the map.
- * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt>
+ * @throws NullPointerException if {@code fromKey} or {@code toKey}
* is null and this map does not permit null keys
- * @throws IllegalArgumentException if <tt>fromKey</tt> is greater than
- * <tt>toKey</tt>; or if this map itself has a restricted
- * range, and <tt>fromKey</tt> or <tt>toKey</tt> lies
+ * @throws IllegalArgumentException if {@code fromKey} is greater than
+ * {@code toKey}; or if this map itself has a restricted
+ * range, and {@code fromKey} or {@code toKey} lies
* outside the bounds of the range
*/
SortedMap<K,V> subMap(K fromKey, K toKey);
/**
* Returns a view of the portion of this map whose keys are
- * strictly less than <tt>toKey</tt>. The returned map is backed
+ * strictly less than {@code toKey}. The returned map is backed
* by this map, so changes in the returned map are reflected in
* this map, and vice-versa. The returned map supports all
* optional map operations that this map supports.
*
- * <p>The returned map will throw an <tt>IllegalArgumentException</tt>
+ * <p>The returned map will throw an {@code IllegalArgumentException}
* on an attempt to insert a key outside its range.
*
* @param toKey high endpoint (exclusive) of the keys in the returned map
* @return a view of the portion of this map whose keys are strictly
- * less than <tt>toKey</tt>
- * @throws ClassCastException if <tt>toKey</tt> is not compatible
+ * less than {@code toKey}
+ * @throws ClassCastException if {@code toKey} is not compatible
* with this map's comparator (or, if the map has no comparator,
- * if <tt>toKey</tt> does not implement {@link Comparable}).
+ * if {@code toKey} does not implement {@link Comparable}).
* Implementations may, but are not required to, throw this
- * exception if <tt>toKey</tt> cannot be compared to keys
+ * exception if {@code toKey} cannot be compared to keys
* currently in the map.
- * @throws NullPointerException if <tt>toKey</tt> is null and
+ * @throws NullPointerException if {@code toKey} is null and
* this map does not permit null keys
* @throws IllegalArgumentException if this map itself has a
- * restricted range, and <tt>toKey</tt> lies outside the
+ * restricted range, and {@code toKey} lies outside the
* bounds of the range
*/
SortedMap<K,V> headMap(K toKey);
/**
* Returns a view of the portion of this map whose keys are
- * greater than or equal to <tt>fromKey</tt>. The returned map is
+ * greater than or equal to {@code fromKey}. The returned map is
* backed by this map, so changes in the returned map are
* reflected in this map, and vice-versa. The returned map
* supports all optional map operations that this map supports.
*
- * <p>The returned map will throw an <tt>IllegalArgumentException</tt>
+ * <p>The returned map will throw an {@code IllegalArgumentException}
* on an attempt to insert a key outside its range.
*
* @param fromKey low endpoint (inclusive) of the keys in the returned map
* @return a view of the portion of this map whose keys are greater
- * than or equal to <tt>fromKey</tt>
- * @throws ClassCastException if <tt>fromKey</tt> is not compatible
+ * than or equal to {@code fromKey}
+ * @throws ClassCastException if {@code fromKey} is not compatible
* with this map's comparator (or, if the map has no comparator,
- * if <tt>fromKey</tt> does not implement {@link Comparable}).
+ * if {@code fromKey} does not implement {@link Comparable}).
* Implementations may, but are not required to, throw this
- * exception if <tt>fromKey</tt> cannot be compared to keys
+ * exception if {@code fromKey} cannot be compared to keys
* currently in the map.
- * @throws NullPointerException if <tt>fromKey</tt> is null and
+ * @throws NullPointerException if {@code fromKey} is null and
* this map does not permit null keys
* @throws IllegalArgumentException if this map itself has a
- * restricted range, and <tt>fromKey</tt> lies outside the
+ * restricted range, and {@code fromKey} lies outside the
* bounds of the range
*/
SortedMap<K,V> tailMap(K fromKey);
@@ -228,12 +229,12 @@
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
- * the iterator's own <tt>remove</tt> operation), the results of
+ * the iterator's own {@code remove} operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
- * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
- * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
- * operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
+ * {@code Iterator.remove}, {@code Set.remove},
+ * {@code removeAll}, {@code retainAll}, and {@code clear}
+ * operations. It does not support the {@code add} or {@code addAll}
* operations.
*
* @return a set view of the keys contained in this map, sorted in
@@ -248,13 +249,13 @@
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
- * (except through the iterator's own <tt>remove</tt> operation),
+ * (except through the iterator's own {@code remove} operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
- * mapping from the map, via the <tt>Iterator.remove</tt>,
- * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
- * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
- * support the <tt>add</tt> or <tt>addAll</tt> operations.
+ * mapping from the map, via the {@code Iterator.remove},
+ * {@code Collection.remove}, {@code removeAll},
+ * {@code retainAll} and {@code clear} operations. It does not
+ * support the {@code add} or {@code addAll} operations.
*
* @return a collection view of the values contained in this map,
* sorted in ascending key order
@@ -267,14 +268,14 @@
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
- * the iterator's own <tt>remove</tt> operation, or through the
- * <tt>setValue</tt> operation on a map entry returned by the
+ * the iterator's own {@code remove} operation, or through the
+ * {@code setValue} operation on a map entry returned by the
* iterator) the results of the iteration are undefined. The set
* supports element removal, which removes the corresponding
- * mapping from the map, via the <tt>Iterator.remove</tt>,
- * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
- * <tt>clear</tt> operations. It does not support the
- * <tt>add</tt> or <tt>addAll</tt> operations.
+ * mapping from the map, via the {@code Iterator.remove},
+ * {@code Set.remove}, {@code removeAll}, {@code retainAll} and
+ * {@code clear} operations. It does not support the
+ * {@code add} or {@code addAll} operations.
*
* @return a set view of the mappings contained in this map,
* sorted in ascending key order
--- a/jdk/src/share/classes/java/util/TimSort.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/util/TimSort.java Sun Apr 10 10:23:28 2011 -0700
@@ -274,7 +274,7 @@
* pivot < all in [left, start), so pivot belongs at left. Note
* that if there are elements equal to pivot, left points to the
* first slot after them -- that's why this sort is stable.
- * Slide elements over to make room to make room for pivot.
+ * Slide elements over to make room for pivot.
*/
int n = start - left; // The number of elements to move
// Switch is just an optimization for arraycopy in default case
--- a/jdk/src/share/classes/java/util/jar/JarVerifier.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/util/jar/JarVerifier.java Sun Apr 10 10:23:28 2011 -0700
@@ -415,6 +415,12 @@
pendingBlocks = null;
signerCache = null;
manDig = null;
+ // MANIFEST.MF is always treated as signed and verified,
+ // move its signers from sigFileSigners to verifiedSigners.
+ if (sigFileSigners.containsKey(JarFile.MANIFEST_NAME)) {
+ verifiedSigners.put(JarFile.MANIFEST_NAME,
+ sigFileSigners.remove(JarFile.MANIFEST_NAME));
+ }
}
static class VerifierStream extends java.io.InputStream {
--- a/jdk/src/share/classes/java/util/logging/LogManager.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/util/logging/LogManager.java Sun Apr 10 10:23:28 2011 -0700
@@ -1166,7 +1166,12 @@
private static LoggingMXBean loggingMXBean = null;
/**
* String representation of the
- * {@link javax.management.ObjectName} for {@link LoggingMXBean}.
+ * {@link javax.management.ObjectName} for the management interface
+ * for the logging facility.
+ *
+ * @see java.lang.management.PlatformLoggingMXBean
+ * @see java.util.logging.LoggingMXBean
+ *
* @since 1.5
*/
public final static String LOGGING_MXBEAN_NAME
@@ -1174,20 +1179,20 @@
/**
* Returns <tt>LoggingMXBean</tt> for managing loggers.
- * An alternative way to manage loggers is using
- * the {@link java.lang.management.ManagementFactory#getPlatformMXBeans(Class)
- * ManagementFactory.getPlatformMXBeans} method as follows:
+ * An alternative way to manage loggers is through the
+ * {@link java.lang.management.PlatformLoggingMXBean} interface
+ * that can be obtained by calling:
* <pre>
- * List<{@link PlatformLoggingMXBean}> result = ManagementFactory.getPlatformMXBeans(PlatformLoggingMXBean.class);
+ * PlatformLoggingMXBean logging = {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class)
+ * ManagementFactory.getPlatformMXBean}(PlatformLoggingMXBean.class);
* </pre>
*
* @return a {@link LoggingMXBean} object.
*
- * @see PlatformLoggingMXBean
- * @see java.lang.management.ManagementFactory
+ * @see java.lang.management.PlatformLoggingMXBean
* @since 1.5
*/
- public static synchronized LoggingMXBean getLoggingMXBean() {
+ public static synchronized LoggingMXBean getLoggingMXBean() {
if (loggingMXBean == null) {
loggingMXBean = new Logging();
}
--- a/jdk/src/share/classes/java/util/logging/LoggingMXBean.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/util/logging/LoggingMXBean.java Sun Apr 10 10:23:28 2011 -0700
@@ -27,36 +27,41 @@
/**
- * The management interface for the logging facility.
+ * The management interface for the logging facility. It is recommended
+ * to use the {@link java.lang.management.PlatformLoggingMXBean} management
+ * interface that implements all attributes defined in this
+ * {@code LoggingMXBean}. The
+ * {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class)
+ * ManagementFactory.getPlatformMXBean} method can be used to obtain
+ * the {@code PlatformLoggingMXBean} object representing the management
+ * interface for logging.
*
* <p>There is a single global instance of the <tt>LoggingMXBean</tt>.
- * This instance is an
- * <a href="../../lang/management/ManagementFactory.html#MXBean">MXBean</a>
- * can be obtained by calling
- * the {@link LogManager#getLoggingMXBean} method or from the
+ * This instance is an {@link javax.management.MXBean MXBean} that
+ * can be obtained by calling the {@link LogManager#getLoggingMXBean}
+ * method or from the
* {@linkplain java.lang.management.ManagementFactory#getPlatformMBeanServer
* platform <tt>MBeanServer</tt>}.
- *
- * The {@link javax.management.ObjectName ObjectName} for uniquely
- * identifying the <tt>LoggingMXBean</tt> within an MBeanServer is:
- * <blockquote>
- * {@link LogManager#LOGGING_MXBEAN_NAME
- * <tt>java.util.logging:type=Logging</tt>}
- * </blockquote>
- *
- * The instance registered in the platform <tt>MBeanServer</tt> with
- * this {@code ObjectName} is also a {@link PlatformLoggingMXBean}.
+ * <p>
+ * The {@link javax.management.ObjectName ObjectName} that uniquely identifies
+ * the management interface for logging within the {@code MBeanServer} is:
+ * <pre>
+ * {@link LogManager#LOGGING_MXBEAN_NAME java.util.logging:type=Logging}
+ * </pre>
+ * <p>
+ * The instance registered in the platform {@code MBeanServer}
+ * is also a {@link java.lang.management.PlatformLoggingMXBean}.
*
* @author Ron Mann
* @author Mandy Chung
* @since 1.5
*
- * @see PlatformLoggingMXBean
+ * @see java.lang.management.PlatformLoggingMXBean
*/
public interface LoggingMXBean {
/**
- * Returns the list of currently registered loggers. This method
+ * Returns the list of currently registered logger names. This method
* calls {@link LogManager#getLoggerNames} and returns a list
* of the logger names.
*
@@ -89,7 +94,7 @@
*
* @see Logger#getLevel
*/
- public String getLoggerLevel( String loggerName );
+ public String getLoggerLevel(String loggerName);
/**
* Sets the specified logger to the specified new level.
@@ -115,7 +120,7 @@
*
* @see Logger#setLevel
*/
- public void setLoggerLevel( String loggerName, String levelName );
+ public void setLoggerLevel(String loggerName, String levelName);
/**
* Returns the name of the parent for the specified logger.
--- a/jdk/src/share/classes/java/util/logging/LoggingProxyImpl.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/util/logging/LoggingProxyImpl.java Sun Apr 10 10:23:28 2011 -0700
@@ -99,4 +99,9 @@
public String getLevelName(Object level) {
return ((Level) level).getName();
}
+
+ @Override
+ public String getProperty(String key) {
+ return LogManager.getLogManager().getProperty(key);
+ }
}
--- a/jdk/src/share/classes/java/util/logging/PlatformLoggingMXBean.java Thu Apr 07 15:21:10 2011 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,60 +0,0 @@
-/*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute 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.logging;
-
-import java.lang.management.PlatformManagedObject;
-
-/**
- * The {@linkplain PlatformManagedObject platform managed object} for the
- * logging facility. This interface simply unifies {@link LoggingMXBean}
- * {@link PlatformManagedObject};
- * and it does not specify any new operations.
- *
- * <p>The {@link java.lang.management.ManagementFactory#getPlatformMXBeans(Class)
- * ManagementFactory.getPlatformMXBeans} method can be used to obtain
- * the {@code PlatformLoggingMXBean} object as follows:
- * <pre>
- * ManagementFactory.getPlatformMXBeans(PlatformLoggingMXBean.class);
- * </pre>
- * or from the {@linkplain java.lang.management.ManagementFactory#getPlatformMBeanServer
- * platform <tt>MBeanServer</tt>}.
- *
- * The {@link javax.management.ObjectName ObjectName} for uniquely
- * identifying the <tt>LoggingMXBean</tt> within an MBeanServer is:
- * <blockquote>
- * <tt>java.util.logging:type=Logging</tt>
- * </blockquote>
- *
- * The {@link PlatformManagedObject#getObjectName} method
- * can be used to obtain its {@code ObjectName}.
- *
- * @see java.lang.management.PlatformManagedObject
- *
- * @author Mandy Chung
- * @since 1.7
- */
-public interface PlatformLoggingMXBean extends LoggingMXBean, PlatformManagedObject {
-}
--- a/jdk/src/share/classes/java/util/logging/SimpleFormatter.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/util/logging/SimpleFormatter.java Sun Apr 10 10:23:28 2011 -0700
@@ -29,31 +29,108 @@
import java.io.*;
import java.text.*;
import java.util.Date;
+import sun.util.logging.LoggingSupport;
/**
- * Print a brief summary of the LogRecord in a human readable
+ * Print a brief summary of the {@code LogRecord} in a human readable
* format. The summary will typically be 1 or 2 lines.
*
+ * <p>
+ * <a name="formatting">
+ * <b>Configuration:</b></a>
+ * The {@code SimpleFormatter} is initialized with the
+ * <a href="../Formatter.html#syntax">format string</a>
+ * specified in the {@code java.util.logging.SimpleFormatter.format}
+ * property to {@linkplain #format format} the log messages.
+ * This property can be defined
+ * in the {@linkplain LogManager#getProperty logging properties}
+ * configuration file
+ * or as a system property. If this property is set in both
+ * the logging properties and system properties,
+ * the format string specified in the system property will be used.
+ * If this property is not defined or the given format string
+ * is {@linkplain java.util.IllegalFormatException illegal},
+ * the default format is implementation-specific.
+ *
* @since 1.4
+ * @see java.util.Formatter
*/
public class SimpleFormatter extends Formatter {
- Date dat = new Date();
- private final static String format = "{0,date} {0,time}";
- private MessageFormat formatter;
-
- private Object args[] = new Object[1];
-
- // Line separator string. This is the value of the line.separator
- // property at the moment that the SimpleFormatter was created.
- private String lineSeparator = java.security.AccessController.doPrivileged(
- new sun.security.action.GetPropertyAction("line.separator"));
+ // format string for printing the log record
+ private static final String format = LoggingSupport.getSimpleFormat();
+ private final Date dat = new Date();
/**
* Format the given LogRecord.
* <p>
- * This method can be overridden in a subclass.
+ * The formatting can be customized by specifying the
+ * <a href="../Formatter.html#syntax">format string</a>
+ * in the <a href="#formatting">
+ * {@code java.util.logging.SimpleFormatter.format}</a> property.
+ * The given {@code LogRecord} will be formatted as if by calling:
+ * <pre>
+ * {@link String#format String.format}(format, date, source, logger, level, message, thrown);
+ * </pre>
+ * where the arguments are:<br>
+ * <ol>
+ * <li>{@code format} - the {@link java.util.Formatter
+ * java.util.Formatter} format string specified in the
+ * {@code java.util.logging.SimpleFormatter.format} property
+ * or the default format.</li>
+ * <li>{@code date} - a {@link Date} object representing
+ * {@linkplain LogRecord#getMillis event time} of the log record.</li>
+ * <li>{@code source} - a string representing the caller, if available;
+ * otherwise, the logger's name.</li>
+ * <li>{@code logger} - the logger's name.</li>
+ * <li>{@code level} - the {@linkplain Level#getLocalizedName
+ * log level}.</li>
+ * <li>{@code message} - the formatted log message
+ * returned from the {@link Formatter#formatMessage(LogRecord)}
+ * method. It uses {@link java.text.MessageFormat java.text}
+ * formatting and does not use the {@code java.util.Formatter
+ * format} argument.</li>
+ * <li>{@code thrown} - a string representing
+ * the {@linkplain LogRecord#getThrown throwable}
+ * associated with the log record and its backtrace
+ * beginning with a newline character, if any;
+ * otherwise, an empty string.</li>
+ * </ol>
+ *
+ * <p>Some example formats:<br>
+ * <ul>
+ * <li> {@code java.util.logging.SimpleFormatter.format="%4$s: %5$s [%1$tc]%n"}
+ * <p>This prints 1 line with the log level ({@code 4$}),
+ * the log message ({@code 5$}) and the timestamp ({@code 1$}) in
+ * a square bracket.
+ * <pre>
+ * WARNING: warning message [Tue Mar 22 13:11:31 PDT 2011]
+ * </pre></li>
+ * <li> {@code java.util.logging.SimpleFormatter.format="%1$tc %2$s%n%4$s: %5$s%6$s%n"}
+ * <p>This prints 2 lines where the first line includes
+ * the timestamp ({@code 1$}) and the source ({@code 2$});
+ * the second line includes the log level ({@code 4$}) and
+ * the log message ({@code 5$}) followed with the throwable
+ * and its backtrace ({@code 6$}), if any:
+ * <pre>
+ * Tue Mar 22 13:11:31 PDT 2011 MyClass fatal
+ * SEVERE: several message with an exception
+ * java.lang.IllegalArgumentException: invalid argument
+ * at MyClass.mash(MyClass.java:9)
+ * at MyClass.crunch(MyClass.java:6)
+ * at MyClass.main(MyClass.java:3)
+ * </pre></li>
+ * <li> {@code java.util.logging.SimpleFormatter.format="%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%n"}
+ * <p>This prints 2 lines similar to the example above
+ * with a different date/time formatting and does not print
+ * the throwable and its backtrace:
+ * <pre>
+ * Mar 22, 2011 1:11:31 PM MyClass fatal
+ * SEVERE: several message with an exception
+ * </pre></li>
+ * </ul>
+ * <p>This method can also be overridden in a subclass.
* It is recommended to use the {@link Formatter#formatMessage}
* convenience method to localize and format the message field.
*
@@ -61,42 +138,32 @@
* @return a formatted log record
*/
public synchronized String format(LogRecord record) {
- StringBuffer sb = new StringBuffer();
- // Minimize memory allocations here.
dat.setTime(record.getMillis());
- args[0] = dat;
- StringBuffer text = new StringBuffer();
- if (formatter == null) {
- formatter = new MessageFormat(format);
- }
- formatter.format(args, text, null);
- sb.append(text);
- sb.append(" ");
+ String source;
if (record.getSourceClassName() != null) {
- sb.append(record.getSourceClassName());
+ source = record.getSourceClassName();
+ if (record.getSourceMethodName() != null) {
+ source += " " + record.getSourceMethodName();
+ }
} else {
- sb.append(record.getLoggerName());
+ source = record.getLoggerName();
}
- if (record.getSourceMethodName() != null) {
- sb.append(" ");
- sb.append(record.getSourceMethodName());
- }
- sb.append(lineSeparator);
String message = formatMessage(record);
- sb.append(record.getLevel().getLocalizedName());
- sb.append(": ");
- sb.append(message);
- sb.append(lineSeparator);
+ String throwable = "";
if (record.getThrown() != null) {
- try {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- record.getThrown().printStackTrace(pw);
- pw.close();
- sb.append(sw.toString());
- } catch (Exception ex) {
- }
+ StringWriter sw = new StringWriter();
+ PrintWriter pw = new PrintWriter(sw);
+ pw.println();
+ record.getThrown().printStackTrace(pw);
+ pw.close();
+ throwable = sw.toString();
}
- return sb.toString();
+ return String.format(format,
+ dat,
+ source,
+ record.getLoggerName(),
+ record.getLevel().getLocalizedName(),
+ message,
+ throwable);
}
}
--- a/jdk/src/share/classes/java/util/zip/DeflaterOutputStream.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/java/util/zip/DeflaterOutputStream.java Sun Apr 10 10:23:28 2011 -0700
@@ -206,14 +206,9 @@
return;
}
if (!def.finished()) {
- // Deflate no more than stride bytes at a time. This avoids
- // excess copying in deflateBytes (see Deflater.c)
- int stride = buf.length;
- for (int i = 0; i < len; i+= stride) {
- def.setInput(b, off + i, Math.min(stride, len - i));
- while (!def.needsInput()) {
- deflate();
- }
+ def.setInput(b, off, len);
+ while (!def.needsInput()) {
+ deflate();
}
}
}
--- a/jdk/src/share/classes/javax/imageio/metadata/IIOMetadataNode.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/javax/imageio/metadata/IIOMetadataNode.java Sun Apr 10 10:23:28 2011 -0700
@@ -724,7 +724,7 @@
/**
* Equivalent to <code>getNodeName</code>.
*
- * @return the node name, as a <code>String</code
+ * @return the node name, as a <code>String</code>
*/
public String getTagName() {
return nodeName;
--- a/jdk/src/share/classes/javax/net/ssl/KeyStoreBuilderParameters.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/javax/net/ssl/KeyStoreBuilderParameters.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -51,7 +51,7 @@
* @exception NullPointerException if builder is null
*/
public KeyStoreBuilderParameters(Builder builder) {
- parameters = Collections.singletonList(builder);
+ parameters = Collections.singletonList(Objects.requireNonNull(builder));
}
/**
@@ -64,11 +64,12 @@
* @exception IllegalArgumentException if parameters is an empty list
*/
public KeyStoreBuilderParameters(List<Builder> parameters) {
+ if (parameters.isEmpty()) {
+ throw new IllegalArgumentException();
+ }
+
this.parameters = Collections.unmodifiableList(
new ArrayList<Builder>(parameters));
- if (this.parameters.isEmpty()) {
- throw new IllegalArgumentException();
- }
}
/**
--- a/jdk/src/share/classes/javax/swing/JLayer.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/javax/swing/JLayer.java Sun Apr 10 10:23:28 2011 -0700
@@ -476,7 +476,7 @@
* for this {@code JLayer} and the {@code JLayer}
* is displayable.
* <p/>
- * The following example shows how to correclty use this method
+ * The following example shows how to correctly use this method
* in the {@code LayerUI} implementations:
* <pre>
* public void installUI(JComponent c) {
@@ -834,7 +834,7 @@
}
/**
- * First, implementatation of this method iterates through
+ * First, implementation of this method iterates through
* glassPane's child components and returns {@code true}
* if any of them is visible and contains passed x,y point.
* After that it checks if no mouseListeners is attached to this component
--- a/jdk/src/share/classes/javax/swing/PopupFactory.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/javax/swing/PopupFactory.java Sun Apr 10 10:23:28 2011 -0700
@@ -203,6 +203,12 @@
popupType = HEAVY_WEIGHT_POPUP;
break;
}
+ } else if (c instanceof Window) {
+ Window w = (Window) c;
+ if (!w.isOpaque() || w.getOpacity() < 1 || w.getShape() != null) {
+ popupType = HEAVY_WEIGHT_POPUP;
+ break;
+ }
}
c = c.getParent();
}
--- a/jdk/src/share/classes/javax/swing/SpringLayout.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/javax/swing/SpringLayout.java Sun Apr 10 10:23:28 2011 -0700
@@ -727,6 +727,9 @@
* For any other <code>String</code> value passed as the edge,
* no action is taken. For a <code>null</code> edge, a
* <code>NullPointerException</code> is thrown.
+ * <p/>
+ * <b>Note:</b> This method can affect {@code x} and {@code y} values
+ * previously set for this {@code Constraints}.
*
* @param edgeName the edge to be set
* @param s the spring controlling the specified edge
--- a/jdk/src/share/classes/javax/swing/plaf/LayerUI.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/LayerUI.java Sun Apr 10 10:23:28 2011 -0700
@@ -25,9 +25,7 @@
package javax.swing.plaf;
-import javax.accessibility.Accessible;
import javax.swing.*;
-import javax.swing.plaf.ComponentUI;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
@@ -38,7 +36,7 @@
/**
* The base class for all {@link javax.swing.JLayer}'s UI delegates.
* <p/>
- * {@link #paint(java.awt.Graphics, javax.swing.JComponent)} method performes the
+ * {@link #paint(java.awt.Graphics, javax.swing.JComponent)} method performs the
* painting of the {@code JLayer}
* and {@link #eventDispatched(AWTEvent, JLayer)} method is notified
* about any {@code AWTEvent}s which have been generated by a {@code JLayer}
@@ -165,7 +163,7 @@
* l.setLayerEventMask(AWTEvent.COMPONENT_EVENT_MASK);
* }
*
- * public void unistallUI(JComponent c) {
+ * public void uninstallUI(JComponent c) {
* super.uninstallUI(c);
* JLayer l = (JLayer) c;
* l.setLayerEventMask(0);
@@ -197,7 +195,7 @@
* l.setLayerEventMask(AWTEvent.FOCUS_EVENT_MASK);
* }
*
- * public void unistallUI(JComponent c) {
+ * public void uninstallUI(JComponent c) {
* super.uninstallUI(c);
* JLayer l = (JLayer) c;
* l.setLayerEventMask(0);
@@ -229,7 +227,7 @@
* l.setLayerEventMask(AWTEvent.KEY_EVENT_MASK);
* }
*
- * public void unistallUI(JComponent c) {
+ * public void uninstallUI(JComponent c) {
* super.uninstallUI(c);
* JLayer l = (JLayer) c;
* l.setLayerEventMask(0);
@@ -261,7 +259,7 @@
* l.setLayerEventMask(AWTEvent.MOUSE_EVENT_MASK);
* }
*
- * public void unistallUI(JComponent c) {
+ * public void uninstallUI(JComponent c) {
* super.uninstallUI(c);
* JLayer l = (JLayer) c;
* l.setLayerEventMask(0);
@@ -293,7 +291,7 @@
* l.setLayerEventMask(AWTEvent.MOUSE_MOTION_EVENT_MASK);
* }
*
- * public void unistallUI(JComponent c) {
+ * public void uninstallUI(JComponent c) {
* super.uninstallUI(c);
* JLayer l = (JLayer) c;
* l.setLayerEventMask(0);
@@ -325,7 +323,7 @@
* l.setLayerEventMask(AWTEvent.MOUSE_WHEEL_EVENT_MASK);
* }
*
- * public void unistallUI(JComponent c) {
+ * public void uninstallUI(JComponent c) {
* super.uninstallUI(c);
* JLayer l = (JLayer) c;
* l.setLayerEventMask(0);
@@ -357,7 +355,7 @@
* l.setLayerEventMask(AWTEvent.INPUT_METHOD_EVENT_MASK);
* }
*
- * public void unistallUI(JComponent c) {
+ * public void uninstallUI(JComponent c) {
* super.uninstallUI(c);
* JLayer l = (JLayer) c;
* l.setLayerEventMask(0);
@@ -389,7 +387,7 @@
* l.setLayerEventMask(AWTEvent.HIERARCHY_EVENT_MASK);
* }
*
- * public void unistallUI(JComponent c) {
+ * public void uninstallUI(JComponent c) {
* super.uninstallUI(c);
* JLayer l = (JLayer) c;
* l.setLayerEventMask(0);
@@ -421,7 +419,7 @@
* l.setLayerEventMask(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK);
* }
*
- * public void unistallUI(JComponent c) {
+ * public void uninstallUI(JComponent c) {
* super.uninstallUI(c);
* JLayer l = (JLayer) c;
* l.setLayerEventMask(0);
@@ -691,7 +689,7 @@
* Otherwise, the default implementation is used.
*
* @param c {@code JLayer} to return preferred size for
- * @return maximun size for the passed {@code JLayer}
+ * @return maximum size for the passed {@code JLayer}
*/
public Dimension getMaximumSize(JComponent c) {
JLayer l = (JLayer) c;
--- a/jdk/src/share/classes/javax/swing/plaf/nimbus/LoweredBorder.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/LoweredBorder.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -26,13 +26,11 @@
import javax.swing.border.Border;
import javax.swing.JComponent;
-import javax.swing.plaf.UIResource;
import java.awt.Insets;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
-import java.awt.Transparency;
import java.awt.RenderingHints;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
@@ -58,7 +56,9 @@
@Override
protected Object[] getExtendedCacheKeys(JComponent c) {
- return new Object[] {c.getBackground()};
+ return (c != null)
+ ? new Object[] { c.getBackground() }
+ : null;
}
/**
@@ -85,6 +85,7 @@
*/
protected void doPaint(Graphics2D g, JComponent c, int width, int height,
Object[] extendedCacheKeys) {
+ Color color = (c == null) ? Color.BLACK : c.getBackground();
BufferedImage img1 = new BufferedImage(IMG_SIZE,IMG_SIZE,
BufferedImage.TYPE_INT_ARGB);
BufferedImage img2 = new BufferedImage(IMG_SIZE,IMG_SIZE,
@@ -93,14 +94,14 @@
Graphics2D g2 = (Graphics2D)img1.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
- g2.setColor(c.getBackground());
+ g2.setColor(color);
g2.fillRoundRect(2,0,26,26,RADIUS,RADIUS);
g2.dispose();
// draw shadow
InnerShadowEffect effect = new InnerShadowEffect();
effect.setDistance(1);
effect.setSize(3);
- effect.setColor(getLighter(c.getBackground(),2.1f));
+ effect.setColor(getLighter(color, 2.1f));
effect.setAngle(90);
effect.applyEffect(img1,img2,IMG_SIZE,IMG_SIZE);
// draw outline to img2
@@ -108,7 +109,7 @@
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setClip(0,28,IMG_SIZE,1);
- g2.setColor(getLighter(c.getBackground(),0.90f));
+ g2.setColor(getLighter(color, 0.90f));
g2.drawRoundRect(2,1,25,25,RADIUS,RADIUS);
g2.dispose();
// draw final image
@@ -150,7 +151,7 @@
* @param c the component for which this border insets value applies
*/
public Insets getBorderInsets(Component c) {
- return INSETS;
+ return (Insets) INSETS.clone();
}
/**
--- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java Sun Apr 10 10:23:28 2011 -0700
@@ -786,9 +786,9 @@
hasFocus, row, column);
setIcon(null);
- Class columnClass = table.getColumnClass(column);
- configureValue(value, columnClass);
-
+ if (table != null) {
+ configureValue(value, table.getColumnClass(column));
+ }
return this;
}
--- a/jdk/src/share/classes/sun/awt/FontConfiguration.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/awt/FontConfiguration.java Sun Apr 10 10:23:28 2011 -0700
@@ -82,6 +82,10 @@
* one to ensure proper static initialisation takes place.
*/
public FontConfiguration(SunFontManager fm) {
+ if (FontUtilities.debugFonts()) {
+ FontUtilities.getLogger()
+ .info("Creating standard Font Configuration");
+ }
if (FontUtilities.debugFonts() && logger == null) {
logger = PlatformLogger.getLogger("sun.awt.FontConfiguration");
}
@@ -111,6 +115,10 @@
boolean preferLocaleFonts,
boolean preferPropFonts) {
fontManager = fm;
+ if (FontUtilities.debugFonts()) {
+ FontUtilities.getLogger()
+ .info("Creating alternate Font Configuration");
+ }
this.preferLocaleFonts = preferLocaleFonts;
this.preferPropFonts = preferPropFonts;
/* fontConfig should be initialised by default constructor, and
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/awt/HToolkit.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,378 @@
+/*
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.awt;
+
+import java.awt.*;
+import java.awt.dnd.*;
+import java.awt.dnd.peer.DragSourceContextPeer;
+import java.awt.im.InputMethodHighlight;
+import java.awt.im.spi.InputMethodDescriptor;
+import java.awt.image.*;
+import java.awt.datatransfer.Clipboard;
+import java.awt.peer.*;
+import java.util.Map;
+import java.util.Properties;
+
+/*
+ * HToolkit is a platform independent Toolkit used
+ * with the HeadlessToolkit. It is primarily used
+ * in embedded JRE's that do not have sun/awt/X11 classes.
+ */
+public class HToolkit extends SunToolkit
+ implements ComponentFactory {
+
+ public HToolkit() {
+ }
+
+ /*
+ * Component peer objects - unsupported.
+ */
+
+ public WindowPeer createWindow(Window target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public FramePeer createFrame(Frame target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public DialogPeer createDialog(Dialog target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public ButtonPeer createButton(Button target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public TextFieldPeer createTextField(TextField target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public ChoicePeer createChoice(Choice target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public LabelPeer createLabel(Label target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public ListPeer createList(List target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public CheckboxPeer createCheckbox(Checkbox target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public ScrollbarPeer createScrollbar(Scrollbar target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public ScrollPanePeer createScrollPane(ScrollPane target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public TextAreaPeer createTextArea(TextArea target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public FileDialogPeer createFileDialog(FileDialog target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public MenuBarPeer createMenuBar(MenuBar target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public MenuPeer createMenu(Menu target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public PopupMenuPeer createPopupMenu(PopupMenu target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public MenuItemPeer createMenuItem(MenuItem target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public CheckboxMenuItemPeer createCheckboxMenuItem(CheckboxMenuItem target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public DragSourceContextPeer createDragSourceContextPeer(
+ DragGestureEvent dge)
+ throws InvalidDnDOperationException {
+ throw new InvalidDnDOperationException("Headless environment");
+ }
+
+ public RobotPeer createRobot(Robot target, GraphicsDevice screen)
+ throws AWTException, HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public KeyboardFocusManagerPeer createKeyboardFocusManagerPeer(KeyboardFocusManager manager) {
+ // See 6833019.
+ return
+ new KeyboardFocusManagerPeer() {
+ public Window getCurrentFocusedWindow() { return null; }
+ public void setCurrentFocusOwner(Component comp) {}
+ public Component getCurrentFocusOwner() { return null; }
+ public void clearGlobalFocusOwner(Window activeWindow) {}
+ };
+ }
+
+ public TrayIconPeer createTrayIcon(TrayIcon target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public SystemTrayPeer createSystemTray(SystemTray target)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public boolean isTraySupported() {
+ return false;
+ }
+
+ public GlobalCursorManager getGlobalCursorManager()
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ /*
+ * Headless toolkit - unsupported.
+ */
+ protected void loadSystemColors(int[] systemColors)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public ColorModel getColorModel()
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public int getScreenResolution()
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public Map mapInputMethodHighlight(InputMethodHighlight highlight)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public int getMenuShortcutKeyMask()
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public boolean getLockingKeyState(int keyCode)
+ throws UnsupportedOperationException {
+ throw new HeadlessException();
+ }
+
+ public void setLockingKeyState(int keyCode, boolean on)
+ throws UnsupportedOperationException {
+ throw new HeadlessException();
+ }
+
+ public Cursor createCustomCursor(Image cursor, Point hotSpot, String name)
+ throws IndexOutOfBoundsException, HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public Dimension getBestCursorSize(int preferredWidth, int preferredHeight)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public int getMaximumCursorColors()
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public <T extends DragGestureRecognizer> T
+ createDragGestureRecognizer(Class<T> abstractRecognizerClass,
+ DragSource ds, Component c,
+ int srcActions, DragGestureListener dgl)
+ {
+ return null;
+ }
+
+ public int getScreenHeight()
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public int getScreenWidth()
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public Dimension getScreenSize()
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public Insets getScreenInsets(GraphicsConfiguration gc)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public void setDynamicLayout(boolean dynamic)
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ protected boolean isDynamicLayoutSet()
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public boolean isDynamicLayoutActive()
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ public Clipboard getSystemClipboard()
+ throws HeadlessException {
+ throw new HeadlessException();
+ }
+
+ /*
+ * Printing
+ */
+ public PrintJob getPrintJob(Frame frame, String jobtitle,
+ JobAttributes jobAttributes,
+ PageAttributes pageAttributes) {
+ if (frame != null) {
+ // Should never happen
+ throw new HeadlessException();
+ }
+ throw new IllegalArgumentException(
+ "PrintJob not supported in a headless environment");
+ }
+
+ public PrintJob getPrintJob(Frame frame, String doctitle, Properties props)
+ {
+ if (frame != null) {
+ // Should never happen
+ throw new HeadlessException();
+ }
+ throw new IllegalArgumentException(
+ "PrintJob not supported in a headless environment");
+ }
+
+ /*
+ * Headless toolkit - supported.
+ */
+
+ public void sync() {
+ // Do nothing
+ }
+
+ protected boolean syncNativeQueue(final long timeout) {
+ return false;
+ }
+
+ public void beep() {
+ // Send alert character
+ System.out.write(0x07);
+ }
+
+
+ /*
+ * Fonts
+ */
+ public FontPeer getFontPeer(String name, int style) {
+ return (FontPeer)null;
+ }
+
+ /*
+ * Modality
+ */
+ public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) {
+ return false;
+ }
+
+ public boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType exclusionType) {
+ return false;
+ }
+
+ public boolean isDesktopSupported() {
+ return false;
+ }
+
+ public DesktopPeer createDesktopPeer(Desktop target)
+ throws HeadlessException{
+ throw new HeadlessException();
+ }
+
+ public boolean isWindowOpacityControlSupported() {
+ return false;
+ }
+
+ public boolean isWindowShapingSupported() {
+ return false;
+ }
+
+ public boolean isWindowTranslucencySupported() {
+ return false;
+ }
+
+ public void grab(Window w) { }
+
+ public void ungrab(Window w) { }
+
+ protected boolean syncNativeQueue() { return false; }
+
+ public InputMethodDescriptor getInputMethodAdapterDescriptor()
+ throws AWTException
+ {
+ return (InputMethodDescriptor)null;
+ }
+}
--- a/jdk/src/share/classes/sun/awt/HeadlessToolkit.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/awt/HeadlessToolkit.java Sun Apr 10 10:23:28 2011 -0700
@@ -320,8 +320,7 @@
// Should never happen
throw new HeadlessException();
}
- throw new IllegalArgumentException(
- "PrintJob not supported in a headless environment");
+ throw new NullPointerException("frame must not be null");
}
public PrintJob getPrintJob(Frame frame, String doctitle, Properties props)
@@ -330,8 +329,7 @@
// Should never happen
throw new HeadlessException();
}
- throw new IllegalArgumentException(
- "PrintJob not supported in a headless environment");
+ throw new NullPointerException("frame must not be null");
}
/*
--- a/jdk/src/share/classes/sun/font/FontManagerForSGE.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/font/FontManagerForSGE.java Sun Apr 10 10:23:28 2011 -0700
@@ -54,4 +54,11 @@
public Font[] getAllInstalledFonts();
public String[] getInstalledFontFamilyNames(Locale requestedLocale);
+
+ /* Modifies the behaviour of a subsequent call to preferLocaleFonts()
+ * to use Mincho instead of Gothic for dialoginput in JA locales
+ * on windows. Not needed on other platforms.
+ */
+ public void useAlternateFontforJALocales();
+
}
--- a/jdk/src/share/classes/sun/font/SunFontManager.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/font/SunFontManager.java Sun Apr 10 10:23:28 2011 -0700
@@ -2874,7 +2874,10 @@
* on windows. Not needed on other platforms.
*/
public synchronized void useAlternateFontforJALocales() {
-
+ if (FontUtilities.isLogging()) {
+ FontUtilities.getLogger()
+ .info("Entered useAlternateFontforJALocales().");
+ }
if (!FontUtilities.isWindows) {
return;
}
@@ -2897,7 +2900,9 @@
}
public synchronized void preferLocaleFonts() {
-
+ if (FontUtilities.isLogging()) {
+ FontUtilities.getLogger().info("Entered preferLocaleFonts().");
+ }
/* Test if re-ordering will have any effect */
if (!FontConfiguration.willReorderForStartupLocale()) {
return;
@@ -2928,7 +2933,10 @@
}
public synchronized void preferProportionalFonts() {
-
+ if (FontUtilities.isLogging()) {
+ FontUtilities.getLogger()
+ .info("Entered preferProportionalFonts().");
+ }
/* If no proportional fonts are configured, there's no need
* to take any action.
*/
@@ -3456,6 +3464,11 @@
initCompositeFonts(FontConfiguration fontConfig,
ConcurrentHashMap<String, Font2D> altNameCache) {
+ if (FontUtilities.isLogging()) {
+ FontUtilities.getLogger()
+ .info("Initialising composite fonts");
+ }
+
int numCoreFonts = fontConfig.getNumberCoreFonts();
String[] fcFonts = fontConfig.getPlatformFontNames();
for (int f=0; f<fcFonts.length; f++) {
--- a/jdk/src/share/classes/sun/java2d/SunGraphicsEnvironment.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/java2d/SunGraphicsEnvironment.java Sun Apr 10 10:23:28 2011 -0700
@@ -185,6 +185,18 @@
FontManager fm = FontManagerFactory.getInstance();
return (FontManagerForSGE) fm;
}
+
+ /* Modifies the behaviour of a subsequent call to preferLocaleFonts()
+ * to use Mincho instead of Gothic for dialoginput in JA locales
+ * on windows. Not needed on other platforms.
+ *
+ * DO NOT MOVE OR RENAME OR OTHERWISE ALTER THIS METHOD.
+ * ITS USED BY SOME NON-JRE INTERNAL CODE.
+ */
+ public static void useAlternateFontforJALocales() {
+ getFontManagerForSGE().useAlternateFontforJALocales();
+ }
+
/**
* Returns all fonts available in this environment.
*/
--- a/jdk/src/share/classes/sun/management/ManagementFactoryHelper.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/management/ManagementFactoryHelper.java Sun Apr 10 10:23:28 2011 -0700
@@ -27,20 +27,18 @@
import java.lang.management.*;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
+import javax.management.MBeanServer;
import javax.management.MBeanRegistrationException;
import javax.management.NotCompliantMBeanException;
+import javax.management.ObjectName;
import javax.management.RuntimeOperationsException;
-import java.nio.BufferPoolMXBean;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import sun.security.action.LoadLibraryAction;
-import java.util.logging.PlatformLoggingMXBean;
import sun.util.logging.LoggingSupport;
import java.util.ArrayList;
@@ -139,61 +137,80 @@
return result;
}
- public static List<PlatformLoggingMXBean> getLoggingMXBean() {
+ public static PlatformLoggingMXBean getPlatformLoggingMXBean() {
if (LoggingSupport.isAvailable()) {
- return Collections.singletonList(createPlatformLoggingMXBean());
+ return PlatformLoggingImpl.instance;
} else {
- return Collections.emptyList();
+ return null;
}
}
- private final static String LOGGING_MXBEAN_NAME = "java.util.logging:type=Logging";
- private static PlatformLoggingMXBean createPlatformLoggingMXBean() {
- return new PlatformLoggingMXBean() {
- private volatile ObjectName objname; // created lazily
- @Override
- public ObjectName getObjectName() {
- ObjectName result = objname;
- if (result == null) {
- synchronized (this) {
- if (objname == null) {
- result = Util.newObjectName(LOGGING_MXBEAN_NAME);
- objname = result;
- }
+ // The logging MXBean object is an instance of
+ // PlatformLoggingMXBean and java.util.logging.LoggingMXBean
+ // but it can't directly implement two MXBean interfaces
+ // as a compliant MXBean implements exactly one MXBean interface,
+ // or if it implements one interface that is a subinterface of
+ // all the others; otherwise, it is a non-compliant MXBean
+ // and MBeanServer will throw NotCompliantMBeanException.
+ // See the Definition of an MXBean section in javax.management.MXBean spec.
+ //
+ // To create a compliant logging MXBean, define a LoggingMXBean interface
+ // that extend PlatformLoggingMXBean and j.u.l.LoggingMXBean
+ interface LoggingMXBean
+ extends PlatformLoggingMXBean, java.util.logging.LoggingMXBean {
+ }
+
+ static class PlatformLoggingImpl implements LoggingMXBean
+ {
+ final static PlatformLoggingMXBean instance = new PlatformLoggingImpl();
+ final static String LOGGING_MXBEAN_NAME = "java.util.logging:type=Logging";
+
+ private volatile ObjectName objname; // created lazily
+ @Override
+ public ObjectName getObjectName() {
+ ObjectName result = objname;
+ if (result == null) {
+ synchronized (this) {
+ if (objname == null) {
+ result = Util.newObjectName(LOGGING_MXBEAN_NAME);
+ objname = result;
}
}
- return result;
}
+ return result;
+ }
- @Override
- public java.util.List<String> getLoggerNames() {
- return LoggingSupport.getLoggerNames();
- }
+ @Override
+ public java.util.List<String> getLoggerNames() {
+ return LoggingSupport.getLoggerNames();
+ }
- @Override
- public String getLoggerLevel(String loggerName) {
- return LoggingSupport.getLoggerLevel(loggerName);
- }
+ @Override
+ public String getLoggerLevel(String loggerName) {
+ return LoggingSupport.getLoggerLevel(loggerName);
+ }
- @Override
- public void setLoggerLevel(String loggerName, String levelName) {
- LoggingSupport.setLoggerLevel(loggerName, levelName);
- }
+ @Override
+ public void setLoggerLevel(String loggerName, String levelName) {
+ LoggingSupport.setLoggerLevel(loggerName, levelName);
+ }
- @Override
- public String getParentLoggerName(String loggerName) {
- return LoggingSupport.getParentLoggerName(loggerName);
- }
- };
+ @Override
+ public String getParentLoggerName(String loggerName) {
+ return LoggingSupport.getParentLoggerName(loggerName);
+ }
}
- public static List<BufferPoolMXBean> getBufferPoolMXBeans() {
- List<BufferPoolMXBean> pools = new ArrayList<BufferPoolMXBean>(2);
- pools.add(createBufferPoolMXBean(sun.misc.SharedSecrets.getJavaNioAccess()
- .getDirectBufferPool()));
- pools.add(createBufferPoolMXBean(sun.nio.ch.FileChannelImpl
- .getMappedBufferPool()));
- return pools;
+ private static List<BufferPoolMXBean> bufferPools = null;
+ public static synchronized List<BufferPoolMXBean> getBufferPoolMXBeans() {
+ if (bufferPools == null) {
+ bufferPools = new ArrayList<>(2);
+ bufferPools.add(createBufferPoolMXBean(sun.misc.SharedSecrets.getJavaNioAccess()
+ .getDirectBufferPool()));
+ bufferPools.add(createBufferPoolMXBean(sun.nio.ch.FileChannelImpl
+ .getMappedBufferPool()));
+ }
+ return bufferPools;
}
private final static String BUFFER_POOL_MXBEAN_NAME = "java.nio:type=BufferPool";
--- a/jdk/src/share/classes/sun/misc/Version.java.template Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/misc/Version.java.template Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -36,8 +36,8 @@
"@@java_version@@";
private static final String java_runtime_name =
- "@@java_runtime_name@@";
-
+ "@@java_runtime_name@@";
+
private static final String java_runtime_version =
"@@java_runtime_version@@";
@@ -87,12 +87,26 @@
* Give a stream, it will print version info on it.
*/
public static void print(PrintStream ps) {
+ boolean isHeadless = false;
+
+ /* Report that we're running headless if the property is true */
+ String headless = System.getProperty("java.awt.headless");
+ if ( (headless != null) && (headless.equalsIgnoreCase("true")) ) {
+ isHeadless = true;
+ }
+
/* First line: platform version. */
ps.println(launcher_name + " version \"" + java_version + "\"");
/* Second line: runtime version (ie, libraries). */
- ps.println(java_runtime_name + " (build " +
- java_runtime_version + ")");
+
+ ps.print(java_runtime_name + " (build " + java_runtime_version);
+
+ if (java_runtime_name.indexOf("Embedded") != -1 && isHeadless) {
+ // embedded builds report headless state
+ ps.print(", headless");
+ }
+ ps.println(')');
/* Third line: JVM information. */
String java_vm_name = System.getProperty("java.vm.name");
--- a/jdk/src/share/classes/sun/nio/fs/Util.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/nio/fs/Util.java Sun Apr 10 10:23:28 2011 -0700
@@ -26,6 +26,7 @@
package sun.nio.fs;
import java.util.*;
+import java.nio.file.*;
/**
* Utility methods
@@ -80,4 +81,21 @@
}
return set;
}
+
+ /**
+ * Returns {@code true} if symbolic links should be followed
+ */
+ static boolean followLinks(LinkOption... options) {
+ boolean followLinks = true;
+ for (LinkOption option: options) {
+ if (option == LinkOption.NOFOLLOW_LINKS) {
+ followLinks = false;
+ } else if (option == null) {
+ throw new NullPointerException();
+ } else {
+ throw new AssertionError("Should not get here");
+ }
+ }
+ return followLinks;
+ }
}
--- a/jdk/src/share/classes/sun/security/krb5/Realm.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/Realm.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2000, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -362,19 +362,15 @@
Stack<String> iStack = new Stack<>();
/*
- * I don't expect any more than a handful of intermediaries.
+ * The half-established reversed-path, starting from the final target
+ * (sRealm), each item can be connected to by the next one.
+ * Might contains wrong item, if found, a bad track is performed
*/
Vector<String> tempList = new Vector<>(8, 8);
-
- /*
- * The initiator at first location.
- */
- tempList.add(cRealm);
+ tempList.add(sRealm);
int count = 0; // For debug only
- if (DEBUG) {
- tempTarget = sRealm;
- }
+ tempTarget = sRealm;
out: do {
if (DEBUG) {
@@ -384,8 +380,8 @@
}
if (intermediaries != null &&
- !intermediaries.equals(PrincipalName.REALM_COMPONENT_SEPARATOR_STR))
- {
+ !intermediaries.equals(".") &&
+ !intermediaries.equals(cRealm)) {
if (DEBUG) {
System.out.println(">>> Realm parseCapaths: loop " +
count + ": intermediaries=[" +
@@ -466,11 +462,15 @@
} while (true);
+ if (tempList.isEmpty()) {
+ return null;
+ }
+
+ // From (SREALM, T1, T2) to (CREALM, T2, T1)
retList = new String[tempList.size()];
- try {
- retList = tempList.toArray(retList);
- } catch (ArrayStoreException exc) {
- retList = null;
+ retList[0] = cRealm;
+ for (int i=1; i<tempList.size(); i++) {
+ retList[i] = tempList.elementAt(tempList.size()-i);
}
if (DEBUG && retList != null) {
--- a/jdk/src/share/classes/sun/security/ssl/HandshakeMessage.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/security/ssl/HandshakeMessage.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -694,47 +694,6 @@
// the preferable signature algorithm used by this ServerKeyExchange message
private SignatureAndHashAlgorithm preferableSignatureAlgorithm;
- /* Return the Diffie-Hellman modulus */
- BigInteger getModulus() {
- return new BigInteger(1, dh_p);
- }
-
- /* Return the Diffie-Hellman base/generator */
- BigInteger getBase() {
- return new BigInteger(1, dh_g);
- }
-
- /* Return the server's Diffie-Hellman public key */
- BigInteger getServerPublicKey() {
- return new BigInteger(1, dh_Ys);
- }
-
- /*
- * Update sig with nonces and Diffie-Hellman public key.
- */
- private void updateSignature(Signature sig, byte clntNonce[],
- byte svrNonce[]) throws SignatureException {
- int tmp;
-
- sig.update(clntNonce);
- sig.update(svrNonce);
-
- tmp = dh_p.length;
- sig.update((byte)(tmp >> 8));
- sig.update((byte)(tmp & 0x0ff));
- sig.update(dh_p);
-
- tmp = dh_g.length;
- sig.update((byte)(tmp >> 8));
- sig.update((byte)(tmp & 0x0ff));
- sig.update(dh_g);
-
- tmp = dh_Ys.length;
- sig.update((byte)(tmp >> 8));
- sig.update((byte)(tmp & 0x0ff));
- sig.update(dh_Ys);
- }
-
/*
* Construct from initialized DH key object, for DH_anon
* key exchange.
@@ -779,12 +738,6 @@
signature = sig.sign();
}
- private void setValues(DHCrypt obj) {
- dh_p = toByteArray(obj.getModulus());
- dh_g = toByteArray(obj.getBase());
- dh_Ys = toByteArray(obj.getPublicKey());
- }
-
/*
* Construct a DH_ServerKeyExchange message from an input
* stream, as if sent from server to client for use with
@@ -875,6 +828,53 @@
}
}
+ /* Return the Diffie-Hellman modulus */
+ BigInteger getModulus() {
+ return new BigInteger(1, dh_p);
+ }
+
+ /* Return the Diffie-Hellman base/generator */
+ BigInteger getBase() {
+ return new BigInteger(1, dh_g);
+ }
+
+ /* Return the server's Diffie-Hellman public key */
+ BigInteger getServerPublicKey() {
+ return new BigInteger(1, dh_Ys);
+ }
+
+ /*
+ * Update sig with nonces and Diffie-Hellman public key.
+ */
+ private void updateSignature(Signature sig, byte clntNonce[],
+ byte svrNonce[]) throws SignatureException {
+ int tmp;
+
+ sig.update(clntNonce);
+ sig.update(svrNonce);
+
+ tmp = dh_p.length;
+ sig.update((byte)(tmp >> 8));
+ sig.update((byte)(tmp & 0x0ff));
+ sig.update(dh_p);
+
+ tmp = dh_g.length;
+ sig.update((byte)(tmp >> 8));
+ sig.update((byte)(tmp & 0x0ff));
+ sig.update(dh_g);
+
+ tmp = dh_Ys.length;
+ sig.update((byte)(tmp >> 8));
+ sig.update((byte)(tmp & 0x0ff));
+ sig.update(dh_Ys);
+ }
+
+ private void setValues(DHCrypt obj) {
+ dh_p = toByteArray(obj.getModulus());
+ dh_g = toByteArray(obj.getBase());
+ dh_Ys = toByteArray(obj.getPublicKey());
+ }
+
int messageLength() {
int temp = 6; // overhead for p, g, y(s) values.
@@ -945,8 +945,7 @@
* We support named curves only, no explicitly encoded curves.
*/
static final
-class ECDH_ServerKeyExchange extends ServerKeyExchange
-{
+class ECDH_ServerKeyExchange extends ServerKeyExchange {
// constants for ECCurveType
private final static int CURVE_EXPLICIT_PRIME = 1;
@@ -1120,10 +1119,12 @@
}
int messageLength() {
- int sigLen = (signatureBytes == null) ? 0 : 2 + signatureBytes.length;
-
- if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
- sigLen += SignatureAndHashAlgorithm.sizeInRecord();
+ int sigLen = 0;
+ if (signatureBytes != null) {
+ sigLen = 2 + signatureBytes.length;
+ if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
+ sigLen += SignatureAndHashAlgorithm.sizeInRecord();
+ }
}
return 4 + pointBytes.length + sigLen;
@@ -1133,12 +1134,13 @@
s.putInt8(CURVE_NAMED_CURVE);
s.putInt16(curveId);
s.putBytes8(pointBytes);
- if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
- s.putInt8(preferableSignatureAlgorithm.getHashValue());
- s.putInt8(preferableSignatureAlgorithm.getSignatureValue());
- }
if (signatureBytes != null) {
+ if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
+ s.putInt8(preferableSignatureAlgorithm.getHashValue());
+ s.putInt8(preferableSignatureAlgorithm.getSignatureValue());
+ }
+
s.putBytes16(signatureBytes);
}
}
@@ -1147,9 +1149,13 @@
s.println("*** ECDH ServerKeyExchange");
if (debug != null && Debug.isOn("verbose")) {
- if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
- s.println("Signature Algorithm " +
- preferableSignatureAlgorithm.getAlgorithmName());
+ if (signatureBytes == null) {
+ s.println("Anonymous");
+ } else {
+ if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
+ s.println("Signature Algorithm " +
+ preferableSignatureAlgorithm.getAlgorithmName());
+ }
}
s.println("Server key: " + publicKey);
--- a/jdk/src/share/classes/sun/security/tools/JarSigner.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/security/tools/JarSigner.java Sun Apr 10 10:23:28 2011 -0700
@@ -1238,10 +1238,11 @@
// Provide a helpful message when TSA is beyond a firewall
error(rb.getString("unable.to.sign.jar.") +
rb.getString("no.response.from.the.Timestamping.Authority.") +
- rb.getString("When.connecting.from.behind.a.firewall.then.an.HTTP.proxy.may.need.to.be.specified.") +
- rb.getString("Supply.the.following.options.to.jarsigner.") +
- "\n -J-Dhttp.proxyHost=<hostname> " +
- "\n -J-Dhttp.proxyPort=<portnumber> ", e);
+ "\n -J-Dhttp.proxyHost=<hostname>" +
+ "\n -J-Dhttp.proxyPort=<portnumber>\n" +
+ rb.getString("or") +
+ "\n -J-Dhttps.proxyHost=<hostname> " +
+ "\n -J-Dhttps.proxyPort=<portnumber> ", e);
}
sfFilename = sf.getMetaName();
--- a/jdk/src/share/classes/sun/security/tools/JarSignerResources.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/security/tools/JarSignerResources.java Sun Apr 10 10:23:28 2011 -0700
@@ -181,11 +181,10 @@
{"TSA.location.", "TSA location: "},
{"TSA.certificate.", "TSA certificate: "},
{"no.response.from.the.Timestamping.Authority.",
- "no response from the Timestamping Authority. "},
- {"When.connecting.from.behind.a.firewall.then.an.HTTP.proxy.may.need.to.be.specified.",
- "When connecting from behind a firewall then an HTTP proxy may need to be specified. "},
- {"Supply.the.following.options.to.jarsigner.",
- "Supply the following options to jarsigner: "},
+ "no response from the Timestamping Authority. When connecting"
+ + " from behind a firewall an HTTP or HTTPS proxy may need to"
+ + " be specified. Supply the following options to jarsigner:"},
+ {"or", "or"},
{"Certificate.not.found.for.alias.alias.must.reference.a.valid.KeyStore.entry.containing.an.X.509.public.key.certificate.for.the",
"Certificate not found for: {0}. {1} must reference a valid KeyStore entry containing an X.509 public key certificate for the Timestamping Authority."},
{"using.an.alternative.signing.mechanism",
--- a/jdk/src/share/classes/sun/security/tools/KeyTool.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/security/tools/KeyTool.java Sun Apr 10 10:23:28 2011 -0700
@@ -1740,16 +1740,19 @@
KeyStore.TrustedCertificateEntry.class)) {
// We have a trusted certificate entry
Certificate cert = keyStore.getCertificate(alias);
+ Object[] source = {"trustedCertEntry"};
+ String mf = new MessageFormat(
+ rb.getString("Entry.type.type.")).format(source) + "\n";
if (verbose && (cert instanceof X509Certificate)) {
- out.println(rb.getString("Entry.type.trustedCertEntry."));
+ out.println(mf);
printX509Cert((X509Certificate)cert, out);
} else if (rfc) {
- out.println(rb.getString("Entry.type.trustedCertEntry."));
+ out.println(mf);
dumpCert(cert, out);
} else if (debug) {
out.println(cert.toString());
} else {
- out.println(rb.getString("trustedCertEntry."));
+ out.println("trustedCertEntry, ");
out.println(rb.getString("Certificate.fingerprint.SHA1.")
+ getCertFingerPrint("SHA1", cert));
}
@@ -1837,10 +1840,6 @@
System.err.println(rb.getString
(".The.integrity.of.the.information.stored.in.the.srckeystore."));
System.err.println(rb.getString
- (".has.NOT.been.verified.In.order.to.verify.its.integrity."));
- System.err.println(rb.getString
- (".you.must.provide.the.srckeystore.password."));
- System.err.println(rb.getString
(".WARNING.WARNING.WARNING."));
System.err.println();
}
@@ -3187,10 +3186,6 @@
System.err.println(rb.getString
(".The.integrity.of.the.information.stored.in.your.keystore."));
System.err.println(rb.getString
- (".has.NOT.been.verified.In.order.to.verify.its.integrity."));
- System.err.println(rb.getString
- (".you.must.provide.your.keystore.password."));
- System.err.println(rb.getString
(".WARNING.WARNING.WARNING."));
System.err.println();
}
--- a/jdk/src/share/classes/sun/security/tools/TimestampedSigner.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/security/tools/TimestampedSigner.java Sun Apr 10 10:23:28 2011 -0700
@@ -250,10 +250,10 @@
* (<a href="http://www.ietf.org/rfc/rfc3280.txt">RFC 3280</a>).
* The extension's <tt>accessMethod</tt> field should contain the object
* identifier defined for timestamping: 1.3.6.1.5.5.7.48.3 and its
- * <tt>accessLocation</tt> field should contain an HTTP URL.
+ * <tt>accessLocation</tt> field should contain an HTTP or HTTPS URL.
*
* @param tsaCertificate An X.509 certificate for the TSA.
- * @return An HTTP URL or null if none was found.
+ * @return An HTTP or HTTPS URL or null if none was found.
*/
public static String getTimestampingUrl(X509Certificate tsaCertificate) {
@@ -279,7 +279,8 @@
location = description.getAccessLocation();
if (location.getType() == GeneralNameInterface.NAME_URI) {
uri = (URIName) location.getName();
- if (uri.getScheme().equalsIgnoreCase("http")) {
+ if (uri.getScheme().equalsIgnoreCase("http") ||
+ uri.getScheme().equalsIgnoreCase("https")) {
return uri.getName();
}
}
--- a/jdk/src/share/classes/sun/security/util/AuthResources.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/security/util/AuthResources.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -111,17 +111,15 @@
// com.sun.security.auth.PolicyParser
{"expected.keystore.type", "expected keystore type"},
- {"can.not.specify.Principal.with.a.",
- "can not specify Principal with a "},
- {"wildcard.class.without.a.wildcard.name",
- "wildcard class without a wildcard name"},
+ {"can.not.specify.Principal.with.a.wildcard.class.without.a.wildcard.name",
+ "can not specify Principal with a wildcard class without a wildcard name"},
{"expected.codeBase.or.SignedBy", "expected codeBase or SignedBy"},
{"only.Principal.based.grant.entries.permitted",
"only Principal-based grant entries permitted"},
{"expected.permission.entry", "expected permission entry"},
{"number.", "number "},
- {"expected.", "expected "},
- {".read.end.of.file", ", read end of file"},
+ {"expected.expect.read.end.of.file.",
+ "expected {0}, read end of file"},
{"expected.read.end.of.file", "expected ';', read end of file"},
{"line.", "line "},
{".expected.", ": expected '"},
@@ -136,6 +134,9 @@
{"SolarisNumericUserPrincipal.",
"SolarisNumericUserPrincipal: "},
{"SolarisPrincipal.", "SolarisPrincipal: "},
+ // provided.null.name is the NullPointerException message when a
+ // developer incorrectly passes a null name to the constructor of
+ // subclasses of java.security.Principal
{"provided.null.name", "provided null name"}
};
--- a/jdk/src/share/classes/sun/security/util/ManifestEntryVerifier.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/security/util/ManifestEntryVerifier.java Sun Apr 10 10:23:28 2011 -0700
@@ -195,8 +195,7 @@
Hashtable<String, CodeSigner[]> sigFileSigners)
throws JarException
{
- // MANIFEST.MF should not be skipped. It has signers.
- if (skip && !entry.getName().equals(JarFile.MANIFEST_NAME)) {
+ if (skip) {
return null;
}
--- a/jdk/src/share/classes/sun/security/util/Resources.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/security/util/Resources.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -304,8 +304,6 @@
{"Certificate.chain.length.", "Certificate chain length: "},
{"Certificate.i.1.", "Certificate[{0,number,integer}]:"},
{"Certificate.fingerprint.SHA1.", "Certificate fingerprint (SHA1): "},
- {"Entry.type.trustedCertEntry.", "Entry type: trustedCertEntry\n"},
- {"trustedCertEntry.", "trustedCertEntry,"},
{"Keystore.type.", "Keystore type: "},
{"Keystore.provider.", "Keystore provider: "},
{"Your.keystore.contains.keyStore.size.entry",
@@ -378,21 +376,15 @@
{"No.certificate.from.the.SSL.server",
"No certificate from the SSL server"},
- // Translators of the following 5 pairs, ATTENTION:
- // the next 5 string pairs are meant to be combined into 2 paragraphs,
- // 1+3+4 and 2+3+5. make sure your translation also does.
{".The.integrity.of.the.information.stored.in.your.keystore.",
- "* The integrity of the information stored in your keystore *"},
+ "* The integrity of the information stored in your keystore *\n" +
+ "* has NOT been verified! In order to verify its integrity, *\n" +
+ "* you must provide your keystore password. *"},
{".The.integrity.of.the.information.stored.in.the.srckeystore.",
- "* The integrity of the information stored in the srckeystore*"},
- {".has.NOT.been.verified.In.order.to.verify.its.integrity.",
- "* has NOT been verified! In order to verify its integrity, *"},
- {".you.must.provide.your.keystore.password.",
- "* you must provide your keystore password. *"},
- {".you.must.provide.the.srckeystore.password.",
+ "* The integrity of the information stored in the srckeystore*\n" +
+ "* has NOT been verified! In order to verify its integrity, *\n" +
"* you must provide the srckeystore password. *"},
-
{"Certificate.reply.does.not.contain.public.key.for.alias.",
"Certificate reply does not contain public key for <{0}>"},
{"Incomplete.certificate.chain.in.reply",
--- a/jdk/src/share/classes/sun/text/bidi/BidiBase.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/text/bidi/BidiBase.java Sun Apr 10 10:23:28 2011 -0700
@@ -3457,13 +3457,18 @@
*/
static final AttributedCharacterIterator.Attribute RUN_DIRECTION =
getTextAttribute("RUN_DIRECTION");
- static final Boolean RUN_DIRECTION_LTR =
- (Boolean)getStaticField(clazz, "RUN_DIRECTION_LTR");
static final AttributedCharacterIterator.Attribute NUMERIC_SHAPING =
getTextAttribute("NUMERIC_SHAPING");
static final AttributedCharacterIterator.Attribute BIDI_EMBEDDING =
getTextAttribute("BIDI_EMBEDDING");
+ /**
+ * TextAttribute.RUN_DIRECTION_LTR
+ */
+ static final Boolean RUN_DIRECTION_LTR = (clazz == null) ?
+ Boolean.FALSE : (Boolean)getStaticField(clazz, "RUN_DIRECTION_LTR");
+
+
private static Class<?> getClass(String name) {
try {
return Class.forName(name, true, null);
@@ -3473,25 +3478,23 @@
}
private static Object getStaticField(Class<?> clazz, String name) {
- if (clazz == null) {
- // fake attribute
- return new AttributedCharacterIterator.Attribute(name) { };
- } else {
- try {
- Field f = clazz.getField(name);
- return f.get(null);
- } catch (NoSuchFieldException x) {
- throw new AssertionError(x);
- } catch (IllegalAccessException x) {
- throw new AssertionError(x);
- }
+ try {
+ Field f = clazz.getField(name);
+ return f.get(null);
+ } catch (NoSuchFieldException | IllegalAccessException x) {
+ throw new AssertionError(x);
}
}
private static AttributedCharacterIterator.Attribute
getTextAttribute(String name)
{
- return (AttributedCharacterIterator.Attribute)getStaticField(clazz, name);
+ if (clazz == null) {
+ // fake attribute
+ return new AttributedCharacterIterator.Attribute(name) { };
+ } else {
+ return (AttributedCharacterIterator.Attribute)getStaticField(clazz, name);
+ }
}
}
--- a/jdk/src/share/classes/sun/util/calendar/ZoneInfoFile.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/util/calendar/ZoneInfoFile.java Sun Apr 10 10:23:28 2011 -0700
@@ -479,7 +479,7 @@
String zi = System.getProperty("java.home") +
File.separator + "lib" + File.separator + "zi";
try {
- zi = FileSystems.getDefault().getPath(zi).toRealPath(true).toString();
+ zi = FileSystems.getDefault().getPath(zi).toRealPath().toString();
} catch(Exception e) {
}
return zi;
--- a/jdk/src/share/classes/sun/util/logging/LoggingProxy.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/util/logging/LoggingProxy.java Sun Apr 10 10:23:28 2011 -0700
@@ -60,4 +60,7 @@
public Object parseLevel(String levelName);
public String getLevelName(Object level);
+
+ // return the logging property
+ public String getProperty(String key);
}
--- a/jdk/src/share/classes/sun/util/logging/LoggingSupport.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/util/logging/LoggingSupport.java Sun Apr 10 10:23:28 2011 -0700
@@ -29,6 +29,7 @@
import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedAction;
+import java.util.Date;
/**
* Internal API to support JRE implementation to detect if the java.util.logging
@@ -138,4 +139,42 @@
ensureAvailable();
return proxy.getLevelName(level);
}
+
+ private static final String DEFAULT_FORMAT =
+ "%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%6$s%n";
+
+ private static final String FORMAT_PROP_KEY = "java.util.logging.SimpleFormatter.format";
+ public static String getSimpleFormat() {
+ return getSimpleFormat(true);
+ }
+
+ // useProxy if true will cause initialization of
+ // java.util.logging and read its configuration
+ static String getSimpleFormat(boolean useProxy) {
+ String format =
+ AccessController.doPrivileged(
+ new PrivilegedAction<String>() {
+ public String run() {
+ return System.getProperty(FORMAT_PROP_KEY);
+ }
+ });
+
+ if (useProxy && proxy != null && format == null) {
+ format = proxy.getProperty(FORMAT_PROP_KEY);
+ }
+
+ if (format != null) {
+ try {
+ // validate the user-defined format string
+ String.format(format, new Date(), "", "", "", "", "");
+ } catch (IllegalArgumentException e) {
+ // illegal syntax; fall back to the default format
+ format = DEFAULT_FORMAT;
+ }
+ } else {
+ format = DEFAULT_FORMAT;
+ }
+ return format;
+ }
+
}
--- a/jdk/src/share/classes/sun/util/logging/PlatformLogger.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/classes/sun/util/logging/PlatformLogger.java Sun Apr 10 10:23:28 2011 -0700
@@ -316,12 +316,6 @@
*/
static class LoggerProxy {
private static final PrintStream defaultStream = System.err;
- private static final String lineSeparator = AccessController.doPrivileged(
- new PrivilegedAction<String>() {
- public String run() {
- return System.getProperty("line.separator");
- }
- });
final String name;
volatile int levelValue;
@@ -353,14 +347,14 @@
if (level < levelValue || levelValue == OFF) {
return;
}
- defaultStream.println(format(level, msg, null));
+ defaultStream.print(format(level, msg, null));
}
void doLog(int level, String msg, Throwable thrown) {
if (level < levelValue || levelValue == OFF) {
return;
}
- defaultStream.println(format(level, msg, thrown));
+ defaultStream.print(format(level, msg, thrown));
}
void doLog(int level, String msg, Object... params) {
@@ -368,7 +362,7 @@
return;
}
String newMsg = formatMessage(msg, params);
- defaultStream.println(format(level, newMsg, null));
+ defaultStream.print(format(level, newMsg, null));
}
public boolean isLoggable(int level) {
@@ -378,12 +372,6 @@
return true;
}
- private static final String format = "{0,date} {0,time}";
-
- private Object args[] = new Object[1];
- private MessageFormat formatter;
- private Date dat;
-
// Copied from java.util.logging.Formatter.formatMessage
private String formatMessage(String format, Object... parameters) {
// Do the formatting.
@@ -408,37 +396,30 @@
}
}
+ private static final String formatString =
+ LoggingSupport.getSimpleFormat(false); // don't check logging.properties
+
+ // minimize memory allocation
+ private Date date = new Date();
private synchronized String format(int level, String msg, Throwable thrown) {
- StringBuffer sb = new StringBuffer();
- // Minimize memory allocations here.
- if (dat == null) {
- dat = new Date();
- formatter = new MessageFormat(format);
- }
- dat.setTime(System.currentTimeMillis());
- args[0] = dat;
- StringBuffer text = new StringBuffer();
- formatter.format(args, text, null);
- sb.append(text);
- sb.append(" ");
- sb.append(getCallerInfo());
- sb.append(lineSeparator);
- sb.append(PlatformLogger.getLevelName(level));
- sb.append(": ");
- sb.append(msg);
+ date.setTime(System.currentTimeMillis());
+ String throwable = "";
if (thrown != null) {
- try {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- thrown.printStackTrace(pw);
- pw.close();
- sb.append(sw.toString());
- } catch (Exception ex) {
- throw new AssertionError(ex);
- }
+ StringWriter sw = new StringWriter();
+ PrintWriter pw = new PrintWriter(sw);
+ pw.println();
+ thrown.printStackTrace(pw);
+ pw.close();
+ throwable = sw.toString();
}
- return sb.toString();
+ return String.format(formatString,
+ date,
+ getCallerInfo(),
+ name,
+ PlatformLogger.getLevelName(level),
+ msg,
+ throwable);
}
// Returns the caller's class and method's name; best effort
--- a/jdk/src/share/demo/applets/ArcTest/ArcTest.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/ArcTest/ArcTest.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,22 +29,24 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
+
/**
* An interactive test of the Graphics.drawArc and Graphics.fillArc
* routines. Can be run either as a standalone application by
* typing "java ArcTest" or as an applet in the AppletViewer.
*/
+@SuppressWarnings("serial")
public class ArcTest extends Applet {
+
ArcControls controls; // The controls for marking and filling arcs
ArcCanvas canvas; // The drawing area to display arcs
+ @Override
public void init() {
setLayout(new BorderLayout());
canvas = new ArcCanvas();
@@ -52,19 +54,23 @@
add("South", controls = new ArcControls(canvas));
}
+ @Override
public void destroy() {
remove(controls);
remove(canvas);
}
+ @Override
public void start() {
controls.setEnabled(true);
}
+ @Override
public void stop() {
controls.setEnabled(false);
}
+ @Override
public void processEvent(AWTEvent e) {
if (e.getID() == Event.WINDOW_DESTROY) {
System.exit(0);
@@ -80,20 +86,28 @@
f.add("Center", arcTest);
f.setSize(300, 300);
- f.show();
+ f.setVisible(true);
}
+ @Override
public String getAppletInfo() {
- return "An interactive test of the Graphics.drawArc and \nGraphics.fillArc routines. Can be run \neither as a standalone application by typing 'java ArcTest' \nor as an applet in the AppletViewer.";
+ return "An interactive test of the Graphics.drawArc and \nGraphics."
+ + "fillArc routines. Can be run \neither as a standalone "
+ + "application by typing 'java ArcTest' \nor as an applet in "
+ + "the AppletViewer.";
}
}
+
+@SuppressWarnings("serial")
class ArcCanvas extends Canvas {
- int startAngle = 0;
- int extent = 45;
- boolean filled = false;
- Font font = new java.awt.Font("SansSerif", Font.PLAIN, 12);
+ int startAngle = 0;
+ int extent = 45;
+ boolean filled = false;
+ Font font = new java.awt.Font("SansSerif", Font.PLAIN, 12);
+
+ @Override
public void paint(Graphics g) {
Rectangle r = getBounds();
int hlines = r.height / 10;
@@ -134,12 +148,16 @@
}
}
+
+@SuppressWarnings("serial")
class ArcControls extends Panel
- implements ActionListener {
+ implements ActionListener {
+
TextField startTF;
TextField extentTF;
ArcCanvas canvas;
+ @SuppressWarnings("LeakingThisInConstructor")
public ArcControls(ArcCanvas canvas) {
Button b = null;
@@ -154,18 +172,19 @@
add(b);
}
+ @Override
public void actionPerformed(ActionEvent ev) {
String label = ev.getActionCommand();
int start, extent;
try {
start = Integer.parseInt(startTF.getText().trim());
- } catch (NumberFormatException nfe) {
+ } catch (NumberFormatException ignored) {
start = 0;
}
try {
extent = Integer.parseInt(extentTF.getText().trim());
- } catch (NumberFormatException nfe) {
+ } catch (NumberFormatException ignored) {
extent = 0;
}
@@ -173,6 +192,8 @@
}
}
+
+@SuppressWarnings("serial")
class IntegerTextField extends TextField {
String oldText = null;
@@ -188,6 +209,7 @@
// function, but this is neater, since ideally, it would prevent
// the text from appearing at all. Sigh. See bugid 4100317/4114565.
//
+ @Override
protected void processEvent(AWTEvent evt) {
int id = evt.getID();
if (id != KeyEvent.KEY_TYPED) {
@@ -200,8 +222,8 @@
// Digits, backspace, and delete are okay
// Note that the minus sign is allowed, but not the decimal
- if (Character.isDigit(c) || (c == '\b') || (c == '\u007f') ||
- (c == '\u002d')) {
+ if (Character.isDigit(c) || (c == '\b') || (c == '\u007f') || (c
+ == '\u002d')) {
super.processEvent(evt);
return;
}
@@ -215,6 +237,7 @@
// so we can revert to it on a TextEvent (paste, or
// legal key in the wrong location) with bad text
//
+ @Override
protected void processTextEvent(TextEvent te) {
// The empty string is okay, too
String newText = getText();
@@ -233,12 +256,11 @@
// Note that the empty string is not allowed.
//
private boolean textIsInteger(String textToCheck) {
- int value = -1;
try {
- value = Integer.parseInt(textToCheck, 10);
+ Integer.parseInt(textToCheck, 10);
return true;
- } catch (NumberFormatException nfe) {
+ } catch (NumberFormatException ignored) {
return false;
}
}
--- a/jdk/src/share/demo/applets/BarChart/BarChart.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/BarChart/BarChart.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,28 +29,26 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
import java.awt.*;
+
/**
* A simple bar chart demo
* @author Sami Shaio
* @modified 06/21/00 Daniel Peek : refactored, comments
*/
+@SuppressWarnings("serial")
public class BarChart extends java.applet.Applet {
+
private static final int VERTICAL = 0;
private static final int HORIZONTAL = 1;
-
private static final int SOLID = 0;
private static final int STRIPED = 1;
-
private int orientation;
private String title;
private Font font;
private FontMetrics metrics;
- private int fontHeight = 15;
private int columns;
private int values[];
private Color colors[];
@@ -61,6 +59,7 @@
private int barSpacing = 10;
private int maxValue = 0;
+ @Override
public void init() {
getSettings();
@@ -70,7 +69,7 @@
styles = new int[columns];
colors = new Color[columns];
- for (int i=0; i < columns; i++) {
+ for (int i = 0; i < columns; i++) {
parseValue(i);
parseLabel(i);
parseStyle(i);
@@ -112,7 +111,7 @@
}
private void parseValue(int i) {
- String temp = getParameter("C" + (i+1));
+ String temp = getParameter("C" + (i + 1));
try {
values[i] = Integer.parseInt(temp);
} catch (NumberFormatException e) {
@@ -124,18 +123,17 @@
}
private void parseLabel(int i) {
- String temp = getParameter("C" + (i+1) + "_label");
- if (temp==null) {
+ String temp = getParameter("C" + (i + 1) + "_label");
+ if (temp == null) {
labels[i] = "";
} else {
labels[i] = temp;
}
- maxLabelWidth = Math.max(metrics.stringWidth
- ((String) (labels[i])), maxLabelWidth);
+ maxLabelWidth = Math.max(metrics.stringWidth(labels[i]), maxLabelWidth);
}
private void parseStyle(int i) {
- String temp = getParameter("C" + (i+1) + "_style");
+ String temp = getParameter("C" + (i + 1) + "_style");
if (temp == null || temp.equalsIgnoreCase("solid")) {
styles[i] = SOLID;
} else if (temp.equalsIgnoreCase("striped")) {
@@ -146,7 +144,7 @@
}
private void parseColor(int i) {
- String temp = getParameter("C" + (i+1) + "_color");
+ String temp = getParameter("C" + (i + 1) + "_color");
if (temp != null) {
temp = temp.toLowerCase();
if (temp.equals("red")) {
@@ -179,6 +177,7 @@
}
}
+ @Override
public void paint(Graphics g) {
// draw the title centered at the bottom of the bar graph
g.setColor(Color.black);
@@ -192,7 +191,7 @@
g.drawString(title, cx, cy);
// draw the bars and their titles
- if(orientation == HORIZONTAL) {
+ if (orientation == HORIZONTAL) {
paintHorizontal(g);
} else { // VERTICAL
paintVertical(g);
@@ -208,12 +207,13 @@
// set the X coordinate for this bar and label and center it
int widthOfItems = maxLabelWidth + 3 + (maxValue * scale) + 5
- + metrics.stringWidth(Integer.toString(maxValue));
+ + metrics.stringWidth(Integer.toString(maxValue));
cx = Math.max((getSize().width - widthOfItems) / 2, 0);
// set the Y coordinate for this bar and label
cy = getSize().height - metrics.getDescent() - metrics.getHeight()
- - barSpacing - ((columns - i - 1) * (barSpacing + barHeight));
+ - barSpacing
+ - ((columns - i - 1) * (barSpacing + barHeight));
// draw the label
g.setColor(Color.black);
@@ -223,7 +223,7 @@
// draw the shadow
g.fillRect(cx + 4, cy - barHeight + 4,
- (values[i] * scale), barHeight);
+ (values[i] * scale), barHeight);
// draw the bar
g.setColor(colors[i]);
@@ -233,7 +233,7 @@
}
} else { // SOLID
g.fillRect(cx, cy - barHeight,
- (values[i] * scale) + 1, barHeight + 1);
+ (values[i] * scale) + 1, barHeight + 1);
}
cx += (values[i] * scale) + 4;
@@ -255,7 +255,7 @@
// Y coordinate for this label and bar
int cy = getSize().height - metrics.getHeight()
- - metrics.getDescent() - 4;
+ - metrics.getDescent() - 4;
// draw the label
g.setColor(Color.black);
@@ -264,18 +264,18 @@
// draw the shadow
g.fillRect(cx + 4, cy - (values[i] * scale) - 4,
- barWidth, (values[i] * scale));
+ barWidth, (values[i] * scale));
// draw the bar
g.setColor(colors[i]);
if (styles[i] == STRIPED) {
- for (int k=0; k <= values[i] * scale; k+=2) {
+ for (int k = 0; k <= values[i] * scale; k += 2) {
g.drawLine(cx, cy - k,
- cx + barWidth, cy - k);
+ cx + barWidth, cy - k);
}
} else {
g.fillRect(cx, cy - (values[i] * scale),
- barWidth + 1, (values[i] * scale) + 1);
+ barWidth + 1, (values[i] * scale) + 1);
}
cy -= (values[i] * scale) + 5;
@@ -285,28 +285,30 @@
}
}
+ @Override
public String getAppletInfo() {
return "Title: Bar Chart \n"
- + "Author: Sami Shaio \n"
- + "A simple bar chart demo.";
+ + "Author: Sami Shaio \n"
+ + "A simple bar chart demo.";
}
+ @Override
public String[][] getParameterInfo() {
String[][] info = {
- {"title", "string", "The title of bar graph. Default is 'Chart'"},
- {"scale", "int", "The scale of the bar graph. Default is 10."},
- {"columns", "int", "The number of columns/rows. Default is 5."},
- {"orientation", "{VERTICAL, HORIZONTAL}",
- "The orienation of the bar graph. Default is VERTICAL."},
- {"c#", "int", "Subsitute a number for #. "
- + "The value/size of bar #. Default is 0."},
- {"c#_label", "string", "The label for bar #. "
- + "Default is an empty label."},
- {"c#_style", "{SOLID, STRIPED}", "The style of bar #. "
- + "Default is SOLID."},
- {"c#_color", "{RED, GREEN, BLUE, PINK, ORANGE, MAGENTA, CYAN, "
- + "WHITE, YELLOW, GRAY, DARKGRAY}",
- "The color of bar #. Default is GRAY."}
+ { "title", "string", "The title of bar graph. Default is 'Chart'" },
+ { "scale", "int", "The scale of the bar graph. Default is 10." },
+ { "columns", "int", "The number of columns/rows. Default is 5." },
+ { "orientation", "{VERTICAL, HORIZONTAL}",
+ "The orienation of the bar graph. Default is VERTICAL." },
+ { "c#", "int", "Subsitute a number for #. "
+ + "The value/size of bar #. Default is 0." },
+ { "c#_label", "string", "The label for bar #. "
+ + "Default is an empty label." },
+ { "c#_style", "{SOLID, STRIPED}", "The style of bar #. "
+ + "Default is SOLID." },
+ { "c#_color", "{RED, GREEN, BLUE, PINK, ORANGE, MAGENTA, CYAN, "
+ + "WHITE, YELLOW, GRAY, DARKGRAY}",
+ "The color of bar #. Default is GRAY." }
};
return info;
}
--- a/jdk/src/share/demo/applets/Blink/Blink.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/Blink/Blink.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,92 +29,106 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
/**
* I love blinking things.
*
* @author Arthur van Hoff
- * @modified 04/24/96 Jim Hagen use getBackground
- * @modified 02/05/98 Mike McCloskey removed use of deprecated methods
- * @modified 04/23/99 Josh Bloch, use timer instead of explicit multithreading.
- * @modified 07/10/00 Daniel Peek brought to code conventions, minor changes
+ * @author 04/24/96 Jim Hagen use getBackground
+ * @author 02/05/98 Mike McCloskey removed use of deprecated methods
+ * @author 04/23/99 Josh Bloch, use timer instead of explicit multithreading.
+ * @author 07/10/00 Daniel Peek brought to code conventions, minor changes
*/
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Graphics;
+import java.util.StringTokenizer;
+import java.util.Timer;
+import java.util.TimerTask;
-import java.awt.*;
-import java.util.*;
public class Blink extends java.applet.Applet {
+
+ private static final long serialVersionUID = -775844794477507646L;
private Timer timer; // Schedules the blinking
private String labelString; // The label for the window
private int delay; // the delay time between blinks
+ @Override
public void init() {
String blinkFrequency = getParameter("speed");
- delay = (blinkFrequency == null) ? 400 :
- (1000 / Integer.parseInt(blinkFrequency));
+ delay = (blinkFrequency == null) ? 400
+ : (1000 / Integer.parseInt(blinkFrequency));
labelString = getParameter("lbl");
- if (labelString == null)
+ if (labelString == null) {
labelString = "Blink";
+ }
Font font = new java.awt.Font("Serif", Font.PLAIN, 24);
setFont(font);
}
+ @Override
public void start() {
timer = new Timer(); //creates a new timer to schedule the blinking
timer.schedule(new TimerTask() { //creates a timertask to schedule
+
// overrides the run method to provide functionality
+ @Override
public void run() {
repaint();
}
- }
- , delay, delay);
+ }, delay, delay);
}
+ @Override
public void paint(Graphics g) {
int fontSize = g.getFont().getSize();
int x = 0, y = fontSize, space;
- int red = (int) ( 50 * Math.random());
- int green = (int) ( 50 * Math.random());
- int blue = (int) (256 * Math.random());
+ int red = (int) (50 * Math.random());
+ int green = (int) (50 * Math.random());
+ int blue = (int) (256 * Math.random());
Dimension d = getSize();
g.setColor(Color.black);
FontMetrics fm = g.getFontMetrics();
space = fm.stringWidth(" ");
for (StringTokenizer t = new StringTokenizer(labelString);
- t.hasMoreTokens();) {
+ t.hasMoreTokens();) {
String word = t.nextToken();
int w = fm.stringWidth(word) + space;
if (x + w > d.width) {
x = 0;
y += fontSize; //move word to next line if it doesn't fit
}
- if (Math.random() < 0.5)
- g.setColor(new java.awt.Color((red + y*30) % 256,
- (green + x/3) % 256, blue));
- else
+ if (Math.random() < 0.5) {
+ g.setColor(new java.awt.Color((red + y * 30) % 256,
+ (green + x / 3) % 256, blue));
+ } else {
g.setColor(getBackground());
+ }
g.drawString(word, x, y);
x += w; //shift to the right to draw the next word
}
}
+ @Override
public void stop() {
timer.cancel(); //stops the timer
}
+ @Override
public String getAppletInfo() {
return "Title: Blinker\n"
- + "Author: Arthur van Hoff\n"
- + "Displays multicolored blinking text.";
+ + "Author: Arthur van Hoff\n"
+ + "Displays multicolored blinking text.";
}
+ @Override
public String[][] getParameterInfo() {
String pinfo[][] = {
- {"speed", "string", "The blink frequency"},
- {"lbl", "string", "The text to blink."},
- };
+ { "speed", "string", "The blink frequency" },
+ { "lbl", "string", "The text to blink." }, };
return pinfo;
}
}
--- a/jdk/src/share/demo/applets/CardTest/CardTest.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/CardTest/CardTest.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,14 +29,27 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import java.awt.*;
-import java.awt.event.*;
import java.applet.Applet;
+import java.awt.BorderLayout;
+import java.awt.Button;
+import java.awt.CardLayout;
+import java.awt.Choice;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.Frame;
+import java.awt.GridLayout;
+import java.awt.LayoutManager;
+import java.awt.Panel;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
-class CardPanel extends Panel {
+
+@SuppressWarnings("serial")
+final class CardPanel extends Panel {
+
ActionListener listener;
Panel create(LayoutManager layout) {
@@ -83,16 +96,21 @@
add("six", create(new GridLayout(2, 2, 10, 10)));
}
+ @Override
public Dimension getPreferredSize() {
return new Dimension(200, 100);
}
}
+
+@SuppressWarnings("serial")
public class CardTest extends Applet
- implements ActionListener,
- ItemListener {
+ implements ActionListener,
+ ItemListener {
+
CardPanel cards;
+ @SuppressWarnings("LeakingThisInConstructor")
public CardTest() {
setLayout(new BorderLayout());
add("Center", cards = new CardPanel(this));
@@ -127,24 +145,26 @@
p.add(c);
}
+ @Override
public void itemStateChanged(ItemEvent e) {
- ((CardLayout)cards.getLayout()).show(cards,
- (String)(e.getItem()));
+ ((CardLayout) cards.getLayout()).show(cards,
+ (String) (e.getItem()));
}
+ @Override
public void actionPerformed(ActionEvent e) {
String arg = e.getActionCommand();
if ("first".equals(arg)) {
- ((CardLayout)cards.getLayout()).first(cards);
+ ((CardLayout) cards.getLayout()).first(cards);
} else if ("next".equals(arg)) {
- ((CardLayout)cards.getLayout()).next(cards);
+ ((CardLayout) cards.getLayout()).next(cards);
} else if ("previous".equals(arg)) {
- ((CardLayout)cards.getLayout()).previous(cards);
+ ((CardLayout) cards.getLayout()).previous(cards);
} else if ("last".equals(arg)) {
- ((CardLayout)cards.getLayout()).last(cards);
+ ((CardLayout) cards.getLayout()).last(cards);
} else {
- ((CardLayout)cards.getLayout()).show(cards,(String)arg);
+ ((CardLayout) cards.getLayout()).show(cards, arg);
}
}
@@ -156,9 +176,10 @@
f.add("Center", cardTest);
f.setSize(300, 300);
- f.show();
+ f.setVisible(true);
}
+ @Override
public String getAppletInfo() {
return "Demonstrates the different types of layout managers.";
}
--- a/jdk/src/share/demo/applets/Clock/Clock.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/Clock/Clock.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,24 +29,28 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import java.util.*;
-import java.awt.*;
-import java.applet.*;
-import java.text.*;
+import java.applet.Applet;
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Locale;
+
/**
* Time!
*
* @author Rachel Gollub
- * @modified Daniel Peek replaced circle drawing calculation, few more changes
+ * @author Daniel Peek replaced circle drawing calculation, few more changes
*/
+@SuppressWarnings("serial")
public class Clock extends Applet implements Runnable {
+
private volatile Thread timer; // The thread that displays clock
private int lastxs, lastys, lastxm,
- lastym, lastxh, lastyh; // Dimensions used to draw hands
+ lastym, lastxh, lastyh; // Dimensions used to draw hands
private SimpleDateFormat formatter; // Formats the date displayed
private String lastdate; // String to hold date displayed
private Font clockFaceFont; // Font for number display on clock
@@ -55,11 +59,11 @@
private Color numberColor; // Color of second hand and numbers
private int xcenter = 80, ycenter = 55; // Center position
+ @Override
public void init() {
- int x,y;
lastxs = lastys = lastxm = lastym = lastxh = lastyh = 0;
- formatter = new SimpleDateFormat ("EEE MMM dd hh:mm:ss yyyy",
- Locale.getDefault());
+ formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy",
+ Locale.getDefault());
currentDate = new Date();
lastdate = formatter.format(currentDate);
clockFaceFont = new Font("Serif", Font.PLAIN, 14);
@@ -68,26 +72,29 @@
try {
setBackground(new Color(Integer.parseInt(getParameter("bgcolor"),
- 16)));
+ 16)));
} catch (NullPointerException e) {
} catch (NumberFormatException e) {
}
try {
handColor = new Color(Integer.parseInt(getParameter("fgcolor1"),
- 16));
+ 16));
} catch (NullPointerException e) {
} catch (NumberFormatException e) {
}
try {
numberColor = new Color(Integer.parseInt(getParameter("fgcolor2"),
- 16));
+ 16));
} catch (NullPointerException e) {
} catch (NumberFormatException e) {
}
- resize(300,300); // Set clock window size
+ resize(300, 300); // Set clock window size
}
- // Paint is the main part of the program
+ /**
+ * Paint is the main part of the program
+ */
+ @Override
public void update(Graphics g) {
int xh, yh, xm, ym, xs, ys;
int s = 0, m = 10, h = 10;
@@ -119,10 +126,12 @@
ys = (int) (Math.sin(s * Math.PI / 30 - Math.PI / 2) * 45 + ycenter);
xm = (int) (Math.cos(m * Math.PI / 30 - Math.PI / 2) * 40 + xcenter);
ym = (int) (Math.sin(m * Math.PI / 30 - Math.PI / 2) * 40 + ycenter);
- xh = (int) (Math.cos((h*30 + m / 2) * Math.PI / 180 - Math.PI / 2) * 30
- + xcenter);
- yh = (int) (Math.sin((h*30 + m / 2) * Math.PI / 180 - Math.PI / 2) * 30
- + ycenter);
+ xh = (int) (Math.cos((h * 30 + m / 2) * Math.PI / 180 - Math.PI / 2)
+ * 30
+ + xcenter);
+ yh = (int) (Math.sin((h * 30 + m / 2) * Math.PI / 180 - Math.PI / 2)
+ * 30
+ + ycenter);
// Get the date to print at the bottom
formatter.applyPattern("EEE MMM dd HH:mm:ss yyyy");
@@ -136,12 +145,12 @@
g.drawString(lastdate, 5, 125);
}
if (xm != lastxm || ym != lastym) {
- g.drawLine(xcenter, ycenter-1, lastxm, lastym);
- g.drawLine(xcenter-1, ycenter, lastxm, lastym);
+ g.drawLine(xcenter, ycenter - 1, lastxm, lastym);
+ g.drawLine(xcenter - 1, ycenter, lastxm, lastym);
}
if (xh != lastxh || yh != lastyh) {
- g.drawLine(xcenter, ycenter-1, lastxh, lastyh);
- g.drawLine(xcenter-1, ycenter, lastxh, lastyh);
+ g.drawLine(xcenter, ycenter - 1, lastxh, lastyh);
+ g.drawLine(xcenter - 1, ycenter, lastxh, lastyh);
}
// Draw date and hands
@@ -149,73 +158,83 @@
g.drawString(today, 5, 125);
g.drawLine(xcenter, ycenter, xs, ys);
g.setColor(handColor);
- g.drawLine(xcenter, ycenter-1, xm, ym);
- g.drawLine(xcenter-1, ycenter, xm, ym);
- g.drawLine(xcenter, ycenter-1, xh, yh);
- g.drawLine(xcenter-1, ycenter, xh, yh);
- lastxs = xs; lastys = ys;
- lastxm = xm; lastym = ym;
- lastxh = xh; lastyh = yh;
+ g.drawLine(xcenter, ycenter - 1, xm, ym);
+ g.drawLine(xcenter - 1, ycenter, xm, ym);
+ g.drawLine(xcenter, ycenter - 1, xh, yh);
+ g.drawLine(xcenter - 1, ycenter, xh, yh);
+ lastxs = xs;
+ lastys = ys;
+ lastxm = xm;
+ lastym = ym;
+ lastxh = xh;
+ lastyh = yh;
lastdate = today;
currentDate = null;
}
+ @Override
public void paint(Graphics g) {
g.setFont(clockFaceFont);
// Draw the circle and numbers
g.setColor(handColor);
- g.drawArc(xcenter-50, ycenter-50, 100, 100, 0, 360);
+ g.drawArc(xcenter - 50, ycenter - 50, 100, 100, 0, 360);
g.setColor(numberColor);
- g.drawString("9", xcenter-45, ycenter+3);
- g.drawString("3", xcenter+40, ycenter+3);
- g.drawString("12", xcenter-5, ycenter-37);
- g.drawString("6", xcenter-3, ycenter+45);
+ g.drawString("9", xcenter - 45, ycenter + 3);
+ g.drawString("3", xcenter + 40, ycenter + 3);
+ g.drawString("12", xcenter - 5, ycenter - 37);
+ g.drawString("6", xcenter - 3, ycenter + 45);
// Draw date and hands
g.setColor(numberColor);
g.drawString(lastdate, 5, 125);
g.drawLine(xcenter, ycenter, lastxs, lastys);
g.setColor(handColor);
- g.drawLine(xcenter, ycenter-1, lastxm, lastym);
- g.drawLine(xcenter-1, ycenter, lastxm, lastym);
- g.drawLine(xcenter, ycenter-1, lastxh, lastyh);
- g.drawLine(xcenter-1, ycenter, lastxh, lastyh);
+ g.drawLine(xcenter, ycenter - 1, lastxm, lastym);
+ g.drawLine(xcenter - 1, ycenter, lastxm, lastym);
+ g.drawLine(xcenter, ycenter - 1, lastxh, lastyh);
+ g.drawLine(xcenter - 1, ycenter, lastxh, lastyh);
}
+ @Override
public void start() {
timer = new Thread(this);
timer.start();
}
+ @Override
public void stop() {
timer = null;
}
+ @Override
+ @SuppressWarnings("SleepWhileHoldingLock")
public void run() {
Thread me = Thread.currentThread();
while (timer == me) {
try {
- Thread.currentThread().sleep(100);
+ Thread.sleep(100);
} catch (InterruptedException e) {
}
repaint();
}
}
+ @Override
public String getAppletInfo() {
return "Title: A Clock \n"
- + "Author: Rachel Gollub, 1995 \n"
- + "An analog clock.";
+ + "Author: Rachel Gollub, 1995 \n"
+ + "An analog clock.";
}
+ @Override
public String[][] getParameterInfo() {
String[][] info = {
- {"bgcolor", "hexadecimal RGB number",
- "The background color. Default is the color of your browser."},
- {"fgcolor1", "hexadecimal RGB number",
- "The color of the hands and dial. Default is blue."},
- {"fgcolor2", "hexadecimal RGB number",
- "The color of the second hand and numbers. Default is dark gray."}
+ { "bgcolor", "hexadecimal RGB number",
+ "The background color. Default is the color of your browser." },
+ { "fgcolor1", "hexadecimal RGB number",
+ "The color of the hands and dial. Default is blue." },
+ { "fgcolor2", "hexadecimal RGB number",
+ "The color of the second hand and numbers. Default is dark gray." }
};
return info;
}
--- a/jdk/src/share/demo/applets/DitherTest/DitherTest.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/DitherTest/DitherTest.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,25 +29,43 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
import java.applet.Applet;
-import java.awt.event.*;
-import java.awt.*;
+import java.awt.AWTEvent;
+import java.awt.BorderLayout;
+import java.awt.Button;
+import java.awt.Canvas;
+import java.awt.Choice;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.FontMetrics;
+import java.awt.Frame;
+import java.awt.Graphics;
+import java.awt.Image;
+import java.awt.Label;
+import java.awt.LayoutManager;
+import java.awt.Panel;
+import java.awt.TextField;
+import java.awt.Toolkit;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.KeyEvent;
+import java.awt.event.TextEvent;
import java.awt.image.ColorModel;
import java.awt.image.MemoryImageSource;
+
+enum DitherMethod {
+
+ NOOP, RED, GREEN, BLUE, ALPHA, SATURATION
+};
+
+
+@SuppressWarnings("serial")
public class DitherTest extends Applet implements Runnable {
- final private static int NOOP = 0;
- final private static int RED = 1;
- final private static int GREEN = 2;
- final private static int BLUE = 3;
- final private static int ALPHA = 4;
- final private static int SATURATION = 5;
private Thread runner;
-
private DitherControls XControls;
private DitherControls YControls;
private DitherCanvas canvas;
@@ -62,6 +80,7 @@
ditherTest.start();
}
+ @Override
public void init() {
String xspec = null, yspec = null;
int xvals[] = new int[2];
@@ -70,7 +89,7 @@
try {
xspec = getParameter("xaxis");
yspec = getParameter("yaxis");
- } catch (NullPointerException npe) {
+ } catch (NullPointerException ignored) {
//only occurs if run as application
}
@@ -80,44 +99,34 @@
if (yspec == null) {
yspec = "blue";
}
- int xmethod = colormethod(xspec, xvals);
- int ymethod = colormethod(yspec, yvals);
+ DitherMethod xmethod = colorMethod(xspec, xvals);
+ DitherMethod ymethod = colorMethod(yspec, yvals);
setLayout(new BorderLayout());
XControls = new DitherControls(this, xvals[0], xvals[1],
- xmethod, false);
+ xmethod, false);
YControls = new DitherControls(this, yvals[0], yvals[1],
- ymethod, true);
+ ymethod, true);
YControls.addRenderButton();
add("North", XControls);
add("South", YControls);
add("Center", canvas = new DitherCanvas());
}
- private int colormethod(String s, int vals[]) {
- int method = NOOP;
+ private DitherMethod colorMethod(String s, int vals[]) {
+ DitherMethod method = DitherMethod.NOOP;
if (s == null) {
s = "";
}
String lower = s.toLowerCase();
- int len = 0;
- if (lower.startsWith("red")) {
- method = RED;
- lower = lower.substring(3);
- } else if (lower.startsWith("green")) {
- method = GREEN;
- lower = lower.substring(5);
- } else if (lower.startsWith("blue")) {
- method = BLUE;
- lower = lower.substring(4);
- } else if (lower.startsWith("alpha")) {
- method = ALPHA;
- lower = lower.substring(5);
- } else if (lower.startsWith("saturation")) {
- method = SATURATION;
- lower = lower.substring(10);
+
+ for (DitherMethod m : DitherMethod.values()) {
+ if (lower.startsWith(m.toString().toLowerCase())) {
+ method = m;
+ lower = lower.substring(m.toString().length());
+ }
}
- if (method == NOOP) {
+ if (method == DitherMethod.NOOP) {
vals[0] = 0;
vals[1] = 0;
return method;
@@ -132,7 +141,7 @@
begval = Integer.parseInt(lower.substring(0, dash));
endval = Integer.parseInt(lower.substring(dash + 1));
}
- } catch (NumberFormatException nfe) {
+ } catch (NumberFormatException ignored) {
}
if (begval < 0) {
@@ -173,16 +182,14 @@
c[0] = c[1] = c[2] = 0;
c[3] = 255;
if (xmethod < ymethod) {
- applymethod(c, xmethod, i, width, xvals);
- applymethod(c, ymethod, j, height, yvals);
+ applyMethod(c, xmethod, i, width, xvals);
+ applyMethod(c, ymethod, j, height, yvals);
} else {
- applymethod(c, ymethod, j, height, yvals);
- applymethod(c, xmethod, i, width, xvals);
+ applyMethod(c, ymethod, j, height, yvals);
+ applyMethod(c, xmethod, i, width, xvals);
}
- pixels[index++] = ((c[3] << 24) |
- (c[0] << 16) |
- (c[1] << 8) |
- c[2]);
+ pixels[index++] = ((c[3] << 24) | (c[0] << 16) | (c[1] << 8)
+ | c[2]);
}
// Poll once per row to see if we've been told to stop.
@@ -191,51 +198,54 @@
}
}
return createImage(new MemoryImageSource(width, height,
- ColorModel.getRGBdefault(), pixels, 0, width));
+ ColorModel.getRGBdefault(), pixels, 0, width));
}
- private void applymethod(int c[], int method, int step,
- int total, int vals[]) {
- if (method == NOOP) {
+ private void applyMethod(int c[], int methodIndex, int step,
+ int total, int vals[]) {
+ DitherMethod method = DitherMethod.values()[methodIndex];
+ if (method == DitherMethod.NOOP) {
return;
}
int val = ((total < 2)
- ? vals[0]
- : vals[0] + ((vals[1] - vals[0]) * step / (total - 1)));
+ ? vals[0]
+ : vals[0] + ((vals[1] - vals[0]) * step / (total - 1)));
switch (method) {
- case RED:
- c[0] = val;
- break;
- case GREEN:
- c[1] = val;
- break;
- case BLUE:
- c[2] = val;
- break;
- case ALPHA:
- c[3] = val;
- break;
- case SATURATION:
- int max = Math.max(Math.max(c[0], c[1]), c[2]);
- int min = max * (255 - val) / 255;
- if (c[0] == 0) {
- c[0] = min;
- }
- if (c[1] == 0) {
- c[1] = min;
- }
- if (c[2] == 0) {
- c[2] = min;
- }
- break;
+ case RED:
+ c[0] = val;
+ break;
+ case GREEN:
+ c[1] = val;
+ break;
+ case BLUE:
+ c[2] = val;
+ break;
+ case ALPHA:
+ c[3] = val;
+ break;
+ case SATURATION:
+ int max = Math.max(Math.max(c[0], c[1]), c[2]);
+ int min = max * (255 - val) / 255;
+ if (c[0] == 0) {
+ c[0] = min;
+ }
+ if (c[1] == 0) {
+ c[1] = min;
+ }
+ if (c[2] == 0) {
+ c[2] = min;
+ }
+ break;
}
}
+ @Override
public void start() {
runner = new Thread(this);
runner.start();
}
+ @Override
public void run() {
canvas.setImage(null); // Wipe previous image
Image img = calculateImage();
@@ -244,35 +254,43 @@
}
}
+ @Override
public void stop() {
runner = null;
}
+ @Override
public void destroy() {
remove(XControls);
remove(YControls);
remove(canvas);
}
+ @Override
public String getAppletInfo() {
return "An interactive demonstration of dithering.";
}
+ @Override
public String[][] getParameterInfo() {
String[][] info = {
- {"xaxis", "{RED, GREEN, BLUE, ALPHA, SATURATION}",
- "The color of the Y axis. Default is RED."},
- {"yaxis", "{RED, GREEN, BLUE, ALPHA, SATURATION}",
- "The color of the X axis. Default is BLUE."}
+ { "xaxis", "{RED, GREEN, BLUE, ALPHA, SATURATION}",
+ "The color of the Y axis. Default is RED." },
+ { "yaxis", "{RED, GREEN, BLUE, ALPHA, SATURATION}",
+ "The color of the X axis. Default is BLUE." }
};
return info;
}
}
+
+@SuppressWarnings("serial")
class DitherCanvas extends Canvas {
+
private Image img;
private static String calcString = "Calculating...";
+ @Override
public void paint(Graphics g) {
int w = getSize().width;
int h = getSize().height;
@@ -288,14 +306,17 @@
}
}
+ @Override
public void update(Graphics g) {
paint(g);
}
+ @Override
public Dimension getMinimumSize() {
return new Dimension(20, 20);
}
+ @Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@@ -310,29 +331,29 @@
}
}
+
+@SuppressWarnings("serial")
class DitherControls extends Panel implements ActionListener {
+
private CardinalTextField start;
private CardinalTextField end;
private Button button;
private Choice choice;
private DitherTest applet;
+ private static LayoutManager dcLayout = new FlowLayout(FlowLayout.CENTER,
+ 10, 5);
- private static LayoutManager dcLayout = new FlowLayout(FlowLayout.CENTER,
- 10, 5);
-
- public DitherControls(DitherTest app, int s, int e, int type,
- boolean vertical) {
+ public DitherControls(DitherTest app, int s, int e, DitherMethod type,
+ boolean vertical) {
applet = app;
setLayout(dcLayout);
add(new Label(vertical ? "Vertical" : "Horizontal"));
add(choice = new Choice());
- choice.addItem("Noop");
- choice.addItem("Red");
- choice.addItem("Green");
- choice.addItem("Blue");
- choice.addItem("Alpha");
- choice.addItem("Saturation");
- choice.select(type);
+ for (DitherMethod m : DitherMethod.values()) {
+ choice.addItem(m.toString().substring(0, 1)
+ + m.toString().substring(1).toLowerCase());
+ }
+ choice.select(type.ordinal());
add(start = new CardinalTextField(Integer.toString(s), 4));
add(end = new CardinalTextField(Integer.toString(e), 4));
}
@@ -369,6 +390,7 @@
}
/* called when user clicks the button */
+ @Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
applet.start();
@@ -376,6 +398,8 @@
}
}
+
+@SuppressWarnings("serial")
class CardinalTextField extends TextField {
String oldText = null;
@@ -391,6 +415,7 @@
// function, but this is neater, since ideally, it would prevent
// the text from appearing at all. Sigh. See bugid 4100317/4114565.
//
+ @Override
protected void processEvent(AWTEvent evt) {
int id = evt.getID();
if (id != KeyEvent.KEY_TYPED) {
@@ -420,6 +445,7 @@
// Note: it would be easy to extend this to an eight-bit
// TextField (range 0-255), but I'll leave it as-is.
//
+ @Override
protected void processTextEvent(TextEvent te) {
// The empty string is okay, too
String newText = getText();
@@ -436,11 +462,8 @@
// Returns true for Cardinal (non-negative) numbers
// Note that the empty string is not allowed
private boolean textIsCardinal(String textToCheck) {
- int value = -1;
-
try {
- value = Integer.parseInt(textToCheck, 10);
- return (value >= 0);
+ return Integer.parseInt(textToCheck, 10) >= 0;
} catch (NumberFormatException nfe) {
return false;
}
--- a/jdk/src/share/demo/applets/DrawTest/DrawTest.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/DrawTest/DrawTest.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,27 +29,46 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import java.awt.event.*;
-import java.awt.*;
-import java.applet.*;
+import java.applet.Applet;
+import java.awt.BorderLayout;
+import java.awt.Checkbox;
+import java.awt.CheckboxGroup;
+import java.awt.Choice;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.Frame;
+import java.awt.Graphics;
+import java.awt.Panel;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.MouseMotionListener;
+import java.util.ArrayList;
+import java.util.List;
-import java.util.Vector;
-public class DrawTest extends Applet{
+@SuppressWarnings("serial")
+public class DrawTest extends Applet {
+
DrawPanel panel;
DrawControls controls;
+ @Override
public void init() {
setLayout(new BorderLayout());
panel = new DrawPanel();
controls = new DrawControls(panel);
add("Center", panel);
- add("South",controls);
+ add("South", controls);
}
+ @Override
public void destroy() {
remove(panel);
remove(controls);
@@ -63,22 +82,28 @@
f.add("Center", drawTest);
f.setSize(300, 300);
- f.show();
+ f.setVisible(true);
}
+
+ @Override
public String getAppletInfo() {
return "A simple drawing program.";
}
}
+
+@SuppressWarnings("serial")
class DrawPanel extends Panel implements MouseListener, MouseMotionListener {
+
public static final int LINES = 0;
public static final int POINTS = 1;
- int mode = LINES;
- Vector lines = new Vector();
- Vector colors = new Vector();
- int x1,y1;
- int x2,y2;
+ int mode = LINES;
+ List<Rectangle> lines = new ArrayList<Rectangle>();
+ List<Color> colors = new ArrayList<Color>();
+ int x1, y1;
+ int x2, y2;
+ @SuppressWarnings("LeakingThisInConstructor")
public DrawPanel() {
setBackground(Color.white);
addMouseMotionListener(this);
@@ -87,16 +112,16 @@
public void setDrawMode(int mode) {
switch (mode) {
- case LINES:
- case POINTS:
- this.mode = mode;
- break;
- default:
- throw new IllegalArgumentException();
+ case LINES:
+ case POINTS:
+ this.mode = mode;
+ break;
+ default:
+ throw new IllegalArgumentException();
}
}
-
+ @Override
public void mouseDragged(MouseEvent e) {
e.consume();
switch (mode) {
@@ -106,8 +131,8 @@
break;
case POINTS:
default:
- colors.addElement(getForeground());
- lines.addElement(new Rectangle(x1, y1, e.getX(), e.getY()));
+ colors.add(getForeground());
+ lines.add(new Rectangle(x1, y1, e.getX(), e.getY()));
x1 = e.getX();
y1 = e.getY();
break;
@@ -115,9 +140,11 @@
repaint();
}
+ @Override
public void mouseMoved(MouseEvent e) {
}
+ @Override
public void mousePressed(MouseEvent e) {
e.consume();
switch (mode) {
@@ -128,8 +155,8 @@
break;
case POINTS:
default:
- colors.addElement(getForeground());
- lines.addElement(new Rectangle(e.getX(), e.getY(), -1, -1));
+ colors.add(getForeground());
+ lines.add(new Rectangle(e.getX(), e.getY(), -1, -1));
x1 = e.getX();
y1 = e.getY();
repaint();
@@ -137,12 +164,13 @@
}
}
+ @Override
public void mouseReleased(MouseEvent e) {
e.consume();
switch (mode) {
case LINES:
- colors.addElement(getForeground());
- lines.addElement(new Rectangle(x1, y1, e.getX(), e.getY()));
+ colors.add(getForeground());
+ lines.add(new Rectangle(x1, y1, e.getX(), e.getY()));
x2 = -1;
break;
case POINTS:
@@ -152,23 +180,27 @@
repaint();
}
+ @Override
public void mouseEntered(MouseEvent e) {
}
+ @Override
public void mouseExited(MouseEvent e) {
}
+ @Override
public void mouseClicked(MouseEvent e) {
}
+ @Override
public void paint(Graphics g) {
int np = lines.size();
/* draw the current lines */
g.setColor(getForeground());
- for (int i=0; i < np; i++) {
- Rectangle p = (Rectangle)lines.elementAt(i);
- g.setColor((Color)colors.elementAt(i));
+ for (int i = 0; i < np; i++) {
+ Rectangle p = lines.get(i);
+ g.setColor(colors.get(i));
if (p.width != -1) {
g.drawLine(p.x, p.y, p.width, p.height);
} else {
@@ -185,9 +217,12 @@
}
+@SuppressWarnings("serial")
class DrawControls extends Panel implements ItemListener {
+
DrawPanel target;
+ @SuppressWarnings("LeakingThisInConstructor")
public DrawControls(DrawPanel target) {
this.target = target;
setLayout(new FlowLayout());
@@ -222,33 +257,35 @@
add(shapes);
}
+ @Override
public void paint(Graphics g) {
Rectangle r = getBounds();
g.setColor(Color.lightGray);
g.draw3DRect(0, 0, r.width, r.height, false);
int n = getComponentCount();
- for(int i=0; i<n; i++) {
+ for (int i = 0; i < n; i++) {
Component comp = getComponent(i);
if (comp instanceof Checkbox) {
Point loc = comp.getLocation();
Dimension d = comp.getSize();
g.setColor(comp.getForeground());
- g.drawRect(loc.x-1, loc.y-1, d.width+1, d.height+1);
+ g.drawRect(loc.x - 1, loc.y - 1, d.width + 1, d.height + 1);
}
}
}
- public void itemStateChanged(ItemEvent e) {
- if (e.getSource() instanceof Checkbox) {
- target.setForeground(((Component)e.getSource()).getForeground());
- } else if (e.getSource() instanceof Choice) {
- String choice = (String) e.getItem();
- if (choice.equals("Lines")) {
- target.setDrawMode(DrawPanel.LINES);
- } else if (choice.equals("Points")) {
- target.setDrawMode(DrawPanel.POINTS);
- }
+ @Override
+ public void itemStateChanged(ItemEvent e) {
+ if (e.getSource() instanceof Checkbox) {
+ target.setForeground(((Component) e.getSource()).getForeground());
+ } else if (e.getSource() instanceof Choice) {
+ String choice = (String) e.getItem();
+ if (choice.equals("Lines")) {
+ target.setDrawMode(DrawPanel.LINES);
+ } else if (choice.equals("Points")) {
+ target.setDrawMode(DrawPanel.POINTS);
+ }
+ }
}
- }
}
--- a/jdk/src/share/demo/applets/Fractal/CLSFractal.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/Fractal/CLSFractal.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,13 +29,13 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
import java.awt.Graphics;
import java.util.Stack;
-import java.util.Vector;
import java.awt.event.*;
+import java.util.ArrayList;
+import java.util.List;
+
/**
* A (not-yet) Context sensitive L-System Fractal applet class.
@@ -50,9 +50,11 @@
*
* @author Jim Graham
*/
+@SuppressWarnings("serial")
public class CLSFractal
- extends java.applet.Applet
- implements Runnable, MouseListener {
+ extends java.applet.Applet
+ implements Runnable, MouseListener {
+
Thread kicker;
ContextLSystem cls;
int fractLevel = 1;
@@ -67,31 +69,48 @@
int border;
boolean normalizescaling;
+ @Override
public void init() {
String s;
cls = new ContextLSystem(this);
s = getParameter("level");
- if (s != null) fractLevel = Integer.parseInt(s);
+ if (s != null) {
+ fractLevel = Integer.parseInt(s);
+ }
s = getParameter("incremental");
- if (s != null) incrementalUpdates = s.equalsIgnoreCase("true");
+ if (s != null) {
+ incrementalUpdates = s.equalsIgnoreCase("true");
+ }
s = getParameter("delay");
- if (s != null) repaintDelay = Integer.parseInt(s);
+ if (s != null) {
+ repaintDelay = Integer.parseInt(s);
+ }
s = getParameter("startAngle");
- if (s != null) startAngle = Float.valueOf(s).floatValue();
+ if (s != null) {
+ startAngle = Float.valueOf(s).floatValue();
+ }
s = getParameter("rotAngle");
- if (s != null) rotAngle = Float.valueOf(s).floatValue();
+ if (s != null) {
+ rotAngle = Float.valueOf(s).floatValue();
+ }
rotAngle = rotAngle / 360 * 2 * 3.14159265358f;
s = getParameter("border");
- if (s != null) border = Integer.parseInt(s);
+ if (s != null) {
+ border = Integer.parseInt(s);
+ }
s = getParameter("normalizescale");
- if (s != null) normalizescaling = s.equalsIgnoreCase("true");
+ if (s != null) {
+ normalizescaling = s.equalsIgnoreCase("true");
+ }
addMouseListener(this);
}
+ @Override
public void destroy() {
removeMouseListener(this);
}
+ @Override
public void run() {
Thread me = Thread.currentThread();
boolean needsRepaint = false;
@@ -99,7 +118,10 @@
cls.generate();
if (kicker == me && incrementalUpdates) {
repaint();
- try {Thread.sleep(repaintDelay);} catch (InterruptedException e){}
+ try {
+ Thread.sleep(repaintDelay);
+ } catch (InterruptedException ignored) {
+ }
} else {
needsRepaint = true;
}
@@ -112,22 +134,27 @@
}
}
+ @Override
public void start() {
kicker = new Thread(this);
kicker.start();
}
+ @Override
public void stop() {
kicker = null;
}
- /*1.1 event handling */
+ /*1.1 event handling */
+ @Override
public void mouseClicked(MouseEvent e) {
}
+ @Override
public void mousePressed(MouseEvent e) {
}
+ @Override
public void mouseReleased(MouseEvent e) {
cls = new ContextLSystem(this);
savedPath = null;
@@ -135,14 +162,16 @@
e.consume();
}
+ @Override
public void mouseEntered(MouseEvent e) {
}
+ @Override
public void mouseExited(MouseEvent e) {
}
-
String savedPath;
+ @Override
public void paint(Graphics g) {
String fractalPath = cls.getPath();
if (fractalPath == null) {
@@ -155,13 +184,14 @@
}
for (int i = 0; i < border; i++) {
- g.draw3DRect(i, i, getSize().width - i * 2, getSize().height - i * 2,false);
+ g.draw3DRect(i, i, getSize().width - i * 2, getSize().height - i * 2,
+ false);
}
render(g, fractalPath);
}
void render(Graphics g, String path) {
- Stack turtleStack = new Stack();
+ Stack<CLSTurtle> turtleStack = new Stack<CLSTurtle>();
CLSTurtle turtle;
if (g == null) {
@@ -172,11 +202,13 @@
turtle = new CLSTurtle(startAngle, 0, 0, 0, 0, 1, 1);
} else {
float frwidth = Xmax - Xmin;
- if (frwidth == 0)
+ if (frwidth == 0) {
frwidth = 1;
+ }
float frheight = Ymax - Ymin;
- if (frheight == 0)
+ if (frheight == 0) {
frheight = 1;
+ }
float xscale = (getSize().width - border * 2 - 1) / frwidth;
float yscale = (getSize().height - border * 2 - 1) / frheight;
int xoff = border;
@@ -184,83 +216,101 @@
if (normalizescaling) {
if (xscale < yscale) {
yoff += ((getSize().height - border * 2)
- - ((Ymax - Ymin) * xscale)) / 2;
+ - ((Ymax - Ymin) * xscale)) / 2;
yscale = xscale;
} else if (yscale < xscale) {
xoff += ((getSize().width - border * 2)
- - ((Xmax - Xmin) * yscale)) / 2;
+ - ((Xmax - Xmin) * yscale)) / 2;
xscale = yscale;
}
}
turtle = new CLSTurtle(startAngle, 0 - Xmin, 0 - Ymin,
- xoff, yoff, xscale, yscale);
+ xoff, yoff, xscale, yscale);
}
for (int pos = 0; pos < path.length(); pos++) {
switch (path.charAt(pos)) {
- case '+':
- turtle.rotate(rotAngle);
- break;
- case '-':
- turtle.rotate(-rotAngle);
- break;
- case '[':
- turtleStack.push(turtle);
- turtle = new CLSTurtle(turtle);
- break;
- case ']':
- turtle = (CLSTurtle) turtleStack.pop();
- break;
- case 'f':
- turtle.jump();
- break;
- case 'F':
- if (g == null) {
- includePt(turtle.X, turtle.Y);
+ case '+':
+ turtle.rotate(rotAngle);
+ break;
+ case '-':
+ turtle.rotate(-rotAngle);
+ break;
+ case '[':
+ turtleStack.push(turtle);
+ turtle = new CLSTurtle(turtle);
+ break;
+ case ']':
+ turtle = turtleStack.pop();
+ break;
+ case 'f':
turtle.jump();
- includePt(turtle.X, turtle.Y);
- } else {
- turtle.draw(g);
- }
- break;
- default:
- break;
+ break;
+ case 'F':
+ if (g == null) {
+ includePt(turtle.X, turtle.Y);
+ turtle.jump();
+ includePt(turtle.X, turtle.Y);
+ } else {
+ turtle.draw(g);
+ }
+ break;
+ default:
+ break;
}
}
}
void includePt(float x, float y) {
- if (x < Xmin)
+ if (x < Xmin) {
Xmin = x;
- if (x > Xmax)
+ }
+ if (x > Xmax) {
Xmax = x;
- if (y < Ymin)
+ }
+ if (y < Ymin) {
Ymin = y;
- if (y > Ymax)
+ }
+ if (y > Ymax) {
Ymax = y;
+ }
+ }
+
+ @Override
+ public String getAppletInfo() {
+ return "Title: CLSFractal 1.1f, 27 Mar 1995 \nAuthor: Jim Graham \nA "
+ + "(not yet) Context Sensitive L-System production rule. \n"
+ + "This class encapsulates a production rule for a Context "
+ + "Sensitive\n L-System \n(pred, succ, lContext, rContext)."
+ + " The matches() method, however, does not \n(yet) verify "
+ + "the lContext and rContext parts of the rule.";
}
- public String getAppletInfo() {
- return "Title: CLSFractal 1.1f, 27 Mar 1995 \nAuthor: Jim Graham \nA (not yet) Context Sensitive L-System production rule. \nThis class encapsulates a production rule for a Context Sensitive\n L-System \n(pred, succ, lContext, rContext). The matches() method, however, does not \n(yet) verify the lContext and rContext parts of the rule.";
- }
+ @Override
+ public String[][] getParameterInfo() {
+ String[][] info = {
+ { "level", "int", "Maximum number of recursions. Default is 1." },
+ { "incremental", "boolean", "Whether or not to repaint between "
+ + "recursions. Default is true." },
+ { "delay", "integer", "Sets delay between repaints. Default is 50." },
+ { "startAngle", "float", "Sets the starting angle. Default is 0." },
+ { "rotAngle", "float", "Sets the rotation angle. Default is 45." },
+ { "border", "integer", "Width of border. Default is 2." },
+ { "normalizeScale", "boolean", "Whether or not to normalize "
+ + "the scaling. Default is true." },
+ { "pred", "String",
+ "Initializes the rules for Context Sensitive L-Systems." },
+ { "succ", "String",
+ "Initializes the rules for Context Sensitive L-Systems." },
+ { "lContext", "String",
+ "Initializes the rules for Context Sensitive L-Systems." },
+ { "rContext", "String",
+ "Initializes the rules for Context Sensitive L-Systems." }
+ };
+ return info;
+ }
+}
- public String[][] getParameterInfo() {
- String[][] info = {
- {"level", "int", "Maximum number of recursions. Default is 1."},
- {"incremental","boolean","Whether or not to repaint between recursions. Default is true."},
- {"delay","integer","Sets delay between repaints. Default is 50."},
- {"startAngle","float","Sets the starting angle. Default is 0."},
- {"rotAngle","float","Sets the rotation angle. Default is 45."},
- {"border","integer","Width of border. Default is 2."},
- {"normalizeScale","boolean","Whether or not to normalize the scaling. Default is true."},
- {"pred","String","Initializes the rules for Context Sensitive L-Systems."},
- {"succ","String","Initializes the rules for Context Sensitive L-Systems."},
- {"lContext","String","Initializes the rules for Context Sensitive L-Systems."},
- {"rContext","String","Initializes the rules for Context Sensitive L-Systems."}
- };
- return info;
- }
-}
/**
* A Logo turtle class designed to support Context sensitive L-Systems.
@@ -271,6 +321,7 @@
* @author Jim Graham
*/
class CLSTurtle {
+
float angle;
float X;
float Y;
@@ -280,7 +331,7 @@
int yoff;
public CLSTurtle(float ang, float x, float y,
- int xorg, int yorg, float sx, float sy) {
+ int xorg, int yorg, float sx, float sy) {
angle = ang;
scaleX = sx;
scaleY = sy;
@@ -313,12 +364,13 @@
float x = X + (float) Math.cos(angle) * scaleX;
float y = Y + (float) Math.sin(angle) * scaleY;
g.drawLine((int) X + xoff, (int) Y + yoff,
- (int) x + xoff, (int) y + yoff);
+ (int) x + xoff, (int) y + yoff);
X = x;
Y = y;
}
}
+
/**
* A (non-)Context sensitive L-System class.
*
@@ -330,22 +382,23 @@
* @author Jim Graham
*/
class ContextLSystem {
+
String axiom;
- Vector rules = new Vector();
+ List<CLSRule> rules = new ArrayList<CLSRule>();
int level;
public ContextLSystem(java.applet.Applet app) {
axiom = app.getParameter("axiom");
int num = 1;
while (true) {
- String pred = app.getParameter("pred"+num);
- String succ = app.getParameter("succ"+num);
+ String pred = app.getParameter("pred" + num);
+ String succ = app.getParameter("succ" + num);
if (pred == null || succ == null) {
break;
}
- rules.addElement(new CLSRule(pred, succ,
- app.getParameter("lContext"+num),
- app.getParameter("rContext"+num)));
+ rules.add(new CLSRule(pred, succ,
+ app.getParameter("lContext" + num),
+ app.getParameter("rContext" + num)));
num++;
}
currentPath = new StringBuffer(axiom);
@@ -355,7 +408,6 @@
public int getLevel() {
return level;
}
-
StringBuffer currentPath;
public synchronized String getPath() {
@@ -385,7 +437,7 @@
public CLSRule findRule(int pos) {
for (int i = 0; i < rules.size(); i++) {
- CLSRule rule = (CLSRule) rules.elementAt(i);
+ CLSRule rule = rules.get(i);
if (rule.matches(currentPath, pos)) {
return rule;
}
@@ -394,6 +446,7 @@
}
}
+
/**
* A Context sensitive L-System production rule.
*
@@ -405,6 +458,7 @@
* @author Jim Graham
*/
class CLSRule {
+
String pred;
String succ;
String lContext;
--- a/jdk/src/share/demo/applets/Fractal/example1.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/Fractal/example1.html Sun Apr 10 10:23:28 2011 -0700
@@ -5,7 +5,7 @@
<body>
<h1>Fractals 1.1</h1>
<hr>
- <applet applet code="CLSFractal.class" width=500 height=120>
+ <applet code="CLSFractal.class" width=500 height=120>
<param name=level value="5">
<param name=rotangle value="45">
<param name=succ1 value="F-F++F-F">
--- a/jdk/src/share/demo/applets/GraphicsTest/AppletFrame.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/GraphicsTest/AppletFrame.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,8 +29,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
import java.awt.Frame;
import java.awt.Event;
@@ -38,66 +36,67 @@
import java.applet.Applet;
import java.awt.AWTEvent;
-// Applet to Application Frame window
-class AppletFrame extends Frame
-{
+
+/**
+ * Applet to Application Frame window
+ */
+@SuppressWarnings("serial")
+class AppletFrame extends Frame {
public static void startApplet(String className,
- String title,
- String args[])
- {
- // local variables
- Applet a;
- Dimension appletSize;
+ String title,
+ String args[]) {
+ // local variables
+ Applet a;
+ Dimension appletSize;
- try
- {
- // create an instance of your applet class
- a = (Applet) Class.forName(className).newInstance();
- }
- catch (ClassNotFoundException e) { return; }
- catch (InstantiationException e) { return; }
- catch (IllegalAccessException e) { return; }
+ try {
+ // create an instance of your applet class
+ a = (Applet) Class.forName(className).newInstance();
+ } catch (ClassNotFoundException e) {
+ return;
+ } catch (InstantiationException e) {
+ return;
+ } catch (IllegalAccessException e) {
+ return;
+ }
- // initialize the applet
- a.init();
- a.start();
+ // initialize the applet
+ a.init();
+ a.start();
- // create new application frame window
- AppletFrame f = new AppletFrame(title);
+ // create new application frame window
+ AppletFrame f = new AppletFrame(title);
- // add applet to frame window
- f.add("Center", a);
+ // add applet to frame window
+ f.add("Center", a);
- // resize frame window to fit applet
- // assumes that the applet sets its own size
- // otherwise, you should set a specific size here.
- appletSize = a.getSize();
- f.pack();
- f.setSize(appletSize);
+ // resize frame window to fit applet
+ // assumes that the applet sets its own size
+ // otherwise, you should set a specific size here.
+ appletSize = a.getSize();
+ f.pack();
+ f.setSize(appletSize);
- // show the window
- f.show();
+ // show the window
+ f.setVisible(true);
} // end startApplet()
-
// constructor needed to pass window title to class Frame
- public AppletFrame(String name)
- {
- // call java.awt.Frame(String) constructor
- super(name);
+ public AppletFrame(String name) {
+ // call java.awt.Frame(String) constructor
+ super(name);
}
// needed to allow window close
- public void processEvent(AWTEvent e)
- {
- // Window Destroy event
- if (e.getID() == Event.WINDOW_DESTROY)
- {
- // exit the program
- System.exit(0);
- }
- } // end handleEvent()
+ @Override
+ public void processEvent(AWTEvent e) {
+ // Window Destroy event
+ if (e.getID() == Event.WINDOW_DESTROY) {
+ // exit the program
+ System.exit(0);
+ }
+ } // end handleEvent()
+} // end class AppletFrame
-} // end class AppletFrame
--- a/jdk/src/share/demo/applets/GraphicsTest/GraphicsTest.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/GraphicsTest/GraphicsTest.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,22 +29,23 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.applet.Applet;
+
+@SuppressWarnings("serial")
class GraphicsPanel extends Panel {
+
ActionListener al;
ItemListener il;
public GraphicsCards cards;
- GraphicsPanel(EventListener listener) {
- al = (ActionListener)listener;
- il = (ItemListener)listener;
+ GraphicsPanel(EventListener listener) {
+ al = (ActionListener) listener;
+ il = (ItemListener) listener;
setLayout(new BorderLayout());
@@ -78,62 +79,75 @@
setSize(400, 400);
}
+ @Override
public Dimension getPreferredSize() {
return new Dimension(200, 100);
}
}
+
+@SuppressWarnings("serial")
public class GraphicsTest extends Applet
-implements ActionListener, ItemListener {
+ implements ActionListener, ItemListener {
+
GraphicsPanel mainPanel;
+ @Override
public void init() {
setLayout(new BorderLayout());
add("Center", mainPanel = new GraphicsPanel(this));
}
+ @Override
public void destroy() {
remove(mainPanel);
}
+ @Override
public void actionPerformed(ActionEvent e) {
String arg = e.getActionCommand();
if ("next".equals(arg)) {
- ((CardLayout)mainPanel.cards.getLayout()).next(mainPanel.cards);
- }
- else if ("previous".equals(arg)) {
- ((CardLayout)mainPanel.cards.getLayout()).previous(mainPanel.cards);
+ ((CardLayout) mainPanel.cards.getLayout()).next(mainPanel.cards);
+ } else if ("previous".equals(arg)) {
+ ((CardLayout) mainPanel.cards.getLayout()).previous(mainPanel.cards);
}
}
+ @Override
public void itemStateChanged(ItemEvent e) {
- ((CardLayout)mainPanel.cards.getLayout()).show(mainPanel.cards,(String)e.getItem());
+ ((CardLayout) mainPanel.cards.getLayout()).show(mainPanel.cards,
+ (String) e.getItem());
}
public static void main(String args[]) {
AppletFrame.startApplet("GraphicsTest", "Graphics Test", args);
}
+ @Override
public String getAppletInfo() {
return "An interactive demonstration of some graphics.";
}
} // end class GraphicsTest
+@SuppressWarnings("serial")
class GraphicsCards extends Panel {
+
public GraphicsCards() {
setLayout(new CardLayout());
add("Arc", new ArcCard());
- add("Oval", new ShapeTest( new OvalShape() ) );
- add("Polygon", new ShapeTest( new PolygonShape() ) );
- add("Rect", new ShapeTest( new RectShape() ) );
- add("RoundRect", new ShapeTest( new RoundRectShape() ) );
+ add("Oval", new ShapeTest(new OvalShape()));
+ add("Polygon", new ShapeTest(new PolygonShape()));
+ add("Rect", new ShapeTest(new RectShape()));
+ add("RoundRect", new ShapeTest(new RoundRectShape()));
}
} // end class GraphicsCards
+@SuppressWarnings("serial")
class ArcCard extends Panel {
+
public ArcCard() {
setLayout(new GridLayout(0, 2));
add(new ArcPanel(true));
@@ -144,7 +158,9 @@
} // end class ArcCard
+@SuppressWarnings("serial")
class ArcDegreePanel extends Panel {
+
boolean filled;
public ArcDegreePanel(boolean filled) {
@@ -152,290 +168,262 @@
}
void arcSteps(Graphics g,
- int step,
- int x,
- int y,
- int w,
- int h,
- Color c1,
- Color c2) {
- int a1 = 0;
- int a2 = step;
- int progress = 0;
- g.setColor(c1);
- for (; (a1+a2) <= 360; a1 = a1+a2, a2 += 1) {
- if (g.getColor() == c1) {
- g.setColor(c2);
- }
- else {
- g.setColor(c1);
- }
+ int step,
+ int x,
+ int y,
+ int w,
+ int h,
+ Color c1,
+ Color c2) {
+ int a1 = 0;
+ int a2 = step;
+ int progress = 0;
+ g.setColor(c1);
+ for (; (a1 + a2) <= 360; a1 = a1 + a2, a2 += 1) {
+ if (g.getColor() == c1) {
+ g.setColor(c2);
+ } else {
+ g.setColor(c1);
+ }
- if (filled) {
- g.fillArc(x, y, w, h, a1, a2);
- }
- else {
- g.drawArc(x, y, w, h, a1, a2);
- }
+ if (filled) {
+ g.fillArc(x, y, w, h, a1, a2);
+ } else {
+ g.drawArc(x, y, w, h, a1, a2);
+ }
- progress = a1+a2;
- } // end for
+ progress = a1 + a2;
+ } // end for
- if (progress != 360) {
- if (filled) {
- g.fillArc(x, y, w, h, a1, 360 - progress);
- }
- else {
- g.drawArc(x, y, w, h, a1, 360 - progress);
- }
- } // end if
- } // end arcSteps()
+ if (progress != 360) {
+ if (filled) {
+ g.fillArc(x, y, w, h, a1, 360 - progress);
+ } else {
+ g.drawArc(x, y, w, h, a1, 360 - progress);
+ }
+ } // end if
+ } // end arcSteps()
+ @Override
public void paint(Graphics g) {
Rectangle r = getBounds();
arcSteps(g, 3, 0, 0, r.width, r.height, Color.orange, Color.blue);
arcSteps(g,
- 2,
- r.width / 4,
- r.height / 4,
- r.width / 2,
- r.height / 2,
- Color.yellow,
- Color.green);
+ 2,
+ r.width / 4,
+ r.height / 4,
+ r.width / 2,
+ r.height / 2,
+ Color.yellow,
+ Color.green);
arcSteps(g,
- 1,
- (r.width * 3) / 8,
- (r.height * 3) / 8,
- r.width / 4,
- r.height / 4,
- Color.magenta,
- Color.white);
+ 1,
+ (r.width * 3) / 8,
+ (r.height * 3) / 8,
+ r.width / 4,
+ r.height / 4,
+ Color.magenta,
+ Color.white);
- } // end paint()
+ } // end paint()
} // end class ArcDegreePanel
+@SuppressWarnings("serial")
class ArcPanel extends Panel {
+
boolean filled;
public ArcPanel(boolean filled) {
- this.filled = filled;
- }
+ this.filled = filled;
+ }
- public void paint(Graphics g)
- {
- Rectangle r = getBounds();
+ @Override
+ public void paint(Graphics g) {
+ Rectangle r = getBounds();
- g.setColor(Color.yellow);
- if (filled)
- {
- g.fillArc(0, 0, r.width, r.height, 0, 45);
- }
- else
- {
- g.drawArc(0, 0, r.width, r.height, 0, 45);
- }
+ g.setColor(Color.yellow);
+ if (filled) {
+ g.fillArc(0, 0, r.width, r.height, 0, 45);
+ } else {
+ g.drawArc(0, 0, r.width, r.height, 0, 45);
+ }
- g.setColor(Color.green);
- if (filled)
- {
- g.fillArc(0, 0, r.width, r.height, 90, -45);
- }
- else
- {
- g.drawArc(0, 0, r.width, r.height, 90, -45);
- }
+ g.setColor(Color.green);
+ if (filled) {
+ g.fillArc(0, 0, r.width, r.height, 90, -45);
+ } else {
+ g.drawArc(0, 0, r.width, r.height, 90, -45);
+ }
- g.setColor(Color.orange);
- if (filled)
- {
- g.fillArc(0, 0, r.width, r.height, 135, -45);
- }
- else
- {
- g.drawArc(0, 0, r.width, r.height, 135, -45);
- }
+ g.setColor(Color.orange);
+ if (filled) {
+ g.fillArc(0, 0, r.width, r.height, 135, -45);
+ } else {
+ g.drawArc(0, 0, r.width, r.height, 135, -45);
+ }
- g.setColor(Color.magenta);
+ g.setColor(Color.magenta);
- if (filled)
- {
- g.fillArc(0, 0, r.width, r.height, -225, 45);
- }
- else
- {
- g.drawArc(0, 0, r.width, r.height, -225, 45);
- }
+ if (filled) {
+ g.fillArc(0, 0, r.width, r.height, -225, 45);
+ } else {
+ g.drawArc(0, 0, r.width, r.height, -225, 45);
+ }
- g.setColor(Color.yellow);
- if (filled)
- {
- g.fillArc(0, 0, r.width, r.height, 225, -45);
- }
- else
- {
- g.drawArc(0, 0, r.width, r.height, 225, -45);
- }
+ g.setColor(Color.yellow);
+ if (filled) {
+ g.fillArc(0, 0, r.width, r.height, 225, -45);
+ } else {
+ g.drawArc(0, 0, r.width, r.height, 225, -45);
+ }
- g.setColor(Color.green);
- if (filled)
- {
- g.fillArc(0, 0, r.width, r.height, -135, 45);
- }
- else
- {
- g.drawArc(0, 0, r.width, r.height, -135, 45);
- }
+ g.setColor(Color.green);
+ if (filled) {
+ g.fillArc(0, 0, r.width, r.height, -135, 45);
+ } else {
+ g.drawArc(0, 0, r.width, r.height, -135, 45);
+ }
- g.setColor(Color.orange);
- if (filled)
- {
- g.fillArc(0, 0, r.width, r.height, -45, -45);
- }
- else
- {
- g.drawArc(0, 0, r.width, r.height, -45, -45);
- }
+ g.setColor(Color.orange);
+ if (filled) {
+ g.fillArc(0, 0, r.width, r.height, -45, -45);
+ } else {
+ g.drawArc(0, 0, r.width, r.height, -45, -45);
+ }
- g.setColor(Color.magenta);
- if (filled)
- {
- g.fillArc(0, 0, r.width, r.height, 315, 45);
- }
- else
- {
- g.drawArc(0, 0, r.width, r.height, 315, 45);
- }
+ g.setColor(Color.magenta);
+ if (filled) {
+ g.fillArc(0, 0, r.width, r.height, 315, 45);
+ } else {
+ g.drawArc(0, 0, r.width, r.height, 315, 45);
+ }
- } // end paint()
-
+ } // end paint()
} // end class ArcPanel
-abstract class Shape
-{
- abstract void draw(Graphics g, int x, int y, int w, int h);
- abstract void fill(Graphics g, int x, int y, int w, int h);
+abstract class Shape {
+
+ abstract void draw(Graphics g, int x, int y, int w, int h);
+
+ abstract void fill(Graphics g, int x, int y, int w, int h);
+}
+
+
+class RectShape extends Shape {
+
+ @Override
+ void draw(Graphics g, int x, int y, int w, int h) {
+ g.drawRect(x, y, w, h);
+ }
+
+ @Override
+ void fill(Graphics g, int x, int y, int w, int h) {
+ g.fillRect(x, y, w, h);
+ }
}
-class RectShape extends Shape
-{
- void draw(Graphics g, int x, int y, int w, int h)
- {
- g.drawRect(x, y, w, h);
- }
+class OvalShape extends Shape {
- void fill(Graphics g, int x, int y, int w, int h)
- {
- g.fillRect(x, y, w, h);
- }
+ @Override
+ void draw(Graphics g, int x, int y, int w, int h) {
+ g.drawOval(x, y, w, h);
+ }
+
+ @Override
+ void fill(Graphics g, int x, int y, int w, int h) {
+ g.fillOval(x, y, w, h);
+ }
}
-class OvalShape extends Shape
-{
- void draw(Graphics g, int x, int y, int w, int h)
- {
- g.drawOval(x, y, w, h);
- }
+class RoundRectShape extends Shape {
- void fill(Graphics g, int x, int y, int w, int h)
- {
- g.fillOval(x, y, w, h);
- }
+ @Override
+ void draw(Graphics g, int x, int y, int w, int h) {
+ g.drawRoundRect(x, y, w, h, 10, 10);
+ }
+
+ @Override
+ void fill(Graphics g, int x, int y, int w, int h) {
+ g.fillRoundRect(x, y, w, h, 10, 10);
+ }
}
-class RoundRectShape extends Shape
-{
- void draw(Graphics g, int x, int y, int w, int h)
- {
- g.drawRoundRect(x, y, w, h, 10, 10);
- }
+class PolygonShape extends Shape {
+ // class variables
- void fill(Graphics g, int x, int y, int w, int h)
- {
- g.fillRoundRect(x, y, w, h, 10, 10);
- }
-}
+ Polygon p;
+ Polygon pBase;
-class PolygonShape extends Shape
-{
- // class variables
- Polygon p;
- Polygon pBase;
+ public PolygonShape() {
+ pBase = new Polygon();
+ pBase.addPoint(0, 0);
+ pBase.addPoint(10, 0);
+ pBase.addPoint(5, 15);
+ pBase.addPoint(10, 20);
+ pBase.addPoint(5, 20);
+ pBase.addPoint(0, 10);
+ pBase.addPoint(0, 0);
+ }
- public PolygonShape()
- {
- pBase = new Polygon();
- pBase.addPoint(0, 0);
- pBase.addPoint(10, 0);
- pBase.addPoint(5, 15);
- pBase.addPoint(10, 20);
- pBase.addPoint(5, 20);
- pBase.addPoint(0, 10);
- pBase.addPoint(0, 0);
- }
+ void scalePolygon(float w, float h) {
+ p = new Polygon();
+ for (int i = 0; i < pBase.npoints; ++i) {
+ p.addPoint((int) (pBase.xpoints[i] * w),
+ (int) (pBase.ypoints[i] * h));
+ }
- void scalePolygon(float w, float h)
- {
- p = new Polygon();
- for (int i = 0; i < pBase.npoints; ++i)
- {
- p.addPoint( (int) (pBase.xpoints[i] * w),
- (int) (pBase.ypoints[i] * h) );
- }
-
- }
+ }
- void draw(Graphics g, int x, int y, int w, int h)
- {
- Graphics ng = g.create();
- try {
- ng.translate(x, y);
- scalePolygon( (float) ( (float) w / (float) 10 ),
- (float) ( (float) h / (float) 20 ) );
- ng.drawPolygon(p);
- } finally {
- ng.dispose();
+ @Override
+ void draw(Graphics g, int x, int y, int w, int h) {
+ Graphics ng = g.create();
+ try {
+ ng.translate(x, y);
+ scalePolygon(((float) w / 10f), ((float) h / 20f));
+ ng.drawPolygon(p);
+ } finally {
+ ng.dispose();
+ }
}
- }
- void fill(Graphics g, int x, int y, int w, int h)
- {
- Graphics ng = g.create();
- try {
- ng.translate(x, y);
- scalePolygon( (float) ( (float) w / (float) 10 ),
- (float) ( (float) h / (float) 20 ) );
- ng.fillPolygon(p);
- } finally {
- ng.dispose();
+ @Override
+ void fill(Graphics g, int x, int y, int w, int h) {
+ Graphics ng = g.create();
+ try {
+ ng.translate(x, y);
+ scalePolygon(((float) w / 10f), ((float) h / 20f));
+ ng.fillPolygon(p);
+ } finally {
+ ng.dispose();
+ }
}
- }
}
-class ShapeTest extends Panel
-{
- Shape shape;
- int step;
+@SuppressWarnings("serial")
+class ShapeTest extends Panel {
+
+ Shape shape;
+ int step;
- public ShapeTest(Shape shape, int step)
- {
- this.shape = shape;
- this.step = step;
- }
+ public ShapeTest(Shape shape, int step) {
+ this.shape = shape;
+ this.step = step;
+ }
- public ShapeTest(Shape shape)
- {
- this(shape, 10);
- }
+ public ShapeTest(Shape shape) {
+ this(shape, 10);
+ }
+ @Override
public void paint(Graphics g) {
Rectangle bounds = getBounds();
@@ -443,35 +431,22 @@
Color color;
- for (color=Color.red,
- cx=bounds.x,
- cy=bounds.y,
- cw=bounds.width / 2,
- ch=bounds.height;
- cw > 0 && ch > 0;
-
- cx+=step,
- cy += step,
- cw -= (step * 2),
- ch -= (step * 2),
- color=ColorUtils.darker(color, 0.9) ) {
+ for (color = Color.red, cx = bounds.x, cy = bounds.y,
+ cw = bounds.width / 2, ch = bounds.height;
+ cw > 0 && ch > 0;
+ cx += step, cy += step, cw -= (step * 2), ch -= (step * 2),
+ color = ColorUtils.darker(color, 0.9)) {
g.setColor(color);
shape.draw(g, cx, cy, cw, ch);
}
- for (cx=bounds.x + bounds.width / 2,
- cy=bounds.y,
- cw=bounds.width / 2, ch=bounds.height;
- cw > 0 && ch > 0;
-
- cx+=step,
- cy += step,
- cw -= (step * 2),
- ch -= (step * 2) ) {
+ for (cx = bounds.x + bounds.width / 2, cy = bounds.y,
+ cw = bounds.width / 2, ch = bounds.height;
+ cw > 0 && ch > 0;
+ cx += step, cy += step, cw -= (step * 2), ch -= (step * 2)) {
if (g.getColor() == Color.red) {
g.setColor(Color.blue);
- }
- else {
+ } else {
g.setColor(Color.red);
}
@@ -480,16 +455,18 @@
} // end paint()
} // end class ShapeTest
+
class ColorUtils {
+
static Color brighter(Color c, double factor) {
- return new Color( Math.min((int)(c.getRed() *(1/factor)), 255),
- Math.min((int)(c.getGreen()*(1/factor)), 255),
- Math.min((int)(c.getBlue() *(1/factor)), 255) );
+ return new Color(Math.min((int) (c.getRed() * (1 / factor)), 255),
+ Math.min((int) (c.getGreen() * (1 / factor)), 255),
+ Math.min((int) (c.getBlue() * (1 / factor)), 255));
}
static Color darker(Color c, double factor) {
- return new Color( Math.max((int)(c.getRed() *factor), 0),
- Math.max((int)(c.getGreen()*factor), 0),
- Math.max((int)(c.getBlue() *factor), 0) );
+ return new Color(Math.max((int) (c.getRed() * factor), 0),
+ Math.max((int) (c.getGreen() * factor), 0),
+ Math.max((int) (c.getBlue() * factor), 0));
}
}
--- a/jdk/src/share/demo/applets/MoleculeViewer/Matrix3D.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/MoleculeViewer/Matrix3D.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,22 +29,23 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
/** A fairly conventional 3D matrix object that can transform sets of
- 3D points and perform a variety of manipulations on the transform */
+3D points and perform a variety of manipulations on the transform */
class Matrix3D {
+
float xx, xy, xz, xo;
float yx, yy, yz, yo;
float zx, zy, zz, zo;
static final double pi = 3.14159265;
+
/** Create a new unit matrix */
- Matrix3D () {
+ Matrix3D() {
xx = 1.0f;
yy = 1.0f;
zz = 1.0f;
}
+
/** Scale by f in all dimensions */
void scale(float f) {
xx *= f;
@@ -60,6 +61,7 @@
zz *= f;
zo *= f;
}
+
/** Scale along each axis independently */
void scale(float xf, float yf, float zf) {
xx *= xf;
@@ -75,12 +77,14 @@
zz *= zf;
zo *= zf;
}
+
/** Translate the origin */
void translate(float x, float y, float z) {
xo += x;
yo += y;
zo += z;
}
+
/** rotate theta degrees about the y axis */
void yrot(double theta) {
theta *= (pi / 180);
@@ -106,6 +110,7 @@
zy = Nzy;
zz = Nzz;
}
+
/** rotate theta degrees about the x axis */
void xrot(double theta) {
theta *= (pi / 180);
@@ -131,6 +136,7 @@
zy = Nzy;
zz = Nzz;
}
+
/** rotate theta degrees about the z axis */
void zrot(double theta) {
theta *= (pi / 180);
@@ -156,6 +162,7 @@
xy = Nxy;
xz = Nxz;
}
+
/** Multiply this matrix by a second: M = M*R */
void mult(Matrix3D rhs) {
float lxx = xx * rhs.xx + yx * rhs.xy + zx * rhs.xz;
@@ -204,10 +211,11 @@
zy = 0;
zz = 1;
}
+
/** Transform nvert points from v into tv. v contains the input
- coordinates in floating point. Three successive entries in
- the array constitute a point. tv ends up holding the transformed
- points as integers; three successive entries per point */
+ coordinates in floating point. Three successive entries in
+ the array constitute a point. tv ends up holding the transformed
+ points as integers; three successive entries per point */
void transform(float v[], int tv[], int nvert) {
float lxx = xx, lxy = xy, lxz = xz, lxo = xo;
float lyx = yx, lyy = yy, lyz = yz, lyo = yo;
@@ -216,11 +224,13 @@
float x = v[i];
float y = v[i + 1];
float z = v[i + 2];
- tv[i ] = (int) (x * lxx + y * lxy + z * lxz + lxo);
+ tv[i] = (int) (x * lxx + y * lxy + z * lxz + lxo);
tv[i + 1] = (int) (x * lyx + y * lyy + z * lyz + lyo);
tv[i + 2] = (int) (x * lzx + y * lzy + z * lzz + lzo);
}
}
+
+ @Override
public String toString() {
return ("[" + xo + "," + xx + "," + xy + "," + xz + ";"
+ yo + "," + yx + "," + yy + "," + yz + ";"
--- a/jdk/src/share/demo/applets/MoleculeViewer/XYZApp.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/MoleculeViewer/XYZApp.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,37 +29,43 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
+
+import java.applet.Applet;
+import java.awt.Image;
+import java.awt.Graphics;
+import java.awt.Dimension;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.MouseMotionListener;
+import java.net.URL;
+import java.awt.image.IndexColorModel;
+import java.awt.image.MemoryImageSource;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.StreamTokenizer;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
/*
* A set of classes to parse, represent and display Chemical compounds in
* .xyz format (see http://chem.leeds.ac.uk/Project/MIME.html)
*/
+/** The representation of a Chemical .xyz model */
+final class XYZChemModel {
-import java.applet.Applet;
-import java.awt.Image;
-import java.awt.Event;
-import java.awt.Graphics;
-import java.awt.Dimension;
-import java.io.*;
-import java.net.URL;
-import java.util.Hashtable;
-import java.awt.image.IndexColorModel;
-import java.awt.image.ColorModel;
-import java.awt.image.MemoryImageSource;
-import java.awt.event.*;
-
-/** The representation of a Chemical .xyz model */
-class XYZChemModel {
float vert[];
Atom atoms[];
int tvert[];
int ZsortMap[];
int nvert, maxvert;
+ static final Map<String, Atom> atomTable = new HashMap<String, Atom>();
+ static Atom defaultAtom;
- static Hashtable atomTable = new Hashtable();
- static Atom defaultAtom;
static {
atomTable.put("c", new Atom(0, 0, 0));
atomTable.put("h", new Atom(210, 210, 210));
@@ -70,77 +76,72 @@
atomTable.put("hn", new Atom(150, 255, 150)); /* !!*/
defaultAtom = new Atom(255, 100, 200);
}
-
boolean transformed;
Matrix3D mat;
-
float xmin, xmax, ymin, ymax, zmin, zmax;
-
- XYZChemModel () {
+ XYZChemModel() {
mat = new Matrix3D();
mat.xrot(20);
mat.yrot(30);
}
-
- /** Create a Cehmical model by parsing an input stream */
- XYZChemModel (InputStream is) throws Exception
- {
- this();
- StreamTokenizer st = new StreamTokenizer(
- new BufferedReader(new InputStreamReader(is, "UTF-8")));
- st.eolIsSignificant(true);
- st.commentChar('#');
- int slot = 0;
+ /** Create a Chemical model by parsing an input stream */
+ XYZChemModel(InputStream is) throws Exception {
+ this();
+ StreamTokenizer st = new StreamTokenizer(
+ new BufferedReader(new InputStreamReader(is, "UTF-8")));
+ st.eolIsSignificant(true);
+ st.commentChar('#');
- try
- {
-scan:
- while (true)
- {
- switch ( st.nextToken() )
- {
- case StreamTokenizer.TT_EOF:
- break scan;
- default:
- break;
- case StreamTokenizer.TT_WORD:
- String name = st.sval;
- double x = 0, y = 0, z = 0;
- if (st.nextToken() == StreamTokenizer.TT_NUMBER)
- {
- x = st.nval;
- if (st.nextToken() == StreamTokenizer.TT_NUMBER)
- {
- y = st.nval;
- if (st.nextToken() == StreamTokenizer.TT_NUMBER)
- z = st.nval;
- }
- }
- addVert(name, (float) x, (float) y, (float) z);
- while( st.ttype != StreamTokenizer.TT_EOL &&
- st.ttype != StreamTokenizer.TT_EOF )
- st.nextToken();
+ try {
+ scan:
+ while (true) {
+ switch (st.nextToken()) {
+ case StreamTokenizer.TT_EOF:
+ break scan;
+ default:
+ break;
+ case StreamTokenizer.TT_WORD:
+ String name = st.sval;
+ double x = 0,
+ y = 0,
+ z = 0;
+ if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
+ x = st.nval;
+ if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
+ y = st.nval;
+ if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
+ z = st.nval;
+ }
+ }
+ }
+ addVert(name, (float) x, (float) y, (float) z);
+ while (st.ttype != StreamTokenizer.TT_EOL
+ && st.ttype != StreamTokenizer.TT_EOF) {
+ st.nextToken();
+ }
- } // end Switch
+ } // end Switch
- } // end while
+ } // end while
- is.close();
+ is.close();
- } // end Try
- catch( IOException e) {}
+ } // end Try
+ catch (IOException e) {
+ }
- if (st.ttype != StreamTokenizer.TT_EOF)
- throw new Exception(st.toString());
+ if (st.ttype != StreamTokenizer.TT_EOF) {
+ throw new Exception(st.toString());
+ }
} // end XYZChemModel()
/** Add a vertex to this model */
int addVert(String name, float x, float y, float z) {
int i = nvert;
- if (i >= maxvert)
+ if (i >= maxvert) {
if (vert == null) {
maxvert = 100;
vert = new float[maxvert * 3];
@@ -154,8 +155,11 @@
System.arraycopy(atoms, 0, na, 0, atoms.length);
atoms = na;
}
- Atom a = (Atom) atomTable.get(name.toLowerCase());
- if (a == null) a = defaultAtom;
+ }
+ Atom a = atomTable.get(name.toLowerCase());
+ if (a == null) {
+ a = defaultAtom;
+ }
atoms[i] = a;
i *= 3;
vert[i] = x;
@@ -166,29 +170,32 @@
/** Transform all the points in this model */
void transform() {
- if (transformed || nvert <= 0)
+ if (transformed || nvert <= 0) {
return;
- if (tvert == null || tvert.length < nvert * 3)
+ }
+ if (tvert == null || tvert.length < nvert * 3) {
tvert = new int[nvert * 3];
+ }
mat.transform(vert, tvert, nvert);
transformed = true;
}
-
/** Paint this model to a graphics context. It uses the matrix associated
- with this model to map from model space to screen space.
- The next version of the browser should have double buffering,
- which will make this *much* nicer */
+ with this model to map from model space to screen space.
+ The next version of the browser should have double buffering,
+ which will make this *much* nicer */
void paint(Graphics g) {
- if (vert == null || nvert <= 0)
+ if (vert == null || nvert <= 0) {
return;
+ }
transform();
int v[] = tvert;
int zs[] = ZsortMap;
if (zs == null) {
ZsortMap = zs = new int[nvert];
- for (int i = nvert; --i >= 0;)
+ for (int i = nvert; --i >= 0;) {
zs[i] = i * 3;
+ }
}
/*
@@ -209,24 +216,26 @@
flipped = true;
}
}
- if (!flipped)
+ if (!flipped) {
break;
+ }
}
- int lg = 0;
int lim = nvert;
- Atom ls[] = atoms;
- if (lim <= 0 || nvert <= 0)
+ if (lim <= 0 || nvert <= 0) {
return;
+ }
for (int i = 0; i < lim; i++) {
int j = zs[i];
int grey = v[j + 2];
- if (grey < 0)
+ if (grey < 0) {
grey = 0;
- if (grey > 15)
+ }
+ if (grey > 15) {
grey = 15;
+ }
// g.drawString(names[i], v[j], v[j+1]);
- atoms[j/3].paint(g, v[j], v[j + 1], grey);
+ atoms[j / 3].paint(g, v[j], v[j + 1], grey);
// g.drawImage(iBall, v[j] - (iBall.width >> 1), v[j + 1] -
// (iBall.height >> 1));
}
@@ -234,47 +243,55 @@
/** Find the bounding box of this model */
void findBB() {
- if (nvert <= 0)
+ if (nvert <= 0) {
return;
+ }
float v[] = vert;
- float xmin = v[0], xmax = xmin;
- float ymin = v[1], ymax = ymin;
- float zmin = v[2], zmax = zmin;
+ float _xmin = v[0], _xmax = _xmin;
+ float _ymin = v[1], _ymax = _ymin;
+ float _zmin = v[2], _zmax = _zmin;
for (int i = nvert * 3; (i -= 3) > 0;) {
float x = v[i];
- if (x < xmin)
- xmin = x;
- if (x > xmax)
- xmax = x;
+ if (x < _xmin) {
+ _xmin = x;
+ }
+ if (x > _xmax) {
+ _xmax = x;
+ }
float y = v[i + 1];
- if (y < ymin)
- ymin = y;
- if (y > ymax)
- ymax = y;
+ if (y < _ymin) {
+ _ymin = y;
+ }
+ if (y > _ymax) {
+ _ymax = y;
+ }
float z = v[i + 2];
- if (z < zmin)
- zmin = z;
- if (z > zmax)
- zmax = z;
+ if (z < _zmin) {
+ _zmin = z;
+ }
+ if (z > _zmax) {
+ _zmax = z;
+ }
}
- this.xmax = xmax;
- this.xmin = xmin;
- this.ymax = ymax;
- this.ymin = ymin;
- this.zmax = zmax;
- this.zmin = zmin;
+ this.xmax = _xmax;
+ this.xmin = _xmin;
+ this.ymax = _ymax;
+ this.ymin = _ymin;
+ this.zmax = _zmax;
+ this.zmin = _zmin;
}
}
+
/** An applet to put a Chemical model into a page */
-public class XYZApp
- extends Applet
- implements Runnable, MouseListener, MouseMotionListener {
+@SuppressWarnings("serial")
+public class XYZApp extends Applet implements Runnable, MouseListener,
+ MouseMotionListener {
+
XYZChemModel md;
boolean painted = true;
float xfac;
int prevx, prevy;
- float xtheta, ytheta;
float scalefudge = 1;
Matrix3D amat = new Matrix3D(), tmat = new Matrix3D();
String mdname = null;
@@ -283,7 +300,6 @@
Graphics backGC;
Dimension backSize;
-
private synchronized void newBackBuffer() {
backBuffer = createImage(getSize().width, getSize().height);
if (backGC != null) {
@@ -293,164 +309,190 @@
backSize = getSize();
}
+ @Override
public void init() {
mdname = getParameter("model");
try {
scalefudge = Float.valueOf(getParameter("scale")).floatValue();
- } catch(Exception e) {
- };
+ } catch (Exception ignored) {
+ }
amat.yrot(20);
amat.xrot(20);
- if (mdname == null)
+ if (mdname == null) {
mdname = "model.obj";
+ }
resize(getSize().width <= 20 ? 400 : getSize().width,
- getSize().height <= 20 ? 400 : getSize().height);
+ getSize().height <= 20 ? 400 : getSize().height);
newBackBuffer();
addMouseListener(this);
addMouseMotionListener(this);
}
+ @Override
public void destroy() {
removeMouseListener(this);
removeMouseMotionListener(this);
}
+ @Override
public void run() {
InputStream is = null;
try {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
is = new URL(getDocumentBase(), mdname).openStream();
- XYZChemModel m = new XYZChemModel (is);
+ XYZChemModel m = new XYZChemModel(is);
Atom.setApplet(this);
md = m;
m.findBB();
float xw = m.xmax - m.xmin;
float yw = m.ymax - m.ymin;
float zw = m.zmax - m.zmin;
- if (yw > xw)
+ if (yw > xw) {
xw = yw;
- if (zw > xw)
+ }
+ if (zw > xw) {
xw = zw;
+ }
float f1 = getSize().width / xw;
float f2 = getSize().height / xw;
xfac = 0.7f * (f1 < f2 ? f1 : f2) * scalefudge;
- } catch(Exception e) {
- e.printStackTrace();
+ } catch (Exception e) {
+ Logger.getLogger(XYZApp.class.getName()).log(Level.SEVERE, null, e);
md = null;
message = e.toString();
}
try {
- if (is != null)
+ if (is != null) {
is.close();
- } catch(Exception e) {
+ }
+ } catch (Exception ignored) {
}
repaint();
}
+
+ @Override
public void start() {
- if (md == null && message == null)
+ if (md == null && message == null) {
new Thread(this).start();
+ }
}
+
+ @Override
public void stop() {
}
- /* event handling */
- public void mouseClicked(MouseEvent e) {
- }
- public void mousePressed(MouseEvent e) {
- prevx = e.getX();
- prevy = e.getY();
- e.consume();
- }
- public void mouseReleased(MouseEvent e) {
- }
- public void mouseEntered(MouseEvent e) {
- }
- public void mouseExited(MouseEvent e) {
- }
- public void mouseDragged(MouseEvent e) {
- int x = e.getX();
- int y = e.getY();
- tmat.unit();
- float xtheta = (prevy - y) * (360.0f / getSize().width);
- float ytheta = (x - prevx) * (360.0f / getSize().height);
- tmat.xrot(xtheta);
- tmat.yrot(ytheta);
- amat.mult(tmat);
- if (painted) {
- painted = false;
- repaint();
+ /* event handling */
+
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ }
+
+ @Override
+ public void mousePressed(MouseEvent e) {
+ prevx = e.getX();
+ prevy = e.getY();
+ e.consume();
+ }
+
+ @Override
+ public void mouseReleased(MouseEvent e) {
+ }
+
+ @Override
+ public void mouseEntered(MouseEvent e) {
+ }
+
+ @Override
+ public void mouseExited(MouseEvent e) {
}
- prevx = x;
- prevy = y;
- e.consume();
- }
- public void mouseMoved(MouseEvent e) {
- }
+ @Override
+ public void mouseDragged(MouseEvent e) {
+ int x = e.getX();
+ int y = e.getY();
+ tmat.unit();
+ float xtheta = (prevy - y) * (360.0f / getSize().width);
+ float ytheta = (x - prevx) * (360.0f / getSize().height);
+ tmat.xrot(xtheta);
+ tmat.yrot(ytheta);
+ amat.mult(tmat);
+ if (painted) {
+ painted = false;
+ repaint();
+ }
+ prevx = x;
+ prevy = y;
+ e.consume();
+ }
+
+ @Override
+ public void mouseMoved(MouseEvent e) {
+ }
+
+ @Override
public void update(Graphics g) {
- if (backBuffer == null)
+ if (backBuffer == null) {
g.clearRect(0, 0, getSize().width, getSize().height);
+ }
paint(g);
}
+ @Override
public void paint(Graphics g) {
if (md != null) {
md.mat.unit();
md.mat.translate(-(md.xmin + md.xmax) / 2,
- -(md.ymin + md.ymax) / 2,
- -(md.zmin + md.zmax) / 2);
+ -(md.ymin + md.ymax) / 2,
+ -(md.zmin + md.zmax) / 2);
md.mat.mult(amat);
// md.mat.scale(xfac, -xfac, 8 * xfac / getSize().width);
md.mat.scale(xfac, -xfac, 16 * xfac / getSize().width);
md.mat.translate(getSize().width / 2, getSize().height / 2, 8);
md.transformed = false;
if (backBuffer != null) {
- if (!backSize.equals(getSize()))
+ if (!backSize.equals(getSize())) {
newBackBuffer();
+ }
backGC.setColor(getBackground());
- backGC.fillRect(0,0,getSize().width,getSize().height);
+ backGC.fillRect(0, 0, getSize().width, getSize().height);
md.paint(backGC);
g.drawImage(backBuffer, 0, 0, this);
+ } else {
+ md.paint(g);
}
- else
- md.paint(g);
setPainted();
} else if (message != null) {
g.drawString("Error in model:", 3, 20);
g.drawString(message, 10, 40);
}
}
+
private synchronized void setPainted() {
painted = true;
notifyAll();
}
- private synchronized void waitPainted()
- {
- while (!painted)
- {
- try
- {
- wait();
- }
- catch (InterruptedException e) {}
- }
- painted = false;
+ @Override
+ public String getAppletInfo() {
+ return "Title: XYZApp \nAuthor: James Gosling \nAn applet to put"
+ + " a Chemical model into a page.";
}
- public String getAppletInfo() {
- return "Title: XYZApp \nAuthor: James Gosling \nAn applet to put a Chemical model into a page.";
- }
-
- public String[][] getParameterInfo() {
- String[][] info = {
- {"model", "path string", "The path to the model to be displayed in .xyz format (see http://chem.leeds.ac.uk/Project/MIME.html). Default is model.obj."},
- {"scale", "float", "Scale factor. Default is 1 (i.e. no scale)."}
- };
- return info;
- }
+ @Override
+ public String[][] getParameterInfo() {
+ String[][] info = {
+ { "model", "path string", "The path to the model to be displayed"
+ + " in .xyz format "
+ + "(see http://chem.leeds.ac.uk/Project/MIME.html)."
+ + " Default is model.obj." },
+ { "scale", "float", "Scale factor. Default is 1 (i.e. no scale)." }
+ };
+ return info;
+ }
} // end class XYZApp
+
class Atom {
+
private static Applet applet;
private static byte[] data;
private final static int R = 40;
@@ -459,7 +501,6 @@
private final static int bgGrey = 192;
private final static int nBalls = 16;
private static int maxr;
-
private int Rl;
private int Gl;
private int Bl;
@@ -475,24 +516,29 @@
int x = X + hx;
int y = Y - R + hy;
int r = (int) (Math.sqrt(x * x + y * y) + 0.5);
- if (r > mr)
+ if (r > mr) {
mr = r;
+ }
data[p++] = r <= 0 ? 1 : (byte) r;
}
}
maxr = mr;
}
+
static void setApplet(Applet app) {
applet = app;
}
+
Atom(int Rl, int Gl, int Bl) {
this.Rl = Rl;
this.Gl = Gl;
this.Bl = Bl;
}
- private final int blend(int fg, int bg, float fgfactor) {
+
+ private int blend(int fg, int bg, float fgfactor) {
return (int) (bg + (fg - bg) * fgfactor);
}
+
private void Setup() {
balls = new Image[nBalls];
byte red[] = new byte[256];
@@ -502,7 +548,7 @@
byte blue[] = new byte[256];
blue[0] = (byte) bgGrey;
for (int r = 0; r < nBalls; r++) {
- float b = (float) (r+1) / nBalls;
+ float b = (float) (r + 1) / nBalls;
for (int i = maxr; i >= 1; --i) {
float d = (float) i / maxr;
red[i] = (byte) blend(blend(Rl, 255, d), bgGrey, b);
@@ -510,11 +556,12 @@
blue[i] = (byte) blend(blend(Bl, 255, d), bgGrey, b);
}
IndexColorModel model = new IndexColorModel(8, maxr + 1,
- red, green, blue, 0);
+ red, green, blue, 0);
balls[r] = applet.createImage(
- new MemoryImageSource(R*2, R*2, model, data, 0, R*2));
+ new MemoryImageSource(R * 2, R * 2, model, data, 0, R * 2));
}
}
+
void paint(Graphics gc, int x, int y, int r) {
Image ba[] = balls;
if (ba == null) {
--- a/jdk/src/share/demo/applets/MoleculeViewer/example1.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/MoleculeViewer/example1.html Sun Apr 10 10:23:28 2011 -0700
@@ -6,7 +6,7 @@
<h1>MoleculeViewer (example 1)</h1>
<hr>
<applet code=XYZApp.class width=300 height=300>
- <param name=model value=models/HyaluronicAcid.xyz>
+ <param name=model value="models/HyaluronicAcid.xyz">
alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason."
Your browser is completely ignoring the <APPLET> tag!
</applet>
--- a/jdk/src/share/demo/applets/MoleculeViewer/example2.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/MoleculeViewer/example2.html Sun Apr 10 10:23:28 2011 -0700
@@ -6,7 +6,7 @@
<h1>MoleculeViewer (example 2)</h1>
<hr>
<applet code=XYZApp.class width=300 height=300>
- <param name=model value=models/buckminsterfullerine.xyz>
+ <param name=model value="models/buckminsterfullerine.xyz">
alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason."
Your browser is completely ignoring the <APPLET> tag!
</applet>
--- a/jdk/src/share/demo/applets/MoleculeViewer/example3.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/MoleculeViewer/example3.html Sun Apr 10 10:23:28 2011 -0700
@@ -6,25 +6,25 @@
<h1>MoleculeViewer (example 3)</h1>
<hr>
<applet code=XYZApp.class width=100 height=100>
- <param name=model value=models/water.xyz>
+ <param name=model value="models/water.xyz">
alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason."
Your browser is completely ignoring the <APPLET> tag!
</applet>
<p>
<applet code=XYZApp.class width=100 height=100>
- <param name=model value=models/benzene.xyz>
+ <param name=model value="models/benzene.xyz">
alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason."
Your browser is completely ignoring the <APPLET> tag!
</applet>
<p>
<applet code=XYZApp.class width=100 height=100>
- <param name=model value=models/ethane.xyz>
+ <param name=model value="models/ethane.xyz">
alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason."
Your browser is completely ignoring the <APPLET> tag!
</applet>
<p>
<applet code=XYZApp.class width=100 height=100>
- <param name=model value=models/cyclohexane.xyz>
+ <param name=model value="models/cyclohexane.xyz">
alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason."
Your browser is completely ignoring the <APPLET> tag!
</applet>
--- a/jdk/src/share/demo/applets/NervousText/NervousText.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/NervousText/NervousText.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,37 +29,37 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import java.awt.event.*;
import java.awt.Graphics;
import java.awt.Font;
import java.applet.Applet;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+
/**
* An applet that displays jittering text on the screen.
*
* @author Daniel Wyszynski 04/12/95
- * @modified 05/09/95 kwalrath Changed string; added thread suspension
- * @modified 02/06/98 madbot removed use of suspend and resume and cleaned up
+ * @author 05/09/95 kwalrath Changed string; added thread suspension
+ * @author 02/06/98 madbot removed use of suspend and resume and cleaned up
*/
+@SuppressWarnings("serial")
+public class NervousText extends Applet implements Runnable, MouseListener {
-public class NervousText extends Applet implements Runnable, MouseListener {
String banner; // The text to be displayed
char bannerChars[]; // The same text as an array of characters
char attributes[]; // Character attributes ('^' for superscript)
Thread runner = null; // The thread that is displaying the text
boolean threadSuspended; // True when thread suspended (via mouse click)
-
static final int REGULAR_WD = 15;
static final int REGULAR_HT = 36;
static final int SMALL_WD = 12;
static final int SMALL_HT = 24;
-
Font regularFont = new Font("Serif", Font.BOLD, REGULAR_HT);
Font smallFont = new Font("Serif", Font.BOLD, SMALL_HT);
+ @Override
public void init() {
banner = getParameter("text");
if (banner == null) {
@@ -67,8 +67,8 @@
}
int bannerLength = banner.length();
- StringBuffer bc = new StringBuffer(bannerLength);
- StringBuffer attrs = new StringBuffer(bannerLength);
+ StringBuilder bc = new StringBuilder(bannerLength);
+ StringBuilder attrs = new StringBuilder(bannerLength);
int wd = 0;
for (int i = 0; i < bannerLength; i++) {
char c = banner.charAt(i);
@@ -89,7 +89,7 @@
}
bannerLength = bc.length();
- bannerChars = new char[bannerLength];
+ bannerChars = new char[bannerLength];
attributes = new char[bannerLength];
bc.getChars(0, bannerLength, bannerChars, 0);
attrs.getChars(0, bannerLength, attributes, 0);
@@ -99,15 +99,18 @@
addMouseListener(this);
}
+ @Override
public void destroy() {
removeMouseListener(this);
}
+ @Override
public void start() {
runner = new Thread(this);
runner.start();
}
+ @Override
public synchronized void stop() {
runner = null;
if (threadSuspended) {
@@ -116,22 +119,24 @@
}
}
+ @Override
public void run() {
Thread me = Thread.currentThread();
while (runner == me) {
try {
Thread.sleep(100);
- synchronized(this) {
+ synchronized (this) {
while (threadSuspended) {
wait();
}
}
- } catch (InterruptedException e){
+ } catch (InterruptedException e) {
}
repaint();
}
}
+ @Override
public void paint(Graphics g) {
int length = bannerChars.length;
for (int i = 0, x = 0; i < length; i++) {
@@ -152,33 +157,41 @@
}
}
+ @Override
public synchronized void mousePressed(MouseEvent e) {
e.consume();
threadSuspended = !threadSuspended;
- if (!threadSuspended)
+ if (!threadSuspended) {
notify();
+ }
}
+ @Override
public void mouseReleased(MouseEvent e) {
}
+ @Override
public void mouseEntered(MouseEvent e) {
}
+ @Override
public void mouseExited(MouseEvent e) {
}
+ @Override
public void mouseClicked(MouseEvent e) {
}
+ @Override
public String getAppletInfo() {
- return "Title: NervousText\nAuthor: Daniel Wyszynski\nDisplays a text banner that jitters.";
+ return "Title: NervousText\nAuthor: Daniel Wyszynski\n"
+ + "Displays a text banner that jitters.";
}
+ @Override
public String[][] getParameterInfo() {
String pinfo[][] = {
- {"text", "string", "Text to display"},
- };
+ { "text", "string", "Text to display" }, };
return pinfo;
}
}
--- a/jdk/src/share/demo/applets/SimpleGraph/GraphApplet.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/SimpleGraph/GraphApplet.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,22 +29,26 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
import java.awt.Graphics;
+
+@SuppressWarnings("serial")
public class GraphApplet extends java.applet.Applet {
+
double f(double x) {
- return (Math.cos(x/5) + Math.sin(x/7) + 2) * getSize().height / 4;
+ return (Math.cos(x / 5) + Math.sin(x / 7) + 2) * getSize().height / 4;
}
+ @Override
public void paint(Graphics g) {
- for (int x = 0 ; x < getSize().width ; x++) {
- g.drawLine(x, (int)f(x), x + 1, (int)f(x + 1));
+ for (int x = 0; x < getSize().width; x++) {
+ g.drawLine(x, (int) f(x), x + 1, (int) f(x + 1));
}
}
- public String getAppletInfo() {
- return "Draws a sin graph.";
- }
+
+ @Override
+ public String getAppletInfo() {
+ return "Draws a sin graph.";
+ }
}
--- a/jdk/src/share/demo/applets/SortDemo/BidirBubbleSortAlgorithm.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/SortDemo/BidirBubbleSortAlgorithm.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,8 +29,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
/**
* A bi-directional bubble sort demonstration algorithm
@@ -39,6 +37,8 @@
* @author James Gosling
*/
class BidirBubbleSortAlgorithm extends SortAlgorithm {
+
+ @Override
void sort(int a[]) throws Exception {
int j;
int limit = a.length;
@@ -61,9 +61,9 @@
}
if (!swapped) {
return;
+ } else {
+ swapped = false;
}
- else
- swapped = false;
for (j = limit; --j >= st;) {
if (stopRequested) {
return;
--- a/jdk/src/share/demo/applets/SortDemo/BubbleSortAlgorithm.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/SortDemo/BubbleSortAlgorithm.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,8 +29,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
/**
* A bubble sort demonstration algorithm
@@ -39,23 +37,26 @@
* @author James Gosling
*/
class BubbleSortAlgorithm extends SortAlgorithm {
+
+ @Override
void sort(int a[]) throws Exception {
- for (int i = a.length; --i>=0; ) {
+ for (int i = a.length; --i >= 0;) {
boolean swapped = false;
- for (int j = 0; j<i; j++) {
+ for (int j = 0; j < i; j++) {
if (stopRequested) {
return;
}
- if (a[j] > a[j+1]) {
+ if (a[j] > a[j + 1]) {
int T = a[j];
- a[j] = a[j+1];
- a[j+1] = T;
+ a[j] = a[j + 1];
+ a[j + 1] = T;
swapped = true;
}
- pause(i,j);
+ pause(i, j);
}
- if (!swapped)
+ if (!swapped) {
return;
+ }
}
}
}
--- a/jdk/src/share/demo/applets/SortDemo/QSortAlgorithm.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/SortDemo/QSortAlgorithm.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,8 +29,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
/**
* A quick sort demonstration algorithm
@@ -39,8 +37,7 @@
* @author James Gosling
* @author Kevin A. Smith
*/
-public class QSortAlgorithm extends SortAlgorithm
-{
+public class QSortAlgorithm extends SortAlgorithm {
/**
* A version of pause() that makes it easier to ensure that we pause
@@ -51,84 +48,83 @@
return true;
}
- /** This is a generic version of C.A.R Hoare's Quick Sort
- * algorithm. This will handle arrays that are already
- * sorted, and arrays with duplicate keys.<BR>
- *
- * If you think of a one dimensional array as going from
- * the lowest index on the left to the highest index on the right
- * then the parameters to this function are lowest index or
- * left and highest index or right. The first time you call
- * this function it will be with the parameters 0, a.length - 1.
- *
- * @param a an integer array
- * @param lo0 left boundary of array partition
- * @param hi0 right boundary of array partition
- */
- void QuickSort(int a[], int lo0, int hi0) throws Exception
- {
- int lo = lo0;
- int hi = hi0;
- int mid;
+ /** This is a generic version of C.A.R Hoare's Quick Sort
+ * algorithm. This will handle arrays that are already
+ * sorted, and arrays with duplicate keys.<BR>
+ *
+ * If you think of a one dimensional array as going from
+ * the lowest index on the left to the highest index on the right
+ * then the parameters to this function are lowest index or
+ * left and highest index or right. The first time you call
+ * this function it will be with the parameters 0, a.length - 1.
+ *
+ * @param a an integer array
+ * @param lo0 left boundary of array partition
+ * @param hi0 right boundary of array partition
+ */
+ void QuickSort(int a[], int lo0, int hi0) throws Exception {
+ int lo = lo0;
+ int hi = hi0;
+ int mid;
- if ( hi0 > lo0)
- {
-
- /* Arbitrarily establishing partition element as the midpoint of
- * the array.
- */
- mid = a[ ( lo0 + hi0 ) / 2 ];
+ if (hi0 > lo0) {
- // loop through the array until indices cross
- while( lo <= hi )
- {
- /* find the first element that is greater than or equal to
- * the partition element starting from the left Index.
- */
- while( ( lo < hi0 ) && pauseTrue(lo0, hi0) && ( a[lo] < mid ))
- ++lo;
-
- /* find an element that is smaller than or equal to
- * the partition element starting from the right Index.
+ /* Arbitrarily establishing partition element as the midpoint of
+ * the array.
*/
- while( ( hi > lo0 ) && pauseTrue(lo0, hi0) && ( a[hi] > mid ))
- --hi;
+ mid = a[(lo0 + hi0) / 2];
+
+ // loop through the array until indices cross
+ while (lo <= hi) {
+ /* find the first element that is greater than or equal to
+ * the partition element starting from the left Index.
+ */
+ while ((lo < hi0) && pauseTrue(lo0, hi0) && (a[lo] < mid)) {
+ ++lo;
+ }
- // if the indexes have not crossed, swap
- if( lo <= hi )
- {
- swap(a, lo, hi);
- ++lo;
- --hi;
+ /* find an element that is smaller than or equal to
+ * the partition element starting from the right Index.
+ */
+ while ((hi > lo0) && pauseTrue(lo0, hi0) && (a[hi] > mid)) {
+ --hi;
+ }
+
+ // if the indexes have not crossed, swap
+ if (lo <= hi) {
+ swap(a, lo, hi);
+ ++lo;
+ --hi;
+ }
}
- }
-
- /* If the right index has not reached the left side of array
- * must now sort the left partition.
- */
- if( lo0 < hi )
- QuickSort( a, lo0, hi );
- /* If the left index has not reached the right side of array
- * must now sort the right partition.
- */
- if( lo < hi0 )
- QuickSort( a, lo, hi0 );
+ /* If the right index has not reached the left side of array
+ * must now sort the left partition.
+ */
+ if (lo0 < hi) {
+ QuickSort(a, lo0, hi);
+ }
- }
- }
+ /* If the left index has not reached the right side of array
+ * must now sort the right partition.
+ */
+ if (lo < hi0) {
+ QuickSort(a, lo, hi0);
+ }
- private void swap(int a[], int i, int j)
- {
- int T;
- T = a[i];
- a[i] = a[j];
- a[j] = T;
+ }
+ }
- }
+ private void swap(int a[], int i, int j) {
+ int T;
+ T = a[i];
+ a[i] = a[j];
+ a[j] = T;
- public void sort(int a[]) throws Exception
- {
- QuickSort(a, 0, a.length - 1);
- }
+ }
+
+ @Override
+ public void sort(int a[]) throws Exception {
+ QuickSort(a, 0, a.length - 1);
+ }
}
--- a/jdk/src/share/demo/applets/SortDemo/SortAlgorithm.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/SortDemo/SortAlgorithm.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,8 +29,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
/**
* A generic sort demonstration algorithm
@@ -38,13 +36,12 @@
*
* @author James Gosling
*/
+class SortAlgorithm {
-class SortAlgorithm {
/**
* The sort item.
*/
private SortItem parent;
-
/**
* When true stop sorting.
*/
--- a/jdk/src/share/demo/applets/SortDemo/SortItem.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/SortDemo/SortItem.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,57 +29,50 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import java.awt.*;
-import java.awt.event.*;
-import java.io.InputStream;
-import java.util.Hashtable;
-import java.net.*;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Graphics;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+
/**
* A simple applet class to demonstrate a sort algorithm.
* You can specify a sorting algorithm using the "alg"
- * attribyte. When you click on the applet, a thread is
+ * attribute. When you click on the applet, a thread is
* forked which animates the sorting algorithm.
*
* @author James Gosling
*/
-public class SortItem
- extends java.applet.Applet
- implements Runnable, MouseListener {
+@SuppressWarnings("serial")
+public class SortItem extends java.applet.Applet implements Runnable,
+ MouseListener {
/**
* The thread that is sorting (or null).
*/
private Thread kicker;
-
/**
* The array that is being sorted.
*/
int arr[];
-
/**
* The high water mark.
*/
int h1 = -1;
-
/**
* The low water mark.
*/
int h2 = -1;
-
/**
* The name of the algorithm.
*/
String algName;
-
/**
* The sorting algorithm (or null).
*/
SortAlgorithm algorithm;
-
Dimension initialSize = null;
/**
@@ -91,10 +84,10 @@
double f = initialSize.width / (double) a.length;
for (int i = a.length; --i >= 0;) {
- a[i] = (int)(i * f);
+ a[i] = (int) (i * f);
}
for (int i = a.length; --i >= 0;) {
- int j = (int)(i * Math.random());
+ int j = (int) (i * Math.random());
int t = a[i];
a[i] = a[j];
a[j] = t;
@@ -128,12 +121,16 @@
if (kicker != null) {
repaint();
}
- try {Thread.sleep(20);} catch (InterruptedException e){}
+ try {
+ Thread.sleep(20);
+ } catch (InterruptedException e) {
+ }
}
/**
* Initialize the applet.
*/
+ @Override
public void init() {
String at = getParameter("alg");
if (at == null) {
@@ -147,6 +144,7 @@
addMouseListener(this);
}
+ @Override
public void start() {
h1 = h2 = -1;
scramble();
@@ -157,6 +155,7 @@
/**
* Deallocate resources of applet.
*/
+ @Override
public void destroy() {
removeMouseListener(this);
}
@@ -165,10 +164,11 @@
* Paint the array of numbers as a list
* of horizontal lines of varying lengths.
*/
+ @Override
public void paint(Graphics g) {
int a[] = arr;
int y = 0;
- int deltaY = 0, deltaX = 0, evenY = 0, evenX = 0;
+ int deltaY = 0, deltaX = 0, evenY = 0;
Dimension currentSize = getSize();
int currentHeight = currentSize.height;
@@ -184,7 +184,6 @@
// even size.
if (!currentSize.equals(initialSize)) {
evenY = (currentHeight - initialSize.height) % 2;
- evenX = (currentWidth - initialSize.width) % 2;
deltaY = (currentHeight - initialSize.height) / 2;
deltaX = (currentWidth - initialSize.width) / 2;
@@ -194,7 +193,6 @@
}
if (deltaX < 0) {
deltaX = 0;
- evenX = 0;
}
}
@@ -227,6 +225,7 @@
/**
* Update without erasing the background.
*/
+ @Override
public void update(Graphics g) {
paint(g);
}
@@ -238,15 +237,16 @@
* @see java.lang.Thread#run
* @see SortItem#mouseUp
*/
+ @Override
public void run() {
try {
if (algorithm == null) {
- algorithm = (SortAlgorithm)Class.forName(algName).newInstance();
+ algorithm = (SortAlgorithm) Class.forName(algName).newInstance();
algorithm.setParent(this);
}
algorithm.init();
algorithm.sort(arr);
- } catch(Exception e) {
+ } catch (Exception e) {
}
}
@@ -254,8 +254,9 @@
* Stop the applet. Kill any sorting algorithm that
* is still sorting.
*/
+ @Override
public synchronized void stop() {
- if (algorithm != null){
+ if (algorithm != null) {
try {
algorithm.stop();
} catch (IllegalThreadStateException e) {
@@ -279,35 +280,42 @@
}
}
-
+ @Override
public void mouseClicked(MouseEvent e) {
showStatus(getParameter("alg"));
}
+ @Override
public void mousePressed(MouseEvent e) {
}
/**
* The user clicked in the applet. Start the clock!
*/
+ @Override
public void mouseReleased(MouseEvent e) {
startSort();
e.consume();
}
+ @Override
public void mouseEntered(MouseEvent e) {
}
+ @Override
public void mouseExited(MouseEvent e) {
}
+ @Override
public String getAppletInfo() {
return "Title: SortDemo \nAuthor: James Gosling 1.17f, 10 Apr 1995 \nA simple applet class to demonstrate a sort algorithm. \nYou can specify a sorting algorithm using the 'alg' attribute. \nWhen you click on the applet, a thread is forked which animates \nthe sorting algorithm.";
}
+ @Override
public String[][] getParameterInfo() {
String[][] info = {
- {"alg", "string", "The name of the algorithm to run. You can choose from the provided algorithms or suppply your own, as long as the classes are runnable as threads and their names end in 'Algorithm.' BubbleSort is the default. Example: Use 'QSort' to run the QSortAlgorithm class."}
+ { "alg", "string",
+ "The name of the algorithm to run. You can choose from the provided algorithms or suppply your own, as long as the classes are runnable as threads and their names end in 'Algorithm.' BubbleSort is the default. Example: Use 'QSort' to run the QSortAlgorithm class." }
};
return info;
}
--- a/jdk/src/share/demo/applets/SortDemo/example1.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/SortDemo/example1.html Sun Apr 10 10:23:28 2011 -0700
@@ -6,7 +6,7 @@
<h1>The Sorting Algorithm Demo (1.1)</h1>
<hr>
- <table cols=3 width="340">
+ <table width="340">
<tr>
<th><strong>Bubble Sort</strong></th>
<th><strong>Bidirectional Bubble Sort</strong></th>
--- a/jdk/src/share/demo/applets/SpreadSheet/SpreadSheet.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/SpreadSheet/SpreadSheet.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,39 +29,38 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
-import java.lang.*;
import java.net.*;
-public class SpreadSheet
- extends Applet
- implements MouseListener, KeyListener {
- String title;
- Font titleFont;
- Color cellColor;
- Color inputColor;
- int cellWidth = 100;
- int cellHeight = 15;
- int titleHeight = 15;
- int rowLabelWidth = 15;
- Font inputFont;
- boolean isStopped = false;
- boolean fullUpdate = true;
- int rows;
- int columns;
- int currentKey = -1;
- int selectedRow = -1;
- int selectedColumn = -1;
- SpreadSheetInput inputArea;
- Cell cells[][];
- Cell current = null;
+
+@SuppressWarnings("serial")
+public class SpreadSheet extends Applet implements MouseListener, KeyListener {
+ String title;
+ Font titleFont;
+ Color cellColor;
+ Color inputColor;
+ int cellWidth = 100;
+ int cellHeight = 15;
+ int titleHeight = 15;
+ int rowLabelWidth = 15;
+ Font inputFont;
+ boolean isStopped = false;
+ boolean fullUpdate = true;
+ int rows;
+ int columns;
+ int currentKey = -1;
+ int selectedRow = -1;
+ int selectedColumn = -1;
+ SpreadSheetInput inputArea;
+ Cell cells[][];
+ Cell current = null;
+
+ @Override
public synchronized void init() {
String rs;
@@ -87,17 +86,17 @@
}
cells = new Cell[rows][columns];
char l[] = new char[1];
- for (int i=0; i < rows; i++) {
- for (int j=0; j < columns; j++) {
+ for (int i = 0; i < rows; i++) {
+ for (int j = 0; j < columns; j++) {
cells[i][j] = new Cell(this,
- Color.lightGray,
- Color.black,
- cellColor,
- cellWidth - 2,
- cellHeight - 2);
- l[0] = (char)((int)'a' + j);
- rs = getParameter("" + new String(l) + (i+1));
+ Color.lightGray,
+ Color.black,
+ cellColor,
+ cellWidth - 2,
+ cellHeight - 2);
+ l[0] = (char) ((int) 'a' + j);
+ rs = getParameter("" + new String(l) + (i + 1));
if (rs != null) {
cells[i][j].setUnparsedValue(rs);
}
@@ -106,9 +105,9 @@
Dimension d = getSize();
inputArea = new SpreadSheetInput(null, this, d.width - 2, cellHeight - 1,
- inputColor, Color.white);
+ inputColor, Color.white);
resize(columns * cellWidth + rowLabelWidth,
- (rows + 3) * cellHeight + titleHeight);
+ (rows + 3) * cellHeight + titleHeight);
addMouseListener(this);
addKeyListener(this);
}
@@ -121,19 +120,22 @@
repaint();
}
+ @Override
public void stop() {
isStopped = true;
}
+ @Override
public void start() {
isStopped = false;
}
+ @Override
public void destroy() {
- for (int i=0; i < rows; i++) {
- for (int j=0; j < columns; j++) {
+ for (int i = 0; i < rows; i++) {
+ for (int j = 0; j < columns; j++) {
if (cells[i][j].type == Cell.URL) {
- cells[i][j].updaterThread.stop();
+ cells[i][j].updaterThread.run = false;
}
}
}
@@ -147,16 +149,17 @@
repaint();
}
+ @Override
public void update(Graphics g) {
- if (! fullUpdate) {
+ if (!fullUpdate) {
int cx, cy;
g.setFont(titleFont);
- for (int i=0; i < rows; i++) {
- for (int j=0; j < columns; j++) {
+ for (int i = 0; i < rows; i++) {
+ for (int j = 0; j < columns; j++) {
if (cells[i][j].needRedisplay) {
cx = (j * cellWidth) + 2 + rowLabelWidth;
- cy = ((i+1) * cellHeight) + 2 + titleHeight;
+ cy = ((i + 1) * cellHeight) + 2 + titleHeight;
cells[i][j].paint(g, cx, cy);
}
}
@@ -168,13 +171,14 @@
}
public void recalculate() {
- int i,j;
+ int i, j;
//System.out.println("SpreadSheet.recalculate");
- for (i=0; i < rows; i++) {
- for (j=0; j < columns; j++) {
+ for (i = 0; i < rows; i++) {
+ for (j = 0; j < columns; j++) {
if (cells[i][j] != null && cells[i][j].type == Cell.FORMULA) {
- cells[i][j].setRawValue(evaluateFormula(cells[i][j].parseRoot));
+ cells[i][j].setRawValue(evaluateFormula(
+ cells[i][j].parseRoot));
cells[i][j].needRedisplay = true;
}
}
@@ -182,8 +186,8 @@
repaint();
}
- public float evaluateFormula(Node n) {
- float val = 0.0f;
+ float evaluateFormula(Node n) {
+ float val = 0.0f;
//System.out.println("evaluateFormula:");
//n.print(3);
@@ -192,43 +196,40 @@
return val;
}
switch (n.type) {
- case Node.OP:
- val = evaluateFormula(n.left);
- switch (n.op) {
- case '+':
- val += evaluateFormula(n.right);
- break;
- case '*':
- val *= evaluateFormula(n.right);
- break;
- case '-':
- val -= evaluateFormula(n.right);
+ case Node.OP:
+ val = evaluateFormula(n.left);
+ switch (n.op) {
+ case '+':
+ val += evaluateFormula(n.right);
+ break;
+ case '*':
+ val *= evaluateFormula(n.right);
+ break;
+ case '-':
+ val -= evaluateFormula(n.right);
+ break;
+ case '/':
+ val /= evaluateFormula(n.right);
+ break;
+ }
break;
- case '/':
- val /= evaluateFormula(n.right);
- break;
- }
- break;
- case Node.VALUE:
- //System.out.println("=>" + n.value);
- return n.value;
- case Node.CELL:
- if (n == null) {
- //System.out.println("NULL at 192");
- } else {
+ case Node.VALUE:
+ //System.out.println("=>" + n.value);
+ return n.value;
+ case Node.CELL:
if (cells[n.row][n.column] == null) {
//System.out.println("NULL at 193");
} else {
//System.out.println("=>" + cells[n.row][n.column].value);
return cells[n.row][n.column].value;
}
- }
}
//System.out.println("=>" + val);
return val;
}
+ @Override
public synchronized void paint(Graphics g) {
int i, j;
int cx, cy;
@@ -240,40 +241,40 @@
g.setFont(titleFont);
i = g.getFontMetrics().stringWidth(title);
g.drawString((title == null) ? "Spreadsheet" : title,
- (d.width - i) / 2, 12);
+ (d.width - i) / 2, 12);
g.setColor(inputColor);
g.fillRect(0, cellHeight, d.width, cellHeight);
g.setFont(titleFont);
- for (i=0; i < rows+1; i++) {
- cy = (i+2) * cellHeight;
+ for (i = 0; i < rows + 1; i++) {
+ cy = (i + 2) * cellHeight;
g.setColor(getBackground());
g.draw3DRect(0, cy, d.width, 2, true);
if (i < rows) {
g.setColor(Color.red);
- g.drawString("" + (i+1), 2, cy + 12);
+ g.drawString("" + (i + 1), 2, cy + 12);
}
}
g.setColor(Color.red);
- cy = (rows+3) * cellHeight + (cellHeight / 2);
- for (i=0; i < columns; i++) {
+ cy = (rows + 3) * cellHeight + (cellHeight / 2);
+ for (i = 0; i < columns; i++) {
cx = i * cellWidth;
g.setColor(getBackground());
g.draw3DRect(cx + rowLabelWidth,
- 2 * cellHeight, 1, d.height, true);
+ 2 * cellHeight, 1, d.height, true);
if (i < columns) {
g.setColor(Color.red);
- l[0] = (char)((int)'A' + i);
+ l[0] = (char) ((int) 'A' + i);
g.drawString(new String(l),
- cx + rowLabelWidth + (cellWidth / 2),
- cy);
+ cx + rowLabelWidth + (cellWidth / 2),
+ cy);
}
}
- for (i=0; i < rows; i++) {
- for (j=0; j < columns; j++) {
+ for (i = 0; i < rows; i++) {
+ for (j = 0; j < columns; j++) {
cx = (j * cellWidth) + 2 + rowLabelWidth;
- cy = ((i+1) * cellHeight) + 2 + titleHeight;
+ cy = ((i + 1) * cellHeight) + 2 + titleHeight;
if (cells[i][j] != null) {
cells[i][j].paint(g, cx, cy);
}
@@ -282,141 +283,152 @@
g.setColor(getBackground());
g.draw3DRect(0, titleHeight,
- d.width,
- d.height - titleHeight,
- false);
+ d.width,
+ d.height - titleHeight,
+ false);
inputArea.paint(g, 1, titleHeight + 1);
}
- //1.1 event handling
-
- public void mouseClicked(MouseEvent e)
- {}
-
- public void mousePressed(MouseEvent e)
- {
- int x = e.getX();
- int y = e.getY();
- Cell cell;
- if (y < (titleHeight + cellHeight)) {
- selectedRow = -1;
- if (y <= titleHeight && current != null) {
- current.deselect();
- current = null;
- }
- e.consume();
+ //1.1 event handling
+ @Override
+ public void mouseClicked(MouseEvent e) {
}
- if (x < rowLabelWidth) {
- selectedRow = -1;
- if (current != null) {
- current.deselect();
+
+ @Override
+ public void mousePressed(MouseEvent e) {
+ int x = e.getX();
+ int y = e.getY();
+ Cell cell;
+ if (y < (titleHeight + cellHeight)) {
+ selectedRow = -1;
+ if (y <= titleHeight && current != null) {
+ current.deselect();
+ current = null;
+ }
+ e.consume();
+ }
+ if (x < rowLabelWidth) {
+ selectedRow = -1;
+ if (current != null) {
+ current.deselect();
current = null;
- }
- e.consume();
+ }
+ e.consume();
+ }
+ selectedRow = ((y - cellHeight - titleHeight) / cellHeight);
+ selectedColumn = (x - rowLabelWidth) / cellWidth;
+ if (selectedRow > rows
+ || selectedColumn >= columns) {
+ selectedRow = -1;
+ if (current != null) {
+ current.deselect();
+ current = null;
+ }
+ } else {
+ if (selectedRow >= rows) {
+ selectedRow = -1;
+ if (current != null) {
+ current.deselect();
+ current = null;
+ }
+ e.consume();
+ }
+ if (selectedRow != -1) {
+ cell = cells[selectedRow][selectedColumn];
+ inputArea.setText(cell.getPrintString());
+ if (current != null) {
+ current.deselect();
+ }
+ current = cell;
+ current.select();
+ requestFocus();
+ fullUpdate = true;
+ repaint();
+ }
+ e.consume();
+ }
}
- selectedRow = ((y - cellHeight - titleHeight) / cellHeight);
- selectedColumn = (x - rowLabelWidth) / cellWidth;
- if (selectedRow > rows ||
- selectedColumn >= columns) {
- selectedRow = -1;
- if (current != null) {
- current.deselect();
- current = null;
- }
- } else {
- if (selectedRow >= rows) {
- selectedRow = -1;
- if (current != null) {
- current.deselect();
- current = null;
- }
+
+ @Override
+ public void mouseReleased(MouseEvent e) {
+ }
+
+ @Override
+ public void mouseEntered(MouseEvent e) {
+ }
+
+ @Override
+ public void mouseExited(MouseEvent e) {
+ }
+
+ @Override
+ public void keyPressed(KeyEvent e) {
+ }
+
+ @Override
+ public void keyTyped(KeyEvent e) {
+ fullUpdate = true;
+ inputArea.processKey(e);
e.consume();
- }
- if (selectedRow != -1) {
- cell = cells[selectedRow][selectedColumn];
- inputArea.setText(new String(cell.getPrintString()));
- if (current != null) {
- current.deselect();
- }
- current = cell;
- current.select();
- requestFocus();
- fullUpdate = true;
- repaint();
- }
- e.consume();
+ }
+
+ @Override
+ public void keyReleased(KeyEvent e) {
}
- }
- public void mouseReleased(MouseEvent e)
- {}
-
- public void mouseEntered(MouseEvent e)
- {}
-
- public void mouseExited(MouseEvent e)
- {}
+ @Override
+ public String getAppletInfo() {
+ return "Title: SpreadSheet \nAuthor: Sami Shaio \nA simple spread sheet.";
+ }
- public void keyPressed(KeyEvent e)
- {
- }
-
- public void keyTyped(KeyEvent e) {
- fullUpdate=true;
- inputArea.processKey(e);
- e.consume();
- }
-
- public void keyReleased(KeyEvent e)
- {}
-
- public String getAppletInfo() {
- return "Title: SpreadSheet \nAuthor: Sami Shaio \nA simple spread sheet.";
- }
-
- public String[][] getParameterInfo() {
- String[][] info = {
- {"title", "string", "The title of the spread sheet. Default is 'Spreadsheet'"},
- {"rows", "int", "The number of rows. Default is 9."},
- {"columns", "int", "The number of columns. Default is 5."}
- };
- return info;
- }
+ @Override
+ public String[][] getParameterInfo() {
+ String[][] info = {
+ { "title", "string",
+ "The title of the spread sheet. Default is 'Spreadsheet'" },
+ { "rows", "int", "The number of rows. Default is 9." },
+ { "columns", "int", "The number of columns. Default is 5." }
+ };
+ return info;
+ }
+}
-}
+class CellUpdater extends Thread {
-class CellUpdater extends Thread {
- Cell target;
+ Cell target;
InputStream dataStream = null;
StreamTokenizer tokenStream;
+ public volatile boolean run = true;
public CellUpdater(Cell c) {
super("cell updater");
target = c;
}
+ @Override
public void run() {
try {
dataStream = new URL(target.app.getDocumentBase(),
- target.getValueString()).openStream();
- tokenStream = new StreamTokenizer(new BufferedReader(new InputStreamReader(dataStream)));
+ target.getValueString()).openStream();
+ tokenStream = new StreamTokenizer(new BufferedReader(
+ new InputStreamReader(dataStream)));
tokenStream.eolIsSignificant(false);
- while (true) {
+ while (run) {
switch (tokenStream.nextToken()) {
- case StreamTokenizer.TT_EOF:
- dataStream.close();
- return;
- default:
- break;
- case StreamTokenizer.TT_NUMBER:
- target.setTransientValue((float)tokenStream.nval);
- if (! target.app.isStopped && ! target.paused) {
- target.app.repaint();
- }
- break;
+ case StreamTokenizer.TT_EOF:
+ dataStream.close();
+ return;
+ default:
+ break;
+ case StreamTokenizer.TT_NUMBER:
+ target.setTransientValue((float) tokenStream.nval);
+ if (!target.app.isStopped && !target.paused) {
+ target.app.repaint();
+ }
+ break;
}
try {
Thread.sleep(2000);
@@ -430,35 +442,36 @@
}
}
+
class Cell {
+
public static final int VALUE = 0;
public static final int LABEL = 1;
- public static final int URL = 2;
+ public static final int URL = 2;
public static final int FORMULA = 3;
-
- Node parseRoot;
- boolean needRedisplay;
+ Node parseRoot;
+ boolean needRedisplay;
boolean selected = false;
boolean transientValue = false;
- public int type = Cell.VALUE;
- String valueString = "";
- String printString = "v";
- float value;
- Color bgColor;
- Color fgColor;
- Color highlightColor;
- int width;
- int height;
+ public int type = Cell.VALUE;
+ String valueString = "";
+ String printString = "v";
+ float value;
+ Color bgColor;
+ Color fgColor;
+ Color highlightColor;
+ int width;
+ int height;
SpreadSheet app;
CellUpdater updaterThread;
- boolean paused = false;
+ boolean paused = false;
public Cell(SpreadSheet app,
- Color bgColor,
- Color fgColor,
- Color highlightColor,
- int width,
- int height) {
+ Color bgColor,
+ Color fgColor,
+ Color highlightColor,
+ int width,
+ int height) {
this.app = app;
this.bgColor = bgColor;
this.fgColor = fgColor;
@@ -472,6 +485,7 @@
valueString = Float.toString(f);
value = f;
}
+
public void setValue(float f) {
setRawValue(f);
printString = "v" + valueString;
@@ -490,18 +504,18 @@
public void setUnparsedValue(String s) {
switch (s.charAt(0)) {
- case 'v':
- setValue(Cell.VALUE, s.substring(1));
- break;
- case 'f':
- setValue(Cell.FORMULA, s.substring(1));
- break;
- case 'l':
- setValue(Cell.LABEL, s.substring(1));
- break;
- case 'u':
- setValue(Cell.URL, s.substring(1));
- break;
+ case 'v':
+ setValue(Cell.VALUE, s.substring(1));
+ break;
+ case 'f':
+ setValue(Cell.FORMULA, s.substring(1));
+ break;
+ case 'l':
+ setValue(Cell.LABEL, s.substring(1));
+ break;
+ case 'u':
+ setValue(Cell.URL, s.substring(1));
+ break;
}
}
@@ -519,8 +533,6 @@
public String parseFormula(String formula, Node node) {
String subformula;
String restFormula;
- float value;
- int length = formula.length();
Node left;
Node right;
char op;
@@ -534,52 +546,53 @@
//System.out.println("Parse succeeded");
return null;
}
- if (subformula == formula) {
+ if (subformula.equals(formula)) {
//System.out.println("Parse failed");
return formula;
}
// parse an operator and then another value
switch (op = subformula.charAt(0)) {
- case 0:
- //System.out.println("Parse succeeded");
- return null;
- case ')':
- //System.out.println("Returning subformula=" + subformula);
- return subformula;
- case '+':
- case '*':
- case '-':
- case '/':
- restFormula = subformula.substring(1);
- subformula = parseValue(restFormula, right=new Node());
- //System.out.println("subformula(2) = " + subformula);
- if (subformula != restFormula) {
+ case 0:
//System.out.println("Parse succeeded");
- left = new Node(node);
- node.left = left;
- node.right = right;
- node.op = op;
- node.type = Node.OP;
- //node.print(3);
+ return null;
+ case ')':
+ //System.out.println("Returning subformula=" + subformula);
return subformula;
- } else {
- //System.out.println("Parse failed");
+ case '+':
+ case '*':
+ case '-':
+ case '/':
+ restFormula = subformula.substring(1);
+ subformula = parseValue(restFormula, right = new Node());
+ //System.out.println("subformula(2) = " + subformula);
+ if (subformula == null ? restFormula != null : !subformula.
+ equals(restFormula)) {
+ //System.out.println("Parse succeeded");
+ left = new Node(node);
+ node.left = left;
+ node.right = right;
+ node.op = op;
+ node.type = Node.OP;
+ //node.print(3);
+ return subformula;
+ } else {
+ //System.out.println("Parse failed");
+ return formula;
+ }
+ default:
+ //System.out.println("Parse failed (bad operator): " + subformula);
return formula;
- }
- default:
- //System.out.println("Parse failed (bad operator): " + subformula);
- return formula;
}
}
public String parseValue(String formula, Node node) {
- char c = formula.charAt(0);
- String subformula;
- String restFormula;
- float value;
- int row;
- int column;
+ char c = formula.charAt(0);
+ String subformula;
+ String restFormula;
+ float _value;
+ int row;
+ int column;
//System.out.println("parseValue: " + formula);
restFormula = formula;
@@ -588,11 +601,11 @@
restFormula = formula.substring(1);
subformula = parseFormula(restFormula, node);
//System.out.println("rest=(" + subformula + ")");
- if (subformula == null ||
- subformula.length() == restFormula.length()) {
+ if (subformula == null
+ || subformula.length() == restFormula.length()) {
//System.out.println("Failed");
return formula;
- } else if (! (subformula.charAt(0) == ')')) {
+ } else if (!(subformula.charAt(0) == ')')) {
//System.out.println("Failed (missing parentheses)");
return formula;
}
@@ -601,31 +614,31 @@
int i;
//System.out.println("formula=" + formula);
- for (i=0; i < formula.length(); i++) {
+ for (i = 0; i < formula.length(); i++) {
c = formula.charAt(i);
if ((c < '0' || c > '9') && c != '.') {
break;
}
}
try {
- value = Float.valueOf(formula.substring(0, i)).floatValue();
+ _value = Float.valueOf(formula.substring(0, i)).floatValue();
} catch (NumberFormatException e) {
//System.out.println("Failed (number format error)");
return formula;
}
node.type = Node.VALUE;
- node.value = value;
+ node.value = _value;
//node.print(3);
restFormula = formula.substring(i);
//System.out.println("value= " + value + " i=" + i +
- // " rest = " + restFormula);
+ // " rest = " + restFormula);
return restFormula;
} else if (c >= 'A' && c <= 'Z') {
int i;
column = c - 'A';
restFormula = formula.substring(1);
- for (i=0; i < restFormula.length(); i++) {
+ for (i = 0; i < restFormula.length(); i++) {
c = restFormula.charAt(i);
if (c < '0' || c > '9') {
break;
@@ -650,33 +663,32 @@
return restFormula;
}
-
public void setValue(int type, String s) {
paused = false;
if (this.type == Cell.URL) {
- updaterThread.stop();
+ updaterThread.run = false;
updaterThread = null;
}
- valueString = new String(s);
+ valueString = s;
this.type = type;
needRedisplay = true;
switch (type) {
- case Cell.VALUE:
- setValue(Float.valueOf(s).floatValue());
- break;
- case Cell.LABEL:
- printString = "l" + valueString;
- break;
- case Cell.URL:
- printString = "u" + valueString;
- updaterThread = new CellUpdater(this);
- updaterThread.start();
- break;
- case Cell.FORMULA:
- parseFormula(valueString, parseRoot = new Node());
- printString = "f" + valueString;
- break;
+ case Cell.VALUE:
+ setValue(Float.valueOf(s).floatValue());
+ break;
+ case Cell.LABEL:
+ printString = "l" + valueString;
+ break;
+ case Cell.URL:
+ printString = "u" + valueString;
+ updaterThread = new CellUpdater(this);
+ updaterThread.start();
+ break;
+ case Cell.FORMULA:
+ parseFormula(valueString, parseRoot = new Node());
+ printString = "f" + valueString;
+ break;
}
app.recalculate();
}
@@ -693,12 +705,14 @@
selected = true;
paused = true;
}
+
public void deselect() {
selected = false;
paused = false;
needRedisplay = true;
app.repaint();
}
+
public void paint(Graphics g, int x, int y) {
if (selected) {
g.setColor(highlightColor);
@@ -708,23 +722,23 @@
g.fillRect(x, y, width - 1, height);
if (valueString != null) {
switch (type) {
- case Cell.VALUE:
- case Cell.LABEL:
- g.setColor(fgColor);
- break;
- case Cell.FORMULA:
- g.setColor(Color.red);
- break;
- case Cell.URL:
- g.setColor(Color.blue);
- break;
+ case Cell.VALUE:
+ case Cell.LABEL:
+ g.setColor(fgColor);
+ break;
+ case Cell.FORMULA:
+ g.setColor(Color.red);
+ break;
+ case Cell.URL:
+ g.setColor(Color.blue);
+ break;
}
- if (transientValue){
+ if (transientValue) {
g.drawString("" + value, x, y + (height / 2) + 5);
} else {
if (valueString.length() > 14) {
g.drawString(valueString.substring(0, 14),
- x, y + (height / 2) + 5);
+ x, y + (height / 2) + 5);
} else {
g.drawString(valueString, x, y + (height / 2) + 5);
}
@@ -734,18 +748,19 @@
}
}
+
class Node {
+
public static final int OP = 0;
public static final int VALUE = 1;
public static final int CELL = 2;
-
- int type;
- Node left;
- Node right;
- int row;
- int column;
- float value;
- char op;
+ int type;
+ Node left;
+ Node right;
+ int row;
+ int column;
+ float value;
+ char op;
public Node() {
left = null;
@@ -756,6 +771,7 @@
op = 0;
type = Node.VALUE;
}
+
public Node(Node n) {
left = n.left;
right = n.right;
@@ -765,47 +781,51 @@
op = n.op;
type = n.type;
}
+
public void indent(int ind) {
for (int i = 0; i < ind; i++) {
System.out.print(" ");
}
}
+
public void print(int indentLevel) {
char l[] = new char[1];
indent(indentLevel);
System.out.println("NODE type=" + type);
indent(indentLevel);
switch (type) {
- case Node.VALUE:
- System.out.println(" value=" + value);
- break;
- case Node.CELL:
- l[0] = (char)((int)'A' + column);
- System.out.println(" cell=" + new String(l) + (row+1));
- break;
- case Node.OP:
- System.out.println(" op=" + op);
- left.print(indentLevel + 3);
- right.print(indentLevel + 3);
- break;
+ case Node.VALUE:
+ System.out.println(" value=" + value);
+ break;
+ case Node.CELL:
+ l[0] = (char) ((int) 'A' + column);
+ System.out.println(" cell=" + new String(l) + (row + 1));
+ break;
+ case Node.OP:
+ System.out.println(" op=" + op);
+ left.print(indentLevel + 3);
+ right.print(indentLevel + 3);
+ break;
}
}
}
+
class InputField {
- int maxchars = 50;
- int cursorPos = 0;
- Applet app;
- String sval;
- char buffer[];
- int nChars;
- int width;
- int height;
- Color bgColor;
- Color fgColor;
+
+ int maxchars = 50;
+ int cursorPos = 0;
+ Applet app;
+ String sval;
+ char buffer[];
+ int nChars;
+ int width;
+ int height;
+ Color bgColor;
+ Color fgColor;
public InputField(String initValue, Applet app, int width, int height,
- Color bgColor, Color fgColor) {
+ Color bgColor, Color fgColor) {
this.width = width;
this.height = height;
this.bgColor = bgColor;
@@ -823,7 +843,7 @@
public void setText(String val) {
int i;
- for (i=0; i < maxchars; i++) {
+ for (i = 0; i < maxchars; i++) {
buffer[i] = 0;
}
if (val == null) {
@@ -876,47 +896,52 @@
}
}
+
class SpreadSheetInput
- extends InputField {
+ extends InputField {
- public SpreadSheetInput(String initValue,
- SpreadSheet app,
- int width,
- int height,
- Color bgColor,
- Color fgColor) {
- super(initValue, app, width, height, bgColor, fgColor);
- }
+ public SpreadSheetInput(String initValue,
+ SpreadSheet app,
+ int width,
+ int height,
+ Color bgColor,
+ Color fgColor) {
+ super(initValue, app, width, height, bgColor, fgColor);
+ }
+ @Override
public void selected() {
float f;
- sval = ("".equals(sval)) ? "v":sval;
+ sval = ("".equals(sval)) ? "v" : sval;
switch (sval.charAt(0)) {
- case 'v':
- String s= sval.substring(1);
- try {
- int i;
- for (i = 0; i < s.length(); i++) {
- char c = s.charAt(i);
- if (c < '0' || c > '9')
- break;
+ case 'v':
+ String s = sval.substring(1);
+ try {
+ int i;
+ for (i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ if (c < '0' || c > '9') {
+ break;
+ }
+ }
+ s = s.substring(0, i);
+ f = Float.valueOf(s).floatValue();
+ ((SpreadSheet) app).setCurrentValue(f);
+ } catch (NumberFormatException e) {
+ System.out.println("Not a float: '" + s + "'");
}
- s = s.substring(0, i);
- f = Float.valueOf(s).floatValue();
- ((SpreadSheet)app).setCurrentValue(f);
- } catch (NumberFormatException e) {
- System.out.println("Not a float: '" + s + "'");
- }
- break;
- case 'l':
- ((SpreadSheet)app).setCurrentValue(Cell.LABEL, sval.substring(1));
- break;
- case 'u':
- ((SpreadSheet)app).setCurrentValue(Cell.URL, sval.substring(1));
- break;
- case 'f':
- ((SpreadSheet)app).setCurrentValue(Cell.FORMULA, sval.substring(1));
- break;
+ break;
+ case 'l':
+ ((SpreadSheet) app).setCurrentValue(Cell.LABEL,
+ sval.substring(1));
+ break;
+ case 'u':
+ ((SpreadSheet) app).setCurrentValue(Cell.URL, sval.substring(1));
+ break;
+ case 'f':
+ ((SpreadSheet) app).setCurrentValue(Cell.FORMULA,
+ sval.substring(1));
+ break;
}
}
}
--- a/jdk/src/share/demo/applets/WireFrame/Matrix3D.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/WireFrame/Matrix3D.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,22 +29,23 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
/** A fairly conventional 3D matrix object that can transform sets of
- 3D points and perform a variety of manipulations on the transform */
+3D points and perform a variety of manipulations on the transform */
class Matrix3D {
+
float xx, xy, xz, xo;
float yx, yy, yz, yo;
float zx, zy, zz, zo;
static final double pi = 3.14159265;
+
/** Create a new unit matrix */
- Matrix3D () {
+ Matrix3D() {
xx = 1.0f;
yy = 1.0f;
zz = 1.0f;
}
+
/** Scale by f in all dimensions */
void scale(float f) {
xx *= f;
@@ -60,6 +61,7 @@
zz *= f;
zo *= f;
}
+
/** Scale along each axis independently */
void scale(float xf, float yf, float zf) {
xx *= xf;
@@ -75,12 +77,14 @@
zz *= zf;
zo *= zf;
}
+
/** Translate the origin */
void translate(float x, float y, float z) {
xo += x;
yo += y;
zo += z;
}
+
/** rotate theta degrees about the y axis */
void yrot(double theta) {
theta *= (pi / 180);
@@ -106,6 +110,7 @@
zy = Nzy;
zz = Nzz;
}
+
/** rotate theta degrees about the x axis */
void xrot(double theta) {
theta *= (pi / 180);
@@ -131,6 +136,7 @@
zy = Nzy;
zz = Nzz;
}
+
/** rotate theta degrees about the z axis */
void zrot(double theta) {
theta *= (pi / 180);
@@ -156,6 +162,7 @@
xy = Nxy;
xz = Nxz;
}
+
/** Multiply this matrix by a second: M = M*R */
void mult(Matrix3D rhs) {
float lxx = xx * rhs.xx + yx * rhs.xy + zx * rhs.xz;
@@ -204,10 +211,11 @@
zy = 0;
zz = 1;
}
+
/** Transform nvert points from v into tv. v contains the input
- coordinates in floating point. Three successive entries in
- the array constitute a point. tv ends up holding the transformed
- points as integers; three successive entries per point */
+ coordinates in floating point. Three successive entries in
+ the array constitute a point. tv ends up holding the transformed
+ points as integers; three successive entries per point */
void transform(float v[], int tv[], int nvert) {
float lxx = xx, lxy = xy, lxz = xz, lxo = xo;
float lyx = yx, lyy = yy, lyz = yz, lyo = yo;
@@ -216,11 +224,13 @@
float x = v[i];
float y = v[i + 1];
float z = v[i + 2];
- tv[i ] = (int) (x * lxx + y * lxy + z * lxz + lxo);
+ tv[i] = (int) (x * lxx + y * lxy + z * lxz + lxo);
tv[i + 1] = (int) (x * lyx + y * lyy + z * lyz + lyo);
tv[i + 2] = (int) (x * lzx + y * lzy + z * lzz + lzo);
}
}
+
+ @Override
public String toString() {
return ("[" + xo + "," + xx + "," + xy + "," + xz + ";"
+ yo + "," + yx + "," + yy + "," + yz + ";"
--- a/jdk/src/share/demo/applets/WireFrame/ThreeD.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/WireFrame/ThreeD.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,28 +29,29 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-
-/* A set of classes to parse, represent and display 3D wireframe models
- represented in Wavefront .obj format. */
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
-import java.awt.Event;
import java.awt.event.*;
import java.io.*;
import java.net.URL;
+
+/* A set of classes to parse, represent and display 3D wireframe models
+represented in Wavefront .obj format. */
+@SuppressWarnings("serial")
class FileFormatException extends Exception {
+
public FileFormatException(String s) {
super(s);
}
}
+
/** The representation of a 3D model */
-class Model3D {
+final class Model3D {
+
float vert[];
int tvert[];
int nvert, maxvert;
@@ -58,78 +59,90 @@
int ncon, maxcon;
boolean transformed;
Matrix3D mat;
-
float xmin, xmax, ymin, ymax, zmin, zmax;
- Model3D () {
- mat = new Matrix3D ();
+ Model3D() {
+ mat = new Matrix3D();
mat.xrot(20);
mat.yrot(30);
}
+
/** Create a 3D model by parsing an input stream */
- Model3D (InputStream is) throws IOException, FileFormatException {
- this();
- StreamTokenizer st = new StreamTokenizer(
- new BufferedReader(new InputStreamReader(is, "UTF-8")));
- st.eolIsSignificant(true);
- st.commentChar('#');
- scan:
+ Model3D(InputStream is) throws IOException, FileFormatException {
+ this();
+ StreamTokenizer st = new StreamTokenizer(
+ new BufferedReader(new InputStreamReader(is, "UTF-8")));
+ st.eolIsSignificant(true);
+ st.commentChar('#');
+ scan:
while (true) {
switch (st.nextToken()) {
- default:
- break scan;
- case StreamTokenizer.TT_EOL:
- break;
- case StreamTokenizer.TT_WORD:
- if ("v".equals(st.sval)) {
- double x = 0, y = 0, z = 0;
- if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
- x = st.nval;
+ default:
+ break scan;
+ case StreamTokenizer.TT_EOL:
+ break;
+ case StreamTokenizer.TT_WORD:
+ if ("v".equals(st.sval)) {
+ double x = 0, y = 0, z = 0;
if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
- y = st.nval;
- if (st.nextToken() == StreamTokenizer.TT_NUMBER)
- z = st.nval;
+ x = st.nval;
+ if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
+ y = st.nval;
+ if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
+ z = st.nval;
+ }
+ }
+ }
+ addVert((float) x, (float) y, (float) z);
+ while (st.ttype != StreamTokenizer.TT_EOL && st.ttype
+ != StreamTokenizer.TT_EOF) {
+ st.nextToken();
+ }
+ } else if ("f".equals(st.sval) || "fo".equals(st.sval) || "l".
+ equals(st.sval)) {
+ int start = -1;
+ int prev = -1;
+ int n = -1;
+ while (true) {
+ if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
+ n = (int) st.nval;
+ if (prev >= 0) {
+ add(prev - 1, n - 1);
+ }
+ if (start < 0) {
+ start = n;
+ }
+ prev = n;
+ } else if (st.ttype == '/') {
+ st.nextToken();
+ } else {
+ break;
+ }
+ }
+ if (start >= 0) {
+ add(start - 1, prev - 1);
+ }
+ if (st.ttype != StreamTokenizer.TT_EOL) {
+ break scan;
+ }
+ } else {
+ while (st.nextToken() != StreamTokenizer.TT_EOL
+ && st.ttype != StreamTokenizer.TT_EOF) {
+ // no-op
}
}
- addVert((float) x, (float) y, (float) z);
- while (st.ttype != StreamTokenizer.TT_EOL &&
- st.ttype != StreamTokenizer.TT_EOF)
- st.nextToken();
- } else if ("f".equals(st.sval) || "fo".equals(st.sval) || "l".equals(st.sval)) {
- int start = -1;
- int prev = -1;
- int n = -1;
- while (true)
- if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
- n = (int) st.nval;
- if (prev >= 0)
- add(prev - 1, n - 1);
- if (start < 0)
- start = n;
- prev = n;
- } else if (st.ttype == '/')
- st.nextToken();
- else
- break;
- if (start >= 0)
- add(start - 1, prev - 1);
- if (st.ttype != StreamTokenizer.TT_EOL)
- break scan;
- } else {
- while (st.nextToken() != StreamTokenizer.TT_EOL
- && st.ttype != StreamTokenizer.TT_EOF);
- }
}
}
is.close();
- if (st.ttype != StreamTokenizer.TT_EOF)
+ if (st.ttype != StreamTokenizer.TT_EOF) {
throw new FileFormatException(st.toString());
+ }
}
/** Add a vertex to this model */
int addVert(float x, float y, float z) {
int i = nvert;
- if (i >= maxvert)
+ if (i >= maxvert) {
if (vert == null) {
maxvert = 100;
vert = new float[maxvert * 3];
@@ -139,18 +152,21 @@
System.arraycopy(vert, 0, nv, 0, vert.length);
vert = nv;
}
+ }
i *= 3;
vert[i] = x;
vert[i + 1] = y;
vert[i + 2] = z;
return nvert++;
}
+
/** Add a line from vertex p1 to vertex p2 */
void add(int p1, int p2) {
int i = ncon;
- if (p1 >= nvert || p2 >= nvert)
+ if (p1 >= nvert || p2 >= nvert) {
return;
- if (i >= maxcon)
+ }
+ if (i >= maxcon) {
if (con == null) {
maxcon = 100;
con = new int[maxcon];
@@ -160,6 +176,7 @@
System.arraycopy(con, 0, nv, 0, con.length);
con = nv;
}
+ }
if (p1 > p2) {
int t = p1;
p1 = p2;
@@ -168,79 +185,79 @@
con[i] = (p1 << 16) | p2;
ncon = i + 1;
}
+
/** Transform all the points in this model */
void transform() {
- if (transformed || nvert <= 0)
+ if (transformed || nvert <= 0) {
return;
- if (tvert == null || tvert.length < nvert * 3)
- tvert = new int[nvert*3];
+ }
+ if (tvert == null || tvert.length < nvert * 3) {
+ tvert = new int[nvert * 3];
+ }
mat.transform(vert, tvert, nvert);
transformed = true;
}
- /* Quick Sort implementation
- */
- private void quickSort(int a[], int left, int right)
- {
- int leftIndex = left;
- int rightIndex = right;
- int partionElement;
- if ( right > left)
- {
+ /* Quick Sort implementation
+ */
+ private void quickSort(int a[], int left, int right) {
+ int leftIndex = left;
+ int rightIndex = right;
+ int partionElement;
+ if (right > left) {
- /* Arbitrarily establishing partition element as the midpoint of
- * the array.
- */
- partionElement = a[ ( left + right ) / 2 ];
+ /* Arbitrarily establishing partition element as the midpoint of
+ * the array.
+ */
+ partionElement = a[(left + right) / 2];
- // loop through the array until indices cross
- while( leftIndex <= rightIndex )
- {
- /* find the first element that is greater than or equal to
- * the partionElement starting from the leftIndex.
- */
- while( ( leftIndex < right ) && ( a[leftIndex] < partionElement ) )
- ++leftIndex;
+ // loop through the array until indices cross
+ while (leftIndex <= rightIndex) {
+ /* find the first element that is greater than or equal to
+ * the partionElement starting from the leftIndex.
+ */
+ while ((leftIndex < right) && (a[leftIndex] < partionElement)) {
+ ++leftIndex;
+ }
- /* find an element that is smaller than or equal to
- * the partionElement starting from the rightIndex.
- */
- while( ( rightIndex > left ) &&
- ( a[rightIndex] > partionElement ) )
- --rightIndex;
+ /* find an element that is smaller than or equal to
+ * the partionElement starting from the rightIndex.
+ */
+ while ((rightIndex > left) && (a[rightIndex] > partionElement)) {
+ --rightIndex;
+ }
- // if the indexes have not crossed, swap
- if( leftIndex <= rightIndex )
- {
- swap(a, leftIndex, rightIndex);
- ++leftIndex;
- --rightIndex;
+ // if the indexes have not crossed, swap
+ if (leftIndex <= rightIndex) {
+ swap(a, leftIndex, rightIndex);
+ ++leftIndex;
+ --rightIndex;
+ }
}
- }
- /* If the right index has not reached the left side of array
- * must now sort the left partition.
- */
- if( left < rightIndex )
- quickSort( a, left, rightIndex );
+ /* If the right index has not reached the left side of array
+ * must now sort the left partition.
+ */
+ if (left < rightIndex) {
+ quickSort(a, left, rightIndex);
+ }
- /* If the left index has not reached the right side of array
- * must now sort the right partition.
- */
- if( leftIndex < right )
- quickSort( a, leftIndex, right );
-
- }
- }
+ /* If the left index has not reached the right side of array
+ * must now sort the right partition.
+ */
+ if (leftIndex < right) {
+ quickSort(a, leftIndex, right);
+ }
- private void swap(int a[], int i, int j)
- {
- int T;
- T = a[i];
- a[i] = a[j];
- a[j] = T;
- }
+ }
+ }
+ private void swap(int a[], int i, int j) {
+ int T;
+ T = a[i];
+ a[i] = a[j];
+ a[j] = T;
+ }
/** eliminate duplicate lines */
void compress() {
@@ -259,21 +276,21 @@
}
ncon = d;
}
-
static Color gr[];
/** Paint this model to a graphics context. It uses the matrix associated
- with this model to map from model space to screen space.
- The next version of the browser should have double buffering,
- which will make this *much* nicer */
+ with this model to map from model space to screen space.
+ The next version of the browser should have double buffering,
+ which will make this *much* nicer */
void paint(Graphics g) {
- if (vert == null || nvert <= 0)
+ if (vert == null || nvert <= 0) {
return;
+ }
transform();
if (gr == null) {
gr = new Color[16];
for (int i = 0; i < 16; i++) {
- int grey = (int) (170*(1-Math.pow(i/15.0, 2.3)));
+ int grey = (int) (170 * (1 - Math.pow(i / 15.0, 2.3)));
gr[i] = new Color(grey, grey, grey);
}
}
@@ -281,151 +298,181 @@
int lim = ncon;
int c[] = con;
int v[] = tvert;
- if (lim <= 0 || nvert <= 0)
+ if (lim <= 0 || nvert <= 0) {
return;
+ }
for (int i = 0; i < lim; i++) {
int T = c[i];
int p1 = ((T >> 16) & 0xFFFF) * 3;
int p2 = (T & 0xFFFF) * 3;
int grey = v[p1 + 2] + v[p2 + 2];
- if (grey < 0)
+ if (grey < 0) {
grey = 0;
- if (grey > 15)
+ }
+ if (grey > 15) {
grey = 15;
+ }
if (grey != lg) {
lg = grey;
g.setColor(gr[grey]);
}
g.drawLine(v[p1], v[p1 + 1],
- v[p2], v[p2 + 1]);
+ v[p2], v[p2 + 1]);
}
}
/** Find the bounding box of this model */
void findBB() {
- if (nvert <= 0)
+ if (nvert <= 0) {
return;
+ }
float v[] = vert;
- float xmin = v[0], xmax = xmin;
- float ymin = v[1], ymax = ymin;
- float zmin = v[2], zmax = zmin;
+ float _xmin = v[0], _xmax = _xmin;
+ float _ymin = v[1], _ymax = _ymin;
+ float _zmin = v[2], _zmax = _zmin;
for (int i = nvert * 3; (i -= 3) > 0;) {
float x = v[i];
- if (x < xmin)
- xmin = x;
- if (x > xmax)
- xmax = x;
+ if (x < _xmin) {
+ _xmin = x;
+ }
+ if (x > _xmax) {
+ _xmax = x;
+ }
float y = v[i + 1];
- if (y < ymin)
- ymin = y;
- if (y > ymax)
- ymax = y;
+ if (y < _ymin) {
+ _ymin = y;
+ }
+ if (y > _ymax) {
+ _ymax = y;
+ }
float z = v[i + 2];
- if (z < zmin)
- zmin = z;
- if (z > zmax)
- zmax = z;
+ if (z < _zmin) {
+ _zmin = z;
+ }
+ if (z > _zmax) {
+ _zmax = z;
+ }
}
- this.xmax = xmax;
- this.xmin = xmin;
- this.ymax = ymax;
- this.ymin = ymin;
- this.zmax = zmax;
- this.zmin = zmin;
+ this.xmax = _xmax;
+ this.xmin = _xmin;
+ this.ymax = _ymax;
+ this.ymin = _ymin;
+ this.zmax = _zmax;
+ this.zmin = _zmin;
}
}
+
/** An applet to put a 3D model into a page */
+@SuppressWarnings("serial")
public class ThreeD extends Applet
- implements Runnable, MouseListener, MouseMotionListener {
+ implements Runnable, MouseListener, MouseMotionListener {
+
Model3D md;
boolean painted = true;
float xfac;
int prevx, prevy;
- float xtheta, ytheta;
float scalefudge = 1;
Matrix3D amat = new Matrix3D(), tmat = new Matrix3D();
String mdname = null;
String message = null;
+ @Override
public void init() {
mdname = getParameter("model");
try {
scalefudge = Float.valueOf(getParameter("scale")).floatValue();
- }catch(Exception e){};
+ } catch (Exception ignored) {
+ // fall back to default scalefudge = 1
+ }
amat.yrot(20);
amat.xrot(20);
- if (mdname == null)
+ if (mdname == null) {
mdname = "model.obj";
+ }
resize(getSize().width <= 20 ? 400 : getSize().width,
- getSize().height <= 20 ? 400 : getSize().height);
+ getSize().height <= 20 ? 400 : getSize().height);
addMouseListener(this);
addMouseMotionListener(this);
}
+ @Override
public void destroy() {
removeMouseListener(this);
removeMouseMotionListener(this);
}
+ @Override
public void run() {
InputStream is = null;
try {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
is = new URL(getDocumentBase(), mdname).openStream();
- Model3D m = new Model3D (is);
+ Model3D m = new Model3D(is);
md = m;
m.findBB();
m.compress();
float xw = m.xmax - m.xmin;
float yw = m.ymax - m.ymin;
float zw = m.zmax - m.zmin;
- if (yw > xw)
+ if (yw > xw) {
xw = yw;
- if (zw > xw)
+ }
+ if (zw > xw) {
xw = zw;
+ }
float f1 = getSize().width / xw;
float f2 = getSize().height / xw;
xfac = 0.7f * (f1 < f2 ? f1 : f2) * scalefudge;
- } catch(Exception e) {
+ } catch (Exception e) {
md = null;
message = e.toString();
}
try {
- if (is != null)
+ if (is != null) {
is.close();
- } catch(Exception e) {
+ }
+ } catch (Exception e) {
}
repaint();
}
+ @Override
public void start() {
- if (md == null && message == null)
+ if (md == null && message == null) {
new Thread(this).start();
+ }
}
+ @Override
public void stop() {
}
- public void mouseClicked(MouseEvent e) {
+ @Override
+ public void mouseClicked(MouseEvent e) {
}
- public void mousePressed(MouseEvent e) {
+ @Override
+ public void mousePressed(MouseEvent e) {
prevx = e.getX();
prevy = e.getY();
e.consume();
}
- public void mouseReleased(MouseEvent e) {
+ @Override
+ public void mouseReleased(MouseEvent e) {
}
- public void mouseEntered(MouseEvent e) {
+ @Override
+ public void mouseEntered(MouseEvent e) {
}
- public void mouseExited(MouseEvent e) {
+ @Override
+ public void mouseExited(MouseEvent e) {
}
- public void mouseDragged(MouseEvent e) {
+ @Override
+ public void mouseDragged(MouseEvent e) {
int x = e.getX();
int y = e.getY();
@@ -444,15 +491,17 @@
e.consume();
}
- public void mouseMoved(MouseEvent e) {
+ @Override
+ public void mouseMoved(MouseEvent e) {
}
+ @Override
public void paint(Graphics g) {
if (md != null) {
md.mat.unit();
md.mat.translate(-(md.xmin + md.xmax) / 2,
- -(md.ymin + md.ymax) / 2,
- -(md.zmin + md.zmax) / 2);
+ -(md.ymin + md.ymax) / 2,
+ -(md.zmin + md.zmax) / 2);
md.mat.mult(amat);
md.mat.scale(xfac, -xfac, 16 * xfac / getSize().width);
md.mat.translate(getSize().width / 2, getSize().height / 2, 8);
@@ -469,20 +518,18 @@
painted = true;
notifyAll();
}
-// private synchronized void waitPainted() {
-// while (!painted)
-// wait();
-// painted = false;
-// }
+ @Override
public String getAppletInfo() {
- return "Title: ThreeD \nAuthor: James Gosling? \nAn applet to put a 3D model into a page.";
+ return "Title: ThreeD \nAuthor: James Gosling? \n"
+ + "An applet to put a 3D model into a page.";
}
+ @Override
public String[][] getParameterInfo() {
String[][] info = {
- {"model", "path string", "The path to the model to be displayed."},
- {"scale", "float", "The scale of the model. Default is 1."}
+ { "model", "path string", "The path to the model to be displayed." },
+ { "scale", "float", "The scale of the model. Default is 1." }
};
return info;
}
--- a/jdk/src/share/demo/applets/WireFrame/example1.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/WireFrame/example1.html Sun Apr 10 10:23:28 2011 -0700
@@ -6,7 +6,7 @@
<h1>3D Model: Cube</h1>
<hr>
<applet code=ThreeD.class width=100 height=100>
- <param name=model value=models/cube.obj>
+ <param name=model value="models/cube.obj">
alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason."
Your browser is completely ignoring the <APPLET> tag!
</applet>
--- a/jdk/src/share/demo/applets/WireFrame/example2.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/WireFrame/example2.html Sun Apr 10 10:23:28 2011 -0700
@@ -6,7 +6,7 @@
<h1>3D Model: Dinosaur</h1>
<hr>
<applet code=ThreeD.class width=300 height=300>
- <param name=model value=models/dinasaur.obj>
+ <param name=model value="models/dinasaur.obj">
alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason."
Your browser is completely ignoring the <APPLET> tag!
</applet>
--- a/jdk/src/share/demo/applets/WireFrame/example3.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/WireFrame/example3.html Sun Apr 10 10:23:28 2011 -0700
@@ -6,7 +6,7 @@
<h1>3D Model: Hughes</h1>
<hr>
<applet code=ThreeD.class width=300 height=300>
- <param name=model value=models/hughes_500.obj>
+ <param name=model value="models/hughes_500.obj">
alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason."
Your browser is completely ignoring the <APPLET> tag!
</applet>
--- a/jdk/src/share/demo/applets/WireFrame/example4.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/applets/WireFrame/example4.html Sun Apr 10 10:23:28 2011 -0700
@@ -6,7 +6,7 @@
<h1>3D Model: knoxS</h1>
<hr>
<applet code=ThreeD.class width=300 height=300>
- <param name=model value=models/knoxS.obj>
+ <param name=model value="models/knoxS.obj">
alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason."
Your browser is completely ignoring the <APPLET> tag!
</applet>
--- a/jdk/src/share/demo/jfc/CodePointIM/CodePointIM.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/CodePointIM/CodePointIM.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,12 +29,12 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
+
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
+
public class CodePointIM {
// Actually, the main method is not required for InputMethod.
@@ -42,11 +42,11 @@
// not correct and encourage their reading README.txt.
public static void main(String[] args) {
try {
- ResourceBundle resource = ResourceBundle.getBundle("resources.codepoint",
- Locale.getDefault());
+ ResourceBundle resource = ResourceBundle.getBundle(
+ "resources.codepoint",
+ Locale.getDefault());
System.err.println(resource.getString("warning"));
- }
- catch (MissingResourceException e) {
+ } catch (MissingResourceException e) {
System.err.println(e.toString());
}
--- a/jdk/src/share/demo/jfc/CodePointIM/CodePointInputMethod.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/CodePointIM/CodePointInputMethod.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -28,13 +28,8 @@
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-
-/*
- */
+package com.sun.inputmethods.internal.codepointim;
-package com.sun.inputmethods.internal.codepointim;
-import java.text.AttributedCharacterIterator;
-import java.util.Map;
import java.awt.AWTEvent;
import java.awt.Toolkit;
@@ -50,6 +45,7 @@
import java.text.AttributedString;
import java.util.Locale;
+
/**
* The Code Point Input Method is a simple input method that allows Unicode
* characters to be entered using their code point or code unit values. See the
@@ -59,18 +55,16 @@
*/
public class CodePointInputMethod implements InputMethod {
- private static final int UNSET = 0;
- private static final int ESCAPE = 1; // \u0000 - \uFFFF
- private static final int SPECIAL_ESCAPE = 2; // \U000000 - \U10FFFF
- private static final int SURROGATE_PAIR = 3; // \uD800\uDC00 - \uDBFF\uDFFF
-
+ private static final int UNSET = 0;
+ private static final int ESCAPE = 1; // \u0000 - \uFFFF
+ private static final int SPECIAL_ESCAPE = 2; // \U000000 - \U10FFFF
+ private static final int SURROGATE_PAIR = 3; // \uD800\uDC00 - \uDBFF\uDFFF
private InputMethodContext context;
private Locale locale;
private StringBuffer buffer;
private int insertionPoint;
private int format = UNSET;
-
public CodePointInputMethod() throws IOException {
}
@@ -90,7 +84,7 @@
if (eventID == KeyEvent.KEY_PRESSED) {
// If we are not in composition mode, pass through
- if (notInCompositionMode) {
+ if (notInCompositionMode) {
return;
}
@@ -106,7 +100,7 @@
char c = e.getKeyChar();
// If we are not in composition mode, wait a back slash
- if (notInCompositionMode) {
+ if (notInCompositionMode) {
// If the type character is not a back slash, pass through
if (c != '\\') {
return;
@@ -115,30 +109,30 @@
startComposition(); // Enter to composition mode
} else {
switch (c) {
- case ' ': // Exit from composition mode
- finishComposition();
- break;
- case '\u007f': // Delete
- deleteCharacter();
- break;
- case '\b': // BackSpace
- deletePreviousCharacter();
- break;
- case '\u001b': // Escape
- cancelComposition();
- break;
- case '\n': // Return
- case '\t': // Tab
- sendCommittedText();
- break;
- default:
- composeUnicodeEscape(c);
- break;
+ case ' ': // Exit from composition mode
+ finishComposition();
+ break;
+ case '\u007f': // Delete
+ deleteCharacter();
+ break;
+ case '\b': // BackSpace
+ deletePreviousCharacter();
+ break;
+ case '\u001b': // Escape
+ cancelComposition();
+ break;
+ case '\n': // Return
+ case '\t': // Tab
+ sendCommittedText();
+ break;
+ default:
+ composeUnicodeEscape(c);
+ break;
}
}
} else { // KeyEvent.KEY_RELEASED
// If we are not in composition mode, pass through
- if (notInCompositionMode) {
+ if (notInCompositionMode) {
return;
}
}
@@ -148,7 +142,7 @@
private void composeUnicodeEscape(char c) {
switch (buffer.length()) {
- case 1: // \\
+ case 1: // \\
waitEscapeCharacter(c);
break;
case 2: // \\u or \\U
@@ -221,7 +215,7 @@
private void waitDigit2(char c) {
if (Character.digit(c, 16) != -1) {
buffer.insert(insertionPoint++, c);
- char codePoint = (char)getCodePoint(buffer, 2, 5);
+ char codePoint = (char) getCodePoint(buffer, 2, 5);
if (Character.isHighSurrogate(codePoint)) {
format = SURROGATE_PAIR;
buffer.append("\\u");
@@ -261,11 +255,11 @@
private void sendComposedText() {
AttributedString as = new AttributedString(buffer.toString());
as.addAttribute(TextAttribute.INPUT_METHOD_HIGHLIGHT,
- InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT);
+ InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT);
context.dispatchInputMethodEvent(
- InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
- as.getIterator(), 0,
- TextHitInfo.leading(insertionPoint), null);
+ InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
+ as.getIterator(), 0,
+ TextHitInfo.leading(insertionPoint), null);
}
/**
@@ -274,9 +268,9 @@
private void sendCommittedText() {
AttributedString as = new AttributedString(buffer.toString());
context.dispatchInputMethodEvent(
- InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
- as.getIterator(), buffer.length(),
- TextHitInfo.leading(insertionPoint), null);
+ InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
+ as.getIterator(), buffer.length(),
+ TextHitInfo.leading(insertionPoint), null);
buffer.setLength(0);
insertionPoint = 0;
@@ -298,9 +292,9 @@
}
context.dispatchInputMethodEvent(
- InputMethodEvent.CARET_POSITION_CHANGED,
- null, 0,
- TextHitInfo.leading(insertionPoint), null);
+ InputMethodEvent.CARET_POSITION_CHANGED,
+ null, 0,
+ TextHitInfo.leading(insertionPoint), null);
}
/**
@@ -314,9 +308,9 @@
}
context.dispatchInputMethodEvent(
- InputMethodEvent.CARET_POSITION_CHANGED,
- null, 0,
- TextHitInfo.leading(insertionPoint), null);
+ InputMethodEvent.CARET_POSITION_CHANGED,
+ null, 0,
+ TextHitInfo.leading(insertionPoint), null);
}
/**
@@ -383,7 +377,7 @@
private void finishComposition() {
int len = buffer.length();
if (len == 6 && format != SPECIAL_ESCAPE) {
- char codePoint = (char)getCodePoint(buffer, 2, 5);
+ char codePoint = (char) getCodePoint(buffer, 2, 5);
if (Character.isValidCodePoint(codePoint) && codePoint != 0xFFFF) {
buffer.setLength(0);
buffer.append(codePoint);
@@ -400,11 +394,11 @@
}
} else if (len == 12 && format == SURROGATE_PAIR) {
char[] codePoint = {
- (char)getCodePoint(buffer, 2, 5),
- (char)getCodePoint(buffer, 8, 11)
+ (char) getCodePoint(buffer, 2, 5),
+ (char) getCodePoint(buffer, 8, 11)
};
- if (Character.isHighSurrogate(codePoint[0]) &&
- Character.isLowSurrogate(codePoint[1])) {
+ if (Character.isHighSurrogate(codePoint[0]) && Character.
+ isLowSurrogate(codePoint[1])) {
buffer.setLength(0);
buffer.append(codePoint);
sendCommittedText();
@@ -418,7 +412,7 @@
private int getCodePoint(StringBuffer sb, int from, int to) {
int value = 0;
for (int i = from; i <= to; i++) {
- value = (value<<4) + Character.digit(sb.charAt(i), 16);
+ value = (value << 4) + Character.digit(sb.charAt(i), 16);
}
return value;
}
@@ -427,7 +421,6 @@
Toolkit.getDefaultToolkit().beep();
}
-
public void activate() {
if (buffer == null) {
buffer = new StringBuffer(12);
--- a/jdk/src/share/demo/jfc/CodePointIM/CodePointInputMethodDescriptor.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/CodePointIM/CodePointInputMethodDescriptor.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -28,17 +28,15 @@
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
+package com.sun.inputmethods.internal.codepointim;
-/*
- */
-
-package com.sun.inputmethods.internal.codepointim;
import java.awt.Image;
import java.awt.im.spi.InputMethodDescriptor;
import java.awt.im.spi.InputMethod;
import java.util.Locale;
+
/**
* The CodePointInputMethod is a simple input method that allows Unicode
* characters to be entered via their hexadecimal code point values.
@@ -68,12 +66,12 @@
*/
public Locale[] getAvailableLocales() {
Locale[] locales = {
- new Locale("","",""),
- };
+ new Locale("", "", ""), };
return locales;
}
- public synchronized String getInputMethodDisplayName(Locale inputLocale, Locale displayLanguage) {
+ public synchronized String getInputMethodDisplayName(Locale inputLocale,
+ Locale displayLanguage) {
return "CodePoint Input Method";
}
--- a/jdk/src/share/demo/jfc/FileChooserDemo/ExampleFileSystemView.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/FileChooserDemo/ExampleFileSystemView.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,13 +29,12 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
import java.io.File;
import java.io.IOException;
import javax.swing.filechooser.FileSystemView;
+
/**
* This is a simple example that uses the FileSystemView class.
* You can provide a superclass of the FileSystemView class with your own functionality.
@@ -43,6 +42,7 @@
* @author Pavel Porvatov
*/
public class ExampleFileSystemView extends FileSystemView {
+
/**
* Creates a new folder with the default name "New folder". This method is invoked
* when the user presses the "New folder" button.
@@ -65,8 +65,9 @@
* Returns a list which appears in a drop-down list of the FileChooser component.
* In this implementation only the home directory is returned.
*/
+ @Override
public File[] getRoots() {
- return new File[]{getHomeDirectory()};
+ return new File[] { getHomeDirectory() };
}
/**
@@ -74,9 +75,11 @@
* A string with all upper case letters is returned for a directory.
* A string with all lower case letters is returned for a file.
*/
+ @Override
public String getSystemDisplayName(File f) {
String displayName = super.getSystemDisplayName(f);
- return f.isDirectory() ? displayName.toUpperCase() : displayName.toLowerCase();
+ return f.isDirectory() ? displayName.toUpperCase() : displayName.
+ toLowerCase();
}
}
--- a/jdk/src/share/demo/jfc/FileChooserDemo/ExampleFileView.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/FileChooserDemo/ExampleFileView.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,14 +29,13 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
import javax.swing.*;
import javax.swing.filechooser.*;
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
-import java.io.File;
-import java.util.Hashtable;
/**
* A convenience implementation of the FileView interface that
@@ -61,15 +60,19 @@
* @author Jeff Dinkins
*/
public class ExampleFileView extends FileView {
- private final Hashtable<String, Icon> icons = new Hashtable<String, Icon>();
- private final Hashtable<File, String> fileDescriptions = new Hashtable<File, String>();
- private final Hashtable<String, String> typeDescriptions = new Hashtable<String, String>();
+
+ private final Map<String, Icon> icons = new HashMap<String, Icon>();
+ private final Map<File, String> fileDescriptions =
+ new HashMap<File, String>();
+ private final Map<String, String> typeDescriptions =
+ new HashMap<String, String>();
/**
* The name of the file. Do nothing special here. Let
* the system file view handle this.
* @see FileView#getName
*/
+ @Override
public String getName(File f) {
return null;
}
@@ -86,6 +89,7 @@
*
* @see FileView#getDescription
*/
+ @Override
public String getDescription(File f) {
return fileDescriptions.get(f);
}
@@ -112,6 +116,7 @@
*
* @see FileView#getTypeDescription
*/
+ @Override
public String getTypeDescription(File f) {
return typeDescriptions.get(getExtension(f));
}
@@ -122,12 +127,12 @@
*/
private String getExtension(File f) {
String name = f.getName();
- if(name != null) {
+ if (name != null) {
int extensionIndex = name.lastIndexOf('.');
- if(extensionIndex < 0) {
+ if (extensionIndex < 0) {
return null;
}
- return name.substring(extensionIndex+1).toLowerCase();
+ return name.substring(extensionIndex + 1).toLowerCase();
}
return null;
}
@@ -147,10 +152,11 @@
*
* @see FileView#getIcon
*/
+ @Override
public Icon getIcon(File f) {
Icon icon = null;
String extension = getExtension(f);
- if(extension != null) {
+ if (extension != null) {
icon = icons.get(extension);
}
return icon;
@@ -168,11 +174,11 @@
*
* @see FileView#isTraversable
*/
+ @Override
public Boolean isTraversable(File f) {
// if (some_reason) {
// return Boolean.FALSE;
// }
return null; // Use default from FileSystemView
}
-
}
--- a/jdk/src/share/demo/jfc/FileChooserDemo/FileChooserDemo.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/FileChooserDemo/FileChooserDemo.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,21 +29,56 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import javax.swing.*;
-import javax.swing.filechooser.*;
+import java.lang.reflect.InvocationTargetException;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import javax.swing.UIManager.LookAndFeelInfo;
+import java.awt.BorderLayout;
+import java.awt.CardLayout;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.Graphics;
+import java.awt.Image;
+import java.awt.Insets;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.util.List;
+import javax.swing.BorderFactory;
+import javax.swing.Box;
+import javax.swing.BoxLayout;
+import javax.swing.ButtonGroup;
+import javax.swing.DefaultComboBoxModel;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JComboBox;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JRadioButton;
+import javax.swing.JTextField;
+import javax.swing.JToggleButton;
+import javax.swing.LookAndFeel;
+import javax.swing.SwingUtilities;
+import javax.swing.UIManager;
+import javax.swing.UnsupportedLookAndFeelException;
+import javax.swing.WindowConstants;
+import javax.swing.filechooser.FileFilter;
+import javax.swing.filechooser.FileNameExtensionFilter;
+import javax.swing.filechooser.FileSystemView;
+import java.util.ArrayList;
import javax.swing.plaf.FileChooserUI;
import javax.swing.plaf.basic.BasicFileChooserUI;
+import java.io.File;
+import static javax.swing.JFileChooser.*;
-import java.awt.*;
-import java.io.File;
-import java.awt.event.*;
-import java.beans.*;
-import java.util.Vector;
-
-import static javax.swing.JFileChooser.*;
/**
*
@@ -51,12 +86,18 @@
*
* @author Jeff Dinkins
*/
+@SuppressWarnings("serial")
public class FileChooserDemo extends JPanel implements ActionListener {
+
+ public static final String NIMBUS_LAF_NAME = "Nimbus";
private static JFrame frame;
+ private final List<SupportedLaF> supportedLaFs =
+ new ArrayList<SupportedLaF>();
+ private static SupportedLaF nimbusLaF;
- private final Vector<SupportedLaF> supportedLaFs = new Vector();
private static class SupportedLaF {
+
private final String name;
private final LookAndFeel laf;
@@ -65,18 +106,15 @@
this.laf = laf;
}
+ @Override
public String toString() {
return name;
}
}
-
-
private JButton showButton;
-
private JCheckBox showAllFilesFilterCheckBox;
private JCheckBox showImageFilesFilterCheckBox;
private JCheckBox showFullDescriptionCheckBox;
-
private JCheckBox useFileViewCheckBox;
private JCheckBox useFileSystemViewCheckBox;
private JCheckBox accessoryCheckBox;
@@ -84,46 +122,44 @@
private JCheckBox useEmbedInWizardCheckBox;
private JCheckBox useControlsCheckBox;
private JCheckBox enableDragCheckBox;
-
private JRadioButton singleSelectionRadioButton;
private JRadioButton multiSelectionRadioButton;
-
private JRadioButton openRadioButton;
private JRadioButton saveRadioButton;
private JRadioButton customButton;
-
private JComboBox lafComboBox;
-
private JRadioButton justFilesRadioButton;
private JRadioButton justDirectoriesRadioButton;
private JRadioButton bothFilesAndDirectoriesRadioButton;
-
private JTextField customField;
-
private final ExampleFileView fileView;
-
private final ExampleFileSystemView fileSystemView;
-
- private final static Dimension hpad10 = new Dimension(10,1);
- private final static Dimension vpad20 = new Dimension(1,20);
+ private final static Dimension hpad10 = new Dimension(10, 1);
+ private final static Dimension vpad20 = new Dimension(1, 20);
private final static Dimension vpad7 = new Dimension(1, 7);
private final static Dimension vpad4 = new Dimension(1, 4);
private final static Insets insets = new Insets(5, 10, 0, 10);
-
private final FilePreviewer previewer;
private final JFileChooser chooser;
+ @SuppressWarnings("LeakingThisInConstructor")
public FileChooserDemo() {
- UIManager.LookAndFeelInfo[] installedLafs = UIManager.getInstalledLookAndFeels();
+ UIManager.LookAndFeelInfo[] installedLafs = UIManager.
+ getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo lafInfo : installedLafs) {
try {
- Class lnfClass = Class.forName(lafInfo.getClassName());
- LookAndFeel laf = (LookAndFeel)(lnfClass.newInstance());
+ Class<?> lnfClass = Class.forName(lafInfo.getClassName());
+ LookAndFeel laf = (LookAndFeel) (lnfClass.newInstance());
if (laf.isSupportedLookAndFeel()) {
String name = lafInfo.getName();
- supportedLaFs.add(new SupportedLaF(name, laf));
+ SupportedLaF supportedLaF = new SupportedLaF(name, laf);
+ supportedLaFs.add(supportedLaF);
+ if (NIMBUS_LAF_NAME.equals(name)) {
+ nimbusLaF = supportedLaF;
+ }
}
- } catch (Exception e) { // If ANYTHING weird happens, don't add it
+ } catch (Exception ignored) {
+ // If ANYTHING weird happens, don't add this L&F
}
}
@@ -134,8 +170,10 @@
// Create Custom FileView
fileView = new ExampleFileView();
- fileView.putIcon("jpg", new ImageIcon(getClass().getResource("/resources/images/jpgIcon.jpg")));
- fileView.putIcon("gif", new ImageIcon(getClass().getResource("/resources/images/gifIcon.gif")));
+ fileView.putIcon("jpg", new ImageIcon(getClass().getResource(
+ "/resources/images/jpgIcon.jpg")));
+ fileView.putIcon("gif", new ImageIcon(getClass().getResource(
+ "/resources/images/gifIcon.gif")));
// Create Custom FileSystemView
fileSystemView = new ExampleFileSystemView();
@@ -155,8 +193,11 @@
customButton.addActionListener(optionListener);
customField = new JTextField(8) {
+
+ @Override
public Dimension getMaximumSize() {
- return new Dimension(getPreferredSize().width, getPreferredSize().height);
+ return new Dimension(getPreferredSize().width,
+ getPreferredSize().height);
}
};
customField.setText("Doit");
@@ -220,7 +261,8 @@
group3.add(justDirectoriesRadioButton);
justDirectoriesRadioButton.addActionListener(optionListener);
- bothFilesAndDirectoriesRadioButton = new JRadioButton("Select Files or Directories");
+ bothFilesAndDirectoriesRadioButton = new JRadioButton(
+ "Select Files or Directories");
group3.add(bothFilesAndDirectoriesRadioButton);
bothFilesAndDirectoriesRadioButton.addActionListener(optionListener);
@@ -241,7 +283,8 @@
showButton.setMnemonic('s');
// Create laf combo box
- lafComboBox = new JComboBox(supportedLaFs);
+ lafComboBox = new JComboBox(supportedLaFs.toArray());
+ lafComboBox.setSelectedItem(nimbusLaF);
lafComboBox.setEditable(false);
lafComboBox.addActionListener(optionListener);
@@ -317,7 +360,8 @@
// ************* File & Directory Options *****************
// ********************************************************
JPanel control4 = new InsetPanel(insets);
- control4.setBorder(BorderFactory.createTitledBorder("File and Directory Options"));
+ control4.setBorder(BorderFactory.createTitledBorder(
+ "File and Directory Options"));
control4.setLayout(new BoxLayout(control4, BoxLayout.Y_AXIS));
control4.add(Box.createRigidArea(vpad20));
control4.add(justFilesRadioButton);
@@ -379,7 +423,7 @@
// clear the preview from the previous display of the chooser
JComponent accessory = chooser.getAccessory();
if (accessory != null) {
- ((FilePreviewer)accessory).loadImage(null);
+ ((FilePreviewer) accessory).loadImage(null);
}
if (useEmbedInWizardCheckBox.isSelected()) {
@@ -393,25 +437,28 @@
if (retval == APPROVE_OPTION) {
JOptionPane.showMessageDialog(frame, getResultString());
} else if (retval == CANCEL_OPTION) {
- JOptionPane.showMessageDialog(frame, "User cancelled operation. No file was chosen.");
+ JOptionPane.showMessageDialog(frame,
+ "User cancelled operation. No file was chosen.");
} else if (retval == ERROR_OPTION) {
- JOptionPane.showMessageDialog(frame, "An error occured. No file was chosen.");
+ JOptionPane.showMessageDialog(frame,
+ "An error occured. No file was chosen.");
} else {
JOptionPane.showMessageDialog(frame, "Unknown operation occured.");
}
}
private void resetFileFilters(boolean enableFilters,
- boolean showExtensionInDescription) {
+ boolean showExtensionInDescription) {
chooser.resetChoosableFileFilters();
if (enableFilters) {
- FileFilter jpgFilter = createFileFilter("JPEG Compressed Image Files",
- showExtensionInDescription, "jpg");
+ FileFilter jpgFilter = createFileFilter(
+ "JPEG Compressed Image Files",
+ showExtensionInDescription, "jpg");
FileFilter gifFilter = createFileFilter("GIF Image Files",
- showExtensionInDescription, "gif");
+ showExtensionInDescription, "gif");
FileFilter bothFilter = createFileFilter("JPEG and GIF Image Files",
- showExtensionInDescription, "jpg",
- "gif");
+ showExtensionInDescription, "jpg",
+ "gif");
chooser.addChoosableFileFilter(bothFilter);
chooser.addChoosableFileFilter(jpgFilter);
chooser.addChoosableFileFilter(gifFilter);
@@ -419,7 +466,7 @@
}
private FileFilter createFileFilter(String description,
- boolean showExtensionInDescription, String...extensions) {
+ boolean showExtensionInDescription, String... extensions) {
if (showExtensionInDescription) {
description = createFileNameFilterDescriptionFromExtensions(
description, extensions);
@@ -429,8 +476,8 @@
private String createFileNameFilterDescriptionFromExtensions(
String description, String[] extensions) {
- String fullDescription = (description == null) ?
- "(" : description + " (";
+ String fullDescription = (description == null) ? "(" : description
+ + " (";
// build the description from the extension list
fullDescription += "." + extensions[0];
for (int i = 1; i < extensions.length; i++) {
@@ -441,12 +488,15 @@
return fullDescription;
}
+
private class WizardDialog extends JDialog implements ActionListener {
+
CardLayout cardLayout;
JPanel cardPanel;
JLabel messageLabel;
JButton backButton, nextButton, closeButton;
+ @SuppressWarnings("LeakingThisInConstructor")
WizardDialog(JFrame frame, boolean modal) {
super(frame, "Embedded JFileChooser Demo", modal);
@@ -494,15 +544,16 @@
// Workaround for bug 4528663. This is necessary to
// pick up the contents of the file chooser text field.
// This will trigger an APPROVE_SELECTION action.
- ((BasicFileChooserUI)ui).getApproveSelectionAction().actionPerformed(null);
+ ((BasicFileChooserUI) ui).getApproveSelectionAction().
+ actionPerformed(null);
} else {
next();
}
} else if (src == closeButton) {
close();
- } else if (cmd == APPROVE_SELECTION) {
+ } else if (APPROVE_SELECTION.equals(cmd)) {
next();
- } else if (cmd == CANCEL_SELECTION) {
+ } else if (CANCEL_SELECTION.equals(cmd)) {
close();
}
}
@@ -528,6 +579,7 @@
setVisible(false);
}
+ @Override
public void dispose() {
chooser.removeActionListener(this);
@@ -542,13 +594,18 @@
private String getResultString() {
String resultString;
- String filter = chooser.getFileFilter().getDescription();
+ String filter;
+ if (chooser.getFileFilter() == null) {
+ filter = "";
+ } else {
+ filter = chooser.getFileFilter().getDescription();
+ }
String path = null;
boolean isDirMode = (chooser.getFileSelectionMode() == DIRECTORIES_ONLY);
boolean isMulti = chooser.isMultiSelectionEnabled();
if (isMulti) {
- File [] files = chooser.getSelectedFiles();
+ File[] files = chooser.getSelectedFiles();
if (files != null && files.length > 0) {
path = "";
for (File file : files) {
@@ -565,11 +622,10 @@
path = path.replace(" ", " ");
filter = filter.replace(" ", " ");
resultString =
- "<html>You chose " + (isMulti ? "these" : "this") + " " +
- (isDirMode ? (isMulti ? "directories" : "directory")
- : (isMulti ? "files" : "file")) +
- ": <code>" + path +
- "</code><br><br>with filter: <br><code>" + filter;
+ "<html>You chose " + (isMulti ? "these" : "this") + " " + (isDirMode ? (isMulti
+ ? "directories" : "directory")
+ : (isMulti ? "files" : "file")) + ": <code>" + path
+ + "</code><br><br>with filter: <br><code>" + filter;
} else {
resultString = "Nothing was chosen";
}
@@ -577,15 +633,14 @@
}
-
-
/** An ActionListener that listens to the radio buttons. */
private class OptionListener implements ActionListener {
+
public void actionPerformed(ActionEvent e) {
JComponent c = (JComponent) e.getSource();
boolean selected = false;
if (c instanceof JToggleButton) {
- selected = ((JToggleButton)c).isSelected();
+ selected = ((JToggleButton) c).isSelected();
}
if (c == openRadioButton) {
@@ -612,7 +667,7 @@
chooser.setAcceptAllFileFilterUsed(selected);
} else if (c == showImageFilesFilterCheckBox) {
resetFileFilters(selected,
- showFullDescriptionCheckBox.isSelected());
+ showFullDescriptionCheckBox.isSelected());
showFullDescriptionCheckBox.setEnabled(selected);
} else if (c == setHiddenCheckBox) {
chooser.setFileHidingEnabled(!selected);
@@ -637,7 +692,7 @@
}
} else if (c == showFullDescriptionCheckBox) {
resetFileFilters(showImageFilesFilterCheckBox.isSelected(),
- selected);
+ selected);
} else if (c == justFilesRadioButton) {
chooser.setFileSelectionMode(FILES_ONLY);
} else if (c == justDirectoriesRadioButton) {
@@ -653,27 +708,33 @@
chooser.setMultiSelectionEnabled(true);
}
} else if (c == lafComboBox) {
- SupportedLaF supportedLaF = ((SupportedLaF)lafComboBox.getSelectedItem());
+ SupportedLaF supportedLaF = ((SupportedLaF) lafComboBox.
+ getSelectedItem());
LookAndFeel laf = supportedLaF.laf;
try {
UIManager.setLookAndFeel(laf);
SwingUtilities.updateComponentTreeUI(frame);
- if(chooser != null) {
+ if (chooser != null) {
SwingUtilities.updateComponentTreeUI(chooser);
}
frame.pack();
} catch (UnsupportedLookAndFeelException exc) {
// This should not happen because we already checked
- ((DefaultComboBoxModel)lafComboBox.getModel()).removeElement(supportedLaF);
+ ((DefaultComboBoxModel) lafComboBox.getModel()).
+ removeElement(supportedLaF);
}
}
}
}
- private class FilePreviewer extends JComponent implements PropertyChangeListener {
+
+ private class FilePreviewer extends JComponent implements
+ PropertyChangeListener {
+
ImageIcon thumbnail = null;
+ @SuppressWarnings("LeakingThisInConstructor")
public FilePreviewer(JFileChooser fc) {
setPreferredSize(new Dimension(100, 50));
fc.addPropertyChangeListener(this);
@@ -684,9 +745,10 @@
thumbnail = null;
} else {
ImageIcon tmpIcon = new ImageIcon(f.getPath());
- if(tmpIcon.getIconWidth() > 90) {
+ if (tmpIcon.getIconWidth() > 90) {
thumbnail = new ImageIcon(
- tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT));
+ tmpIcon.getImage().getScaledInstance(90, -1,
+ Image.SCALE_DEFAULT));
} else {
thumbnail = tmpIcon;
}
@@ -695,23 +757,24 @@
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
- if (prop == SELECTED_FILE_CHANGED_PROPERTY) {
- if(isShowing()) {
+ if (SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
+ if (isShowing()) {
loadImage((File) e.getNewValue());
repaint();
}
}
}
+ @Override
public void paint(Graphics g) {
- if(thumbnail != null) {
- int x = getWidth()/2 - thumbnail.getIconWidth()/2;
- int y = getHeight()/2 - thumbnail.getIconHeight()/2;
- if(y < 0) {
+ if (thumbnail != null) {
+ int x = getWidth() / 2 - thumbnail.getIconWidth() / 2;
+ int y = getHeight() / 2 - thumbnail.getIconHeight() / 2;
+ if (y < 0) {
y = 0;
}
- if(x < 5) {
+ if (x < 5) {
x = 5;
}
thumbnail.paintIcon(this, g, x, y);
@@ -720,46 +783,57 @@
}
public static void main(String s[]) {
- /*
- NOTE: By default, the look and feel will be set to the
- Cross Platform Look and Feel (which is currently Metal).
- The user may someday be able to override the default
- via a system property. If you as the developer want to
- be sure that a particular L&F is set, you can do so
- by calling UIManager.setLookAndFeel(). For example, the
- first code snippet below forcibly sets the UI to be the
- System Look and Feel. The second code snippet forcibly
- sets the look and feel to the Cross Platform L&F.
+ try {
+ SwingUtilities.invokeAndWait(new Runnable() {
- Snippet 1:
- try {
- UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
- } catch (Exception exc) {
- System.err.println("Error loading L&F: " + exc);
- }
+ public void run() {
+ /*
+ * NOTE: By default, the look and feel will be set to the
+ * Cross Platform Look and Feel (which is currently Metal).
+ * The following code tries to set the Look and Feel to Nimbus.
+ * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/nimbus.html
+ */
+ try {
+ for (LookAndFeelInfo info : UIManager.
+ getInstalledLookAndFeels()) {
+ if (NIMBUS_LAF_NAME.equals(info.getName())) {
+ UIManager.setLookAndFeel(info.getClassName());
+ break;
+ }
+ }
+ } catch (Exception ignored) {
+ }
- Snippet 2:
- try {
- UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
- } catch (Exception exc) {
- System.err.println("Error loading L&F: " + exc);
- }
- */
+ FileChooserDemo panel = new FileChooserDemo();
- FileChooserDemo panel = new FileChooserDemo();
-
- frame = new JFrame("FileChooserDemo");
- frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
- frame.getContentPane().add("Center", panel);
- frame.pack();
- frame.setVisible(true);
+ frame = new JFrame("FileChooserDemo");
+ frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+ frame.getContentPane().add("Center", panel);
+ frame.pack();
+ frame.setVisible(true);
+ }
+ });
+ } catch (InterruptedException ex) {
+ Logger.getLogger(FileChooserDemo.class.getName()).log(Level.SEVERE,
+ null,
+ ex);
+ } catch (InvocationTargetException ex) {
+ Logger.getLogger(FileChooserDemo.class.getName()).log(Level.SEVERE,
+ null,
+ ex);
+ }
}
+
private static class InsetPanel extends JPanel {
+
Insets i;
+
InsetPanel(Insets i) {
this.i = i;
}
+
+ @Override
public Insets getInsets() {
return i;
}
--- a/jdk/src/share/demo/jfc/Metalworks/AquaMetalTheme.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/AquaMetalTheme.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,31 +29,39 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-
-import javax.swing.plaf.*;
-import javax.swing.plaf.metal.*;
-import javax.swing.*;
-import javax.swing.border.*;
-import java.awt.*;
+import javax.swing.plaf.ColorUIResource;
+import javax.swing.plaf.metal.DefaultMetalTheme;
+
/**
* This class describes a theme using "blue-green" colors.
*
* @author Steve Wilson
+ * @author Alexander Kouznetsov
*/
public class AquaMetalTheme extends DefaultMetalTheme {
- public String getName() { return "Oxide"; }
-
+ @Override
+ public String getName() {
+ return "Oxide";
+ }
private final ColorUIResource primary1 = new ColorUIResource(102, 153, 153);
private final ColorUIResource primary2 = new ColorUIResource(128, 192, 192);
private final ColorUIResource primary3 = new ColorUIResource(159, 235, 235);
- protected ColorUIResource getPrimary1() { return primary1; }
- protected ColorUIResource getPrimary2() { return primary2; }
- protected ColorUIResource getPrimary3() { return primary3; }
+ @Override
+ protected ColorUIResource getPrimary1() {
+ return primary1;
+ }
+ @Override
+ protected ColorUIResource getPrimary2() {
+ return primary2;
+ }
+
+ @Override
+ protected ColorUIResource getPrimary3() {
+ return primary3;
+ }
}
--- a/jdk/src/share/demo/jfc/Metalworks/BigContrastMetalTheme.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/BigContrastMetalTheme.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,9 +29,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-
import javax.swing.plaf.*;
import javax.swing.plaf.metal.*;
@@ -39,54 +36,91 @@
import javax.swing.border.*;
import java.awt.*;
+
/**
* This class describes a theme using "green" colors.
*
* @author Steve Wilson
+ * @author Alexander Kouznetsov
*/
public class BigContrastMetalTheme extends ContrastMetalTheme {
- public String getName() { return "Low Vision"; }
+ @Override
+ public String getName() {
+ return "Low Vision";
+ }
+ private final FontUIResource controlFont = new FontUIResource("Dialog",
+ Font.BOLD, 24);
+ private final FontUIResource systemFont = new FontUIResource("Dialog",
+ Font.PLAIN, 24);
+ private final FontUIResource windowTitleFont = new FontUIResource("Dialog",
+ Font.BOLD, 24);
+ private final FontUIResource userFont = new FontUIResource("SansSerif",
+ Font.PLAIN, 24);
+ private final FontUIResource smallFont = new FontUIResource("Dialog",
+ Font.PLAIN, 20);
+
+ @Override
+ public FontUIResource getControlTextFont() {
+ return controlFont;
+ }
+
+ @Override
+ public FontUIResource getSystemTextFont() {
+ return systemFont;
+ }
- private final FontUIResource controlFont = new FontUIResource("Dialog", Font.BOLD, 24);
- private final FontUIResource systemFont = new FontUIResource("Dialog", Font.PLAIN, 24);
- private final FontUIResource windowTitleFont = new FontUIResource("Dialog", Font.BOLD, 24);
- private final FontUIResource userFont = new FontUIResource("SansSerif", Font.PLAIN, 24);
- private final FontUIResource smallFont = new FontUIResource("Dialog", Font.PLAIN, 20);
+ @Override
+ public FontUIResource getUserTextFont() {
+ return userFont;
+ }
+
+ @Override
+ public FontUIResource getMenuTextFont() {
+ return controlFont;
+ }
+
+ @Override
+ public FontUIResource getWindowTitleFont() {
+ return windowTitleFont;
+ }
+
+ @Override
+ public FontUIResource getSubTextFont() {
+ return smallFont;
+ }
+
+ @Override
+ public void addCustomEntriesToTable(UIDefaults table) {
+ super.addCustomEntriesToTable(table);
+
+ final int internalFrameIconSize = 30;
+ table.put("InternalFrame.closeIcon", MetalIconFactory.
+ getInternalFrameCloseIcon(internalFrameIconSize));
+ table.put("InternalFrame.maximizeIcon", MetalIconFactory.
+ getInternalFrameMaximizeIcon(internalFrameIconSize));
+ table.put("InternalFrame.iconifyIcon", MetalIconFactory.
+ getInternalFrameMinimizeIcon(internalFrameIconSize));
+ table.put("InternalFrame.minimizeIcon", MetalIconFactory.
+ getInternalFrameAltMaximizeIcon(internalFrameIconSize));
- public FontUIResource getControlTextFont() { return controlFont;}
- public FontUIResource getSystemTextFont() { return systemFont;}
- public FontUIResource getUserTextFont() { return userFont;}
- public FontUIResource getMenuTextFont() { return controlFont;}
- public FontUIResource getWindowTitleFont() { return windowTitleFont;}
- public FontUIResource getSubTextFont() { return smallFont;}
+ Border blackLineBorder = new BorderUIResource(new MatteBorder(2, 2, 2, 2,
+ Color.black));
+ Border textBorder = blackLineBorder;
- public void addCustomEntriesToTable(UIDefaults table) {
- super.addCustomEntriesToTable(table);
-
- final int internalFrameIconSize = 30;
- table.put("InternalFrame.closeIcon", MetalIconFactory.getInternalFrameCloseIcon(internalFrameIconSize));
- table.put("InternalFrame.maximizeIcon", MetalIconFactory.getInternalFrameMaximizeIcon(internalFrameIconSize));
- table.put("InternalFrame.iconifyIcon", MetalIconFactory.getInternalFrameMinimizeIcon(internalFrameIconSize));
- table.put("InternalFrame.minimizeIcon", MetalIconFactory.getInternalFrameAltMaximizeIcon(internalFrameIconSize));
+ table.put("ToolTip.border", blackLineBorder);
+ table.put("TitledBorder.border", blackLineBorder);
- Border blackLineBorder = new BorderUIResource( new MatteBorder( 2,2,2,2, Color.black) );
- Border textBorder = blackLineBorder;
-
- table.put( "ToolTip.border", blackLineBorder);
- table.put( "TitledBorder.border", blackLineBorder);
-
+ table.put("TextField.border", textBorder);
+ table.put("PasswordField.border", textBorder);
+ table.put("TextArea.border", textBorder);
+ table.put("TextPane.font", textBorder);
- table.put( "TextField.border", textBorder);
- table.put( "PasswordField.border", textBorder);
- table.put( "TextArea.border", textBorder);
- table.put( "TextPane.font", textBorder);
+ table.put("ScrollPane.border", blackLineBorder);
- table.put( "ScrollPane.border", blackLineBorder);
-
- table.put( "ScrollBar.width", new Integer(25) );
+ table.put("ScrollBar.width", 25);
--- a/jdk/src/share/demo/jfc/Metalworks/ContrastMetalTheme.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/ContrastMetalTheme.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,75 +29,131 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import javax.swing.plaf.*;
-import javax.swing.plaf.basic.*;
-import javax.swing.plaf.metal.*;
-import javax.swing.*;
-import javax.swing.border.*;
-import java.awt.*;
+import javax.swing.UIDefaults;
+import javax.swing.border.Border;
+import javax.swing.border.CompoundBorder;
+import javax.swing.border.LineBorder;
+import javax.swing.plaf.BorderUIResource;
+import javax.swing.plaf.ColorUIResource;
+import javax.swing.plaf.basic.BasicBorders;
+import javax.swing.plaf.metal.DefaultMetalTheme;
+
/**
* This class describes a higher-contrast Metal Theme.
*
* @author Michael C. Albers
+ * @author Alexander Kouznetsov
*/
-
public class ContrastMetalTheme extends DefaultMetalTheme {
- public String getName() { return "Contrast"; }
-
+ @Override
+ public String getName() {
+ return "Contrast";
+ }
private final ColorUIResource primary1 = new ColorUIResource(0, 0, 0);
private final ColorUIResource primary2 = new ColorUIResource(204, 204, 204);
private final ColorUIResource primary3 = new ColorUIResource(255, 255, 255);
- private final ColorUIResource primaryHighlight = new ColorUIResource(102,102,102);
+ private final ColorUIResource primaryHighlight = new ColorUIResource(102,
+ 102, 102);
+ private final ColorUIResource secondary2 =
+ new ColorUIResource(204, 204, 204);
+ private final ColorUIResource secondary3 =
+ new ColorUIResource(255, 255, 255);
+
+ @Override
+ protected ColorUIResource getPrimary1() {
+ return primary1;
+ }
+
+ @Override
+ protected ColorUIResource getPrimary2() {
+ return primary2;
+ }
- private final ColorUIResource secondary2 = new ColorUIResource(204, 204, 204);
- private final ColorUIResource secondary3 = new ColorUIResource(255, 255, 255);
- private final ColorUIResource controlHighlight = new ColorUIResource(102,102,102);
+ @Override
+ protected ColorUIResource getPrimary3() {
+ return primary3;
+ }
+
+ @Override
+ public ColorUIResource getPrimaryControlHighlight() {
+ return primaryHighlight;
+ }
- protected ColorUIResource getPrimary1() { return primary1; }
- protected ColorUIResource getPrimary2() { return primary2; }
- protected ColorUIResource getPrimary3() { return primary3; }
- public ColorUIResource getPrimaryControlHighlight() { return primaryHighlight;}
+ @Override
+ protected ColorUIResource getSecondary2() {
+ return secondary2;
+ }
+
+ @Override
+ protected ColorUIResource getSecondary3() {
+ return secondary3;
+ }
- protected ColorUIResource getSecondary2() { return secondary2; }
- protected ColorUIResource getSecondary3() { return secondary3; }
- public ColorUIResource getControlHighlight() { return super.getSecondary3(); }
+ @Override
+ public ColorUIResource getControlHighlight() {
+ return super.getSecondary3();
+ }
+
+ @Override
+ public ColorUIResource getFocusColor() {
+ return getBlack();
+ }
- public ColorUIResource getFocusColor() { return getBlack(); }
+ @Override
+ public ColorUIResource getTextHighlightColor() {
+ return getBlack();
+ }
+
+ @Override
+ public ColorUIResource getHighlightedTextColor() {
+ return getWhite();
+ }
- public ColorUIResource getTextHighlightColor() { return getBlack(); }
- public ColorUIResource getHighlightedTextColor() { return getWhite(); }
+ @Override
+ public ColorUIResource getMenuSelectedBackground() {
+ return getBlack();
+ }
+
+ @Override
+ public ColorUIResource getMenuSelectedForeground() {
+ return getWhite();
+ }
- public ColorUIResource getMenuSelectedBackground() { return getBlack(); }
- public ColorUIResource getMenuSelectedForeground() { return getWhite(); }
- public ColorUIResource getAcceleratorForeground() { return getBlack(); }
- public ColorUIResource getAcceleratorSelectedForeground() { return getWhite(); }
+ @Override
+ public ColorUIResource getAcceleratorForeground() {
+ return getBlack();
+ }
+ @Override
+ public ColorUIResource getAcceleratorSelectedForeground() {
+ return getWhite();
+ }
+ @Override
public void addCustomEntriesToTable(UIDefaults table) {
- Border blackLineBorder = new BorderUIResource(new LineBorder( getBlack() ));
- Border whiteLineBorder = new BorderUIResource(new LineBorder( getWhite() ));
+ Border blackLineBorder =
+ new BorderUIResource(new LineBorder(getBlack()));
+ Border whiteLineBorder =
+ new BorderUIResource(new LineBorder(getWhite()));
- Object textBorder = new BorderUIResource( new CompoundBorder(
- blackLineBorder,
- new BasicBorders.MarginBorder()));
+ Object textBorder = new BorderUIResource(new CompoundBorder(
+ blackLineBorder,
+ new BasicBorders.MarginBorder()));
- table.put( "ToolTip.border", blackLineBorder);
- table.put( "TitledBorder.border", blackLineBorder);
- table.put( "Table.focusCellHighlightBorder", whiteLineBorder);
- table.put( "Table.focusCellForeground", getWhite());
+ table.put("ToolTip.border", blackLineBorder);
+ table.put("TitledBorder.border", blackLineBorder);
+ table.put("Table.focusCellHighlightBorder", whiteLineBorder);
+ table.put("Table.focusCellForeground", getWhite());
- table.put( "TextField.border", textBorder);
- table.put( "PasswordField.border", textBorder);
- table.put( "TextArea.border", textBorder);
- table.put( "TextPane.font", textBorder);
+ table.put("TextField.border", textBorder);
+ table.put("PasswordField.border", textBorder);
+ table.put("TextArea.border", textBorder);
+ table.put("TextPane.font", textBorder);
}
-
}
--- a/jdk/src/share/demo/jfc/Metalworks/DemoMetalTheme.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/DemoMetalTheme.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,15 +29,13 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-
-import javax.swing.plaf.*;
-import javax.swing.plaf.metal.*;
-import javax.swing.*;
-import javax.swing.border.*;
-import java.awt.*;
+import java.awt.Font;
+import javax.swing.UIDefaults;
+import javax.swing.plaf.FontUIResource;
+import javax.swing.plaf.metal.DefaultMetalTheme;
+import javax.swing.plaf.metal.MetalIconFactory;
+
/**
* This class describes a theme using large fonts.
@@ -45,37 +43,71 @@
* where people will have trouble seeing what you're doing.
*
* @author Steve Wilson
+ * @author Alexander Kouznetsov
*/
public class DemoMetalTheme extends DefaultMetalTheme {
- public String getName() { return "Presentation"; }
+ @Override
+ public String getName() {
+ return "Presentation";
+ }
+ private final FontUIResource controlFont = new FontUIResource("Dialog",
+ Font.BOLD, 18);
+ private final FontUIResource systemFont = new FontUIResource("Dialog",
+ Font.PLAIN, 18);
+ private final FontUIResource userFont = new FontUIResource("SansSerif",
+ Font.PLAIN, 18);
+ private final FontUIResource smallFont = new FontUIResource("Dialog",
+ Font.PLAIN, 14);
- private final FontUIResource controlFont = new FontUIResource("Dialog", Font.BOLD, 18);
- private final FontUIResource systemFont = new FontUIResource("Dialog", Font.PLAIN, 18);
- private final FontUIResource userFont = new FontUIResource("SansSerif", Font.PLAIN, 18);
- private final FontUIResource smallFont = new FontUIResource("Dialog", Font.PLAIN, 14);
+ @Override
+ public FontUIResource getControlTextFont() {
+ return controlFont;
+ }
+
+ @Override
+ public FontUIResource getSystemTextFont() {
+ return systemFont;
+ }
+
+ @Override
+ public FontUIResource getUserTextFont() {
+ return userFont;
+ }
- public FontUIResource getControlTextFont() { return controlFont;}
- public FontUIResource getSystemTextFont() { return systemFont;}
- public FontUIResource getUserTextFont() { return userFont;}
- public FontUIResource getMenuTextFont() { return controlFont;}
- public FontUIResource getWindowTitleFont() { return controlFont;}
- public FontUIResource getSubTextFont() { return smallFont;}
+ @Override
+ public FontUIResource getMenuTextFont() {
+ return controlFont;
+ }
+ @Override
+ public FontUIResource getWindowTitleFont() {
+ return controlFont;
+ }
+
+ @Override
+ public FontUIResource getSubTextFont() {
+ return smallFont;
+ }
+
+ @Override
public void addCustomEntriesToTable(UIDefaults table) {
- super.addCustomEntriesToTable(table);
+ super.addCustomEntriesToTable(table);
- final int internalFrameIconSize = 22;
- table.put("InternalFrame.closeIcon", MetalIconFactory.getInternalFrameCloseIcon(internalFrameIconSize));
- table.put("InternalFrame.maximizeIcon", MetalIconFactory.getInternalFrameMaximizeIcon(internalFrameIconSize));
- table.put("InternalFrame.iconifyIcon", MetalIconFactory.getInternalFrameMinimizeIcon(internalFrameIconSize));
- table.put("InternalFrame.minimizeIcon", MetalIconFactory.getInternalFrameAltMaximizeIcon(internalFrameIconSize));
+ final int internalFrameIconSize = 22;
+ table.put("InternalFrame.closeIcon", MetalIconFactory.
+ getInternalFrameCloseIcon(internalFrameIconSize));
+ table.put("InternalFrame.maximizeIcon", MetalIconFactory.
+ getInternalFrameMaximizeIcon(internalFrameIconSize));
+ table.put("InternalFrame.iconifyIcon", MetalIconFactory.
+ getInternalFrameMinimizeIcon(internalFrameIconSize));
+ table.put("InternalFrame.minimizeIcon", MetalIconFactory.
+ getInternalFrameAltMaximizeIcon(internalFrameIconSize));
- table.put( "ScrollBar.width", new Integer(21) );
+ table.put("ScrollBar.width", 21);
}
-
}
--- a/jdk/src/share/demo/jfc/Metalworks/GreenMetalTheme.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/GreenMetalTheme.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,32 +29,40 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-
-import javax.swing.plaf.*;
-import javax.swing.plaf.metal.*;
-import javax.swing.*;
-import javax.swing.border.*;
-import java.awt.*;
+import javax.swing.plaf.ColorUIResource;
+import javax.swing.plaf.metal.DefaultMetalTheme;
+
/**
* This class describes a theme using "green" colors.
*
* @author Steve Wilson
+ * @author Alexander Kouznetsov
*/
public class GreenMetalTheme extends DefaultMetalTheme {
- public String getName() { return "Emerald"; }
-
- // greenish colors
+ @Override
+ public String getName() {
+ return "Emerald";
+ }
+ // greenish colors
private final ColorUIResource primary1 = new ColorUIResource(51, 102, 51);
private final ColorUIResource primary2 = new ColorUIResource(102, 153, 102);
private final ColorUIResource primary3 = new ColorUIResource(153, 204, 153);
- protected ColorUIResource getPrimary1() { return primary1; }
- protected ColorUIResource getPrimary2() { return primary2; }
- protected ColorUIResource getPrimary3() { return primary3; }
+ @Override
+ protected ColorUIResource getPrimary1() {
+ return primary1;
+ }
+ @Override
+ protected ColorUIResource getPrimary2() {
+ return primary2;
+ }
+
+ @Override
+ protected ColorUIResource getPrimary3() {
+ return primary3;
+ }
}
--- a/jdk/src/share/demo/jfc/Metalworks/KhakiMetalTheme.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/KhakiMetalTheme.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,39 +29,60 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-
-import javax.swing.plaf.*;
-import javax.swing.plaf.metal.*;
-import javax.swing.*;
-import javax.swing.border.*;
-import java.awt.*;
+import javax.swing.plaf.ColorUIResource;
+import javax.swing.plaf.metal.DefaultMetalTheme;
+
/**
* This class describes a theme using "khaki" colors.
*
* @author Steve Wilson
+ * @author Alexander Kouznetsov
*/
public class KhakiMetalTheme extends DefaultMetalTheme {
- public String getName() { return "Sandstone"; }
-
- private final ColorUIResource primary1 = new ColorUIResource( 87, 87, 47);
+ @Override
+ public String getName() {
+ return "Sandstone";
+ }
+ private final ColorUIResource primary1 = new ColorUIResource(87, 87, 47);
private final ColorUIResource primary2 = new ColorUIResource(159, 151, 111);
private final ColorUIResource primary3 = new ColorUIResource(199, 183, 143);
+ private final ColorUIResource secondary1 =
+ new ColorUIResource(111, 111, 111);
+ private final ColorUIResource secondary2 =
+ new ColorUIResource(159, 159, 159);
+ private final ColorUIResource secondary3 =
+ new ColorUIResource(231, 215, 183);
- private final ColorUIResource secondary1 = new ColorUIResource( 111, 111, 111);
- private final ColorUIResource secondary2 = new ColorUIResource(159, 159, 159);
- private final ColorUIResource secondary3 = new ColorUIResource(231, 215, 183);
+ @Override
+ protected ColorUIResource getPrimary1() {
+ return primary1;
+ }
+
+ @Override
+ protected ColorUIResource getPrimary2() {
+ return primary2;
+ }
- protected ColorUIResource getPrimary1() { return primary1; }
- protected ColorUIResource getPrimary2() { return primary2; }
- protected ColorUIResource getPrimary3() { return primary3; }
+ @Override
+ protected ColorUIResource getPrimary3() {
+ return primary3;
+ }
+
+ @Override
+ protected ColorUIResource getSecondary1() {
+ return secondary1;
+ }
- protected ColorUIResource getSecondary1() { return secondary1; }
- protected ColorUIResource getSecondary2() { return secondary2; }
- protected ColorUIResource getSecondary3() { return secondary3; }
+ @Override
+ protected ColorUIResource getSecondary2() {
+ return secondary2;
+ }
+ @Override
+ protected ColorUIResource getSecondary3() {
+ return secondary3;
+ }
}
--- a/jdk/src/share/demo/jfc/Metalworks/MetalThemeMenu.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/MetalThemeMenu.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,51 +29,57 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-
-import javax.swing.plaf.metal.*;
-import javax.swing.*;
-import javax.swing.border.*;
-import java.awt.*;
-import java.awt.event.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import javax.swing.ButtonGroup;
+import javax.swing.JMenu;
+import javax.swing.JRadioButtonMenuItem;
+import javax.swing.UIManager;
+import javax.swing.plaf.metal.MetalLookAndFeel;
+import javax.swing.plaf.metal.MetalTheme;
+
/**
* This class describes a theme using "green" colors.
*
* @author Steve Wilson
+ * @author Alexander Kouznetsov
*/
-public class MetalThemeMenu extends JMenu implements ActionListener{
+@SuppressWarnings("serial")
+public class MetalThemeMenu extends JMenu implements ActionListener {
+
+ MetalTheme[] themes;
- MetalTheme[] themes;
- public MetalThemeMenu(String name, MetalTheme[] themeArray) {
- super(name);
- themes = themeArray;
- ButtonGroup group = new ButtonGroup();
- for (int i = 0; i < themes.length; i++) {
- JRadioButtonMenuItem item = new JRadioButtonMenuItem( themes[i].getName() );
- group.add(item);
- add( item );
- item.setActionCommand(i+"");
- item.addActionListener(this);
- if ( i == 0)
- item.setSelected(true);
+ @SuppressWarnings("LeakingThisInConstructor")
+ public MetalThemeMenu(String name, MetalTheme[] themeArray) {
+ super(name);
+ themes = themeArray;
+ ButtonGroup group = new ButtonGroup();
+ for (int i = 0; i < themes.length; i++) {
+ JRadioButtonMenuItem item = new JRadioButtonMenuItem(themes[i].
+ getName());
+ group.add(item);
+ add(item);
+ item.setActionCommand(i + "");
+ item.addActionListener(this);
+ if (i == 0) {
+ item.setSelected(true);
+ }
+ }
+
}
- }
+ public void actionPerformed(ActionEvent e) {
+ String numStr = e.getActionCommand();
+ MetalTheme selectedTheme = themes[Integer.parseInt(numStr)];
+ MetalLookAndFeel.setCurrentTheme(selectedTheme);
+ try {
+ UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
+ } catch (Exception ex) {
+ System.out.println("Failed loading Metal");
+ System.out.println(ex);
+ }
- public void actionPerformed(ActionEvent e) {
- String numStr = e.getActionCommand();
- MetalTheme selectedTheme = themes[ Integer.parseInt(numStr) ];
- MetalLookAndFeel.setCurrentTheme(selectedTheme);
- try {
- UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
- } catch (Exception ex) {
- System.out.println("Failed loading Metal");
- System.out.println(ex);
}
-
- }
-
}
--- a/jdk/src/share/demo/jfc/Metalworks/Metalworks.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/Metalworks.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,34 +29,35 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-
-import java.awt.*;
-import javax.swing.*;
-import javax.swing.border.*;
+import java.awt.Toolkit;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.UIManager;
+import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.metal.MetalLookAndFeel;
+
/**
- * This application is a demo of the Metal Look & Feel
- *
- * @author Steve Wilson
- */
+ * This application is a demo of the Metal Look & Feel
+ *
+ * @author Steve Wilson
+ * @author Alexander Kouznetsov
+ */
public class Metalworks {
- public static void main( String[] args ) {
+ public static void main(String[] args) {
UIManager.put("swing.boldMetal", Boolean.FALSE);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame.setDefaultLookAndFeelDecorated(true);
Toolkit.getDefaultToolkit().setDynamicLayout(true);
- System.setProperty("sun.awt.noerasebackground","true");
-
+ System.setProperty("sun.awt.noerasebackground", "true");
try {
UIManager.setLookAndFeel(new MetalLookAndFeel());
- }
- catch ( UnsupportedLookAndFeelException e ) {
- System.out.println ("Metal Look & Feel not supported on this platform. \nProgram Terminated");
+ } catch (UnsupportedLookAndFeelException e) {
+ System.out.println(
+ "Metal Look & Feel not supported on this platform. \n"
+ + "Program Terminated");
System.exit(0);
}
JFrame frame = new MetalworksFrame();
--- a/jdk/src/share/demo/jfc/Metalworks/MetalworksDocumentFrame.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/MetalworksDocumentFrame.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,21 +29,32 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import java.awt.*;
-import java.awt.event.*;
-import java.util.*;
-import javax.swing.*;
-import javax.swing.border.*;
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.Dimension;
+import java.awt.Insets;
+import java.awt.LayoutManager;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import javax.swing.JComponent;
+import javax.swing.JInternalFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTextArea;
+import javax.swing.JTextField;
+import javax.swing.border.EmptyBorder;
/**
- * This is a subclass of JInternalFrame which displays documents.
- *
- * @author Steve Wilson
- */
+ * This is a subclass of JInternalFrame which displays documents.
+ *
+ * @author Steve Wilson
+ */
+@SuppressWarnings("serial")
public class MetalworksDocumentFrame extends JInternalFrame {
static int openFrameCount = 0;
@@ -59,27 +70,27 @@
top.setLayout(new BorderLayout());
top.add(buildAddressPanel(), BorderLayout.NORTH);
- JTextArea content = new JTextArea( 15, 30 );
- content.setBorder( new EmptyBorder(0,5 ,0, 5) );
+ JTextArea content = new JTextArea(15, 30);
+ content.setBorder(new EmptyBorder(0, 5, 0, 5));
content.setLineWrap(true);
JScrollPane textScroller = new JScrollPane(content,
- JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
- JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
- top.add( textScroller, BorderLayout.CENTER);
+ JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
+ JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
+ top.add(textScroller, BorderLayout.CENTER);
setContentPane(top);
pack();
- setLocation( offset * openFrameCount, offset *openFrameCount);
+ setLocation(offset * openFrameCount, offset * openFrameCount);
}
private JPanel buildAddressPanel() {
JPanel p = new JPanel();
- p.setLayout( new LabeledPairLayout() );
+ p.setLayout(new LabeledPairLayout());
JLabel toLabel = new JLabel("To: ", JLabel.RIGHT);
@@ -103,83 +114,79 @@
}
+
class LabeledPairLayout implements LayoutManager {
- Vector labels = new Vector();
- Vector fields = new Vector();
-
- int yGap = 2;
- int xGap = 2;
+ List<Component> labels = new ArrayList<Component>();
+ List<Component> fields = new ArrayList<Component>();
+ int yGap = 2;
+ int xGap = 2;
- public void addLayoutComponent(String s, Component c) {
- if (s.equals("label")) {
- labels.addElement(c);
- } else {
- fields.addElement(c);
- }
- }
+ public void addLayoutComponent(String s, Component c) {
+ if (s.equals("label")) {
+ labels.add(c);
+ } else {
+ fields.add(c);
+ }
+ }
- public void layoutContainer(Container c) {
- Insets insets = c.getInsets();
+ public void layoutContainer(Container c) {
+ Insets insets = c.getInsets();
- int labelWidth = 0;
- Enumeration labelIter = labels.elements();
- while(labelIter.hasMoreElements()) {
- JComponent comp = (JComponent)labelIter.nextElement();
- labelWidth = Math.max( labelWidth, comp.getPreferredSize().width );
- }
+ int labelWidth = 0;
+ for (Component comp : labels) {
+ labelWidth = Math.max(labelWidth, comp.getPreferredSize().width);
+ }
- int yPos = insets.top;
+ int yPos = insets.top;
- Enumeration fieldIter = fields.elements();
- labelIter = labels.elements();
- while(labelIter.hasMoreElements() && fieldIter.hasMoreElements()) {
- JComponent label = (JComponent)labelIter.nextElement();
- JComponent field = (JComponent)fieldIter.nextElement();
- int height = Math.max(label.getPreferredSize().height, field.getPreferredSize().height);
- label.setBounds( insets.left, yPos, labelWidth, height );
- field.setBounds( insets.left + labelWidth + xGap,
- yPos,
- c.getSize().width - (labelWidth +xGap + insets.left + insets.right),
- height );
- yPos += (height + yGap);
- }
+ Iterator<Component> fieldIter = fields.listIterator();
+ Iterator<Component> labelIter = labels.listIterator();
+ while (labelIter.hasNext() && fieldIter.hasNext()) {
+ JComponent label = (JComponent) labelIter.next();
+ JComponent field = (JComponent) fieldIter.next();
+ int height = Math.max(label.getPreferredSize().height, field.
+ getPreferredSize().height);
+ label.setBounds(insets.left, yPos, labelWidth, height);
+ field.setBounds(insets.left + labelWidth + xGap,
+ yPos,
+ c.getSize().width - (labelWidth + xGap + insets.left
+ + insets.right),
+ height);
+ yPos += (height + yGap);
+ }
- }
-
+ }
- public Dimension minimumLayoutSize(Container c) {
- Insets insets = c.getInsets();
+ public Dimension minimumLayoutSize(Container c) {
+ Insets insets = c.getInsets();
- int labelWidth = 0;
- Enumeration labelIter = labels.elements();
- while(labelIter.hasMoreElements()) {
- JComponent comp = (JComponent)labelIter.nextElement();
- labelWidth = Math.max( labelWidth, comp.getPreferredSize().width );
- }
+ int labelWidth = 0;
+ for (Component comp : labels) {
+ labelWidth = Math.max(labelWidth, comp.getPreferredSize().width);
+ }
- int yPos = insets.top;
+ int yPos = insets.top;
- labelIter = labels.elements();
- Enumeration fieldIter = fields.elements();
- while(labelIter.hasMoreElements() && fieldIter.hasMoreElements()) {
- JComponent label = (JComponent)labelIter.nextElement();
- JComponent field = (JComponent)fieldIter.nextElement();
- int height = Math.max(label.getPreferredSize().height, field.getPreferredSize().height);
- yPos += (height + yGap);
- }
- return new Dimension( labelWidth * 3 , yPos );
- }
+ Iterator<Component> labelIter = labels.listIterator();
+ Iterator<Component> fieldIter = fields.listIterator();
+ while (labelIter.hasNext() && fieldIter.hasNext()) {
+ Component label = labelIter.next();
+ Component field = fieldIter.next();
+ int height = Math.max(label.getPreferredSize().height, field.
+ getPreferredSize().height);
+ yPos += (height + yGap);
+ }
+ return new Dimension(labelWidth * 3, yPos);
+ }
- public Dimension preferredLayoutSize(Container c) {
- Dimension d = minimumLayoutSize(c);
- d.width *= 2;
- return d;
- }
+ public Dimension preferredLayoutSize(Container c) {
+ Dimension d = minimumLayoutSize(c);
+ d.width *= 2;
+ return d;
+ }
- public void removeLayoutComponent(Component c) {}
-
+ public void removeLayoutComponent(Component c) {
+ }
+ }
}
-
-
-}
--- a/jdk/src/share/demo/jfc/Metalworks/MetalworksFrame.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/MetalworksFrame.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,50 +29,70 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import java.awt.*;
-import java.io.*;
-import java.awt.event.*;
-import java.beans.*;
-import javax.swing.*;
-import javax.swing.border.*;
-
-import javax.swing.plaf.metal.*;
+import java.awt.Dimension;
+import java.awt.Toolkit;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.io.InputStream;
+import javax.swing.ButtonGroup;
+import javax.swing.JCheckBoxMenuItem;
+import javax.swing.JComponent;
+import javax.swing.JDesktopPane;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JInternalFrame;
+import javax.swing.JMenu;
+import javax.swing.JMenuBar;
+import javax.swing.JMenuItem;
+import javax.swing.JOptionPane;
+import javax.swing.JRadioButtonMenuItem;
+import javax.swing.UIManager;
+import javax.swing.plaf.metal.DefaultMetalTheme;
+import javax.swing.plaf.metal.MetalTheme;
+import javax.swing.plaf.metal.OceanTheme;
/**
- * This is the main container frame for the Metalworks demo app
- *
- * @author Steve Wilson
- */
-public class MetalworksFrame extends JFrame {
+ * This is the main container frame for the Metalworks demo app
+ *
+ * @author Steve Wilson
+ * @author Alexander Kouznetsov
+ */
+@SuppressWarnings("serial")
+public final class MetalworksFrame extends JFrame {
JMenuBar menuBar;
JDesktopPane desktop;
JInternalFrame toolPalette;
JCheckBoxMenuItem showToolPaletteMenuItem;
-
- static final Integer DOCLAYER = new Integer(5);
- static final Integer TOOLLAYER = new Integer(6);
- static final Integer HELPLAYER = new Integer(7);
-
- static final String ABOUTMSG = "Metalworks \n \nAn application written to show off the Java Look & Feel. \n \nWritten by the JavaSoft Look & Feel Team \n Michael Albers\n Tom Santos\n Jeff Shapiro\n Steve Wilson";
-
+ static final Integer DOCLAYER = 5;
+ static final Integer TOOLLAYER = 6;
+ static final Integer HELPLAYER = 7;
+ static final String ABOUTMSG = "Metalworks \n \nAn application written to "
+ + "show off the Java Look & Feel. \n \nWritten by the JavaSoft "
+ + "Look & Feel Team \n Michael Albers\n Tom Santos\n "
+ + "Jeff Shapiro\n Steve Wilson";
public MetalworksFrame() {
super("Metalworks");
final int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
- setBounds ( inset, inset, screenSize.width - inset*2, screenSize.height - inset*2 );
+ setBounds(inset, inset, screenSize.width - inset * 2, screenSize.height - inset
+ * 2);
buildContent();
buildMenus();
this.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- quit();
- }});
- UIManager.addPropertyChangeListener(new UISwitchListener((JComponent)getRootPane()));
+
+ @Override
+ public void windowClosing(WindowEvent e) {
+ quit();
+ }
+ });
+ UIManager.addPropertyChangeListener(new UISwitchListener(
+ (JComponent) getRootPane()));
}
protected void buildMenus() {
@@ -87,20 +107,23 @@
// load a theme from a text file
MetalTheme myTheme = null;
try {
- InputStream istream = getClass().getResourceAsStream("/resources/MyTheme.theme");
- myTheme = new PropertiesMetalTheme(istream);
- } catch (NullPointerException e) {System.out.println(e);}
+ InputStream istream = getClass().getResourceAsStream(
+ "/resources/MyTheme.theme");
+ myTheme = new PropertiesMetalTheme(istream);
+ } catch (NullPointerException e) {
+ System.out.println(e);
+ }
// build an array of themes
MetalTheme[] themes = { new OceanTheme(),
- new DefaultMetalTheme(),
- new GreenMetalTheme(),
- new AquaMetalTheme(),
- new KhakiMetalTheme(),
- new DemoMetalTheme(),
- new ContrastMetalTheme(),
- new BigContrastMetalTheme(),
- myTheme };
+ new DefaultMetalTheme(),
+ new GreenMetalTheme(),
+ new AquaMetalTheme(),
+ new KhakiMetalTheme(),
+ new DemoMetalTheme(),
+ new ContrastMetalTheme(),
+ new BigContrastMetalTheme(),
+ myTheme };
// put the themes in a menu
JMenu themeMenu = new MetalThemeMenu("Theme", themes);
@@ -121,19 +144,25 @@
JMenuItem quit = new JMenuItem("Quit");
newWin.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- newDocument();
- }});
+
+ public void actionPerformed(ActionEvent e) {
+ newDocument();
+ }
+ });
open.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- openDocument();
- }});
+
+ public void actionPerformed(ActionEvent e) {
+ openDocument();
+ }
+ });
quit.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- quit();
- }});
+
+ public void actionPerformed(ActionEvent e) {
+ quit();
+ }
+ });
file.add(newWin);
file.add(open);
@@ -156,9 +185,11 @@
paste.setEnabled(false);
prefs.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- openPrefsWindow();
- }});
+
+ public void actionPerformed(ActionEvent e) {
+ openPrefsWindow();
+ }
+ });
edit.add(undo);
edit.addSeparator();
@@ -178,16 +209,18 @@
outBox.setEnabled(false);
inBox.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- openInBox();
- }});
+
+ public void actionPerformed(ActionEvent e) {
+ openInBox();
+ }
+ });
views.add(inBox);
views.add(outBox);
return views;
}
- protected JMenu buildSpeedMenu() {
+ protected JMenu buildSpeedMenu() {
JMenu speed = new JMenu("Drag");
JRadioButtonMenuItem live = new JRadioButtonMenuItem("Live");
@@ -203,28 +236,37 @@
live.setSelected(true);
- slow.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e){
- // for right now I'm saying if you set the mode
- // to something other than a specified mode
- // it will revert to the old way
- // This is mostly for comparison's sake
- desktop.setDragMode(-1);}});
+ slow.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent e) {
+ // for right now I'm saying if you set the mode
+ // to something other than a specified mode
+ // it will revert to the old way
+ // This is mostly for comparison's sake
+ desktop.setDragMode(-1);
+ }
+ });
- live.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e){
- desktop.setDragMode(JDesktopPane.LIVE_DRAG_MODE);}});
+ live.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent e) {
+ desktop.setDragMode(JDesktopPane.LIVE_DRAG_MODE);
+ }
+ });
- outline.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e){
- desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);}});
+ outline.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent e) {
+ desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
+ }
+ });
speed.add(live);
speed.add(outline);
speed.add(slow);
return speed;
- }
+ }
protected JMenu buildHelpMenu() {
JMenu help = new JMenu("Help");
@@ -232,15 +274,18 @@
JMenuItem openHelp = new JMenuItem("Open Help Window");
about.addActionListener(new ActionListener() {
+
public void actionPerformed(ActionEvent e) {
showAboutBox();
}
});
openHelp.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- openHelpWindow();
- }});
+
+ public void actionPerformed(ActionEvent e) {
+ openHelpWindow();
+ }
+ });
help.add(about);
help.add(openHelp);
@@ -263,7 +308,8 @@
try {
doc.setVisible(true);
doc.setSelected(true);
- } catch (java.beans.PropertyVetoException e2) {}
+ } catch (java.beans.PropertyVetoException e2) {
+ }
}
public void openDocument() {
@@ -277,7 +323,8 @@
try {
help.setVisible(true);
help.setSelected(true);
- } catch (java.beans.PropertyVetoException e2) {}
+ } catch (java.beans.PropertyVetoException e2) {
+ }
}
public void showAboutBox() {
@@ -286,7 +333,7 @@
public void openPrefsWindow() {
MetalworksPrefs dialog = new MetalworksPrefs(this);
- dialog.show();
+ dialog.setVisible(true);
}
@@ -296,6 +343,7 @@
try {
doc.setVisible(true);
doc.setSelected(true);
- } catch (java.beans.PropertyVetoException e2) {}
+ } catch (java.beans.PropertyVetoException e2) {
+ }
}
}
--- a/jdk/src/share/demo/jfc/Metalworks/MetalworksHelp.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/MetalworksHelp.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,8 +29,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
import javax.swing.*;
import java.awt.*;
@@ -40,26 +38,31 @@
import javax.swing.text.*;
import javax.swing.event.*;
-/*
+
+/**
* @author Steve Wilson
+ * @author Alexander Kouznetsov
*/
+@SuppressWarnings("serial")
public class MetalworksHelp extends JInternalFrame {
public MetalworksHelp() {
super("Help", true, true, true, true);
- setFrameIcon( (Icon)UIManager.get("Tree.openIcon")); // PENDING(steve) need more general palce to get this icon
- setBounds( 200, 25, 400, 400);
+ setFrameIcon((Icon) UIManager.get("Tree.openIcon")); // PENDING(steve) need more general place to get this icon
+ setBounds(200, 25, 400, 400);
HtmlPane html = new HtmlPane();
setContentPane(html);
}
-
}
+@SuppressWarnings("serial")
class HtmlPane extends JScrollPane implements HyperlinkListener {
+
JEditorPane html;
+ @SuppressWarnings("LeakingThisInConstructor")
public HtmlPane() {
try {
URL url = getClass().getResource("/resources/HelpFiles/toc.html");
@@ -67,7 +70,7 @@
html.setEditable(false);
html.addHyperlinkListener(this);
html.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES,
- Boolean.TRUE);
+ Boolean.TRUE);
JViewport vp = getViewport();
vp.add(html);
} catch (MalformedURLException e) {
@@ -106,6 +109,7 @@
SwingUtilities.invokeLater(new PageLoader(u, c));
}
+
/**
* temporary class that loads synchronously (although
* later than the request so that a cursor change
@@ -142,9 +146,7 @@
}
}
}
-
URL url;
Cursor cursor;
}
-
}
--- a/jdk/src/share/demo/jfc/Metalworks/MetalworksInBox.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/MetalworksInBox.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,22 +29,20 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import java.awt.*;
-import java.awt.event.*;
-import java.util.*;
-import javax.swing.*;
-import javax.swing.border.*;
-import javax.swing.tree.*;
+import javax.swing.JInternalFrame;
+import javax.swing.JScrollPane;
+import javax.swing.JTree;
+import javax.swing.tree.DefaultMutableTreeNode;
/**
- * This is a subclass of JInternalFrame which displays a tree.
- *
- * @author Steve Wilson
- */
+ * This is a subclass of JInternalFrame which displays a tree.
+ *
+ * @author Steve Wilson
+ * @author Alexander Kouznetsov
+ */
+@SuppressWarnings("serial")
public class MetalworksInBox extends JInternalFrame {
public MetalworksInBox() {
@@ -57,49 +55,47 @@
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Mail Boxes");
- top.add( unread = new DefaultMutableTreeNode("Unread Mail") );
- top.add( personal = new DefaultMutableTreeNode("Personal") );
- top.add( business = new DefaultMutableTreeNode("Business") );
- top.add( spam = new DefaultMutableTreeNode("Spam") );
+ top.add(unread = new DefaultMutableTreeNode("Unread Mail"));
+ top.add(personal = new DefaultMutableTreeNode("Personal"));
+ top.add(business = new DefaultMutableTreeNode("Business"));
+ top.add(spam = new DefaultMutableTreeNode("Spam"));
- unread.add( new DefaultMutableTreeNode("Buy Stuff Now") );
- unread.add( new DefaultMutableTreeNode("Read Me Now") );
- unread.add( new DefaultMutableTreeNode("Hot Offer") );
- unread.add( new DefaultMutableTreeNode("Re: Re: Thank You") );
- unread.add( new DefaultMutableTreeNode("Fwd: Good Joke") );
+ unread.add(new DefaultMutableTreeNode("Buy Stuff Now"));
+ unread.add(new DefaultMutableTreeNode("Read Me Now"));
+ unread.add(new DefaultMutableTreeNode("Hot Offer"));
+ unread.add(new DefaultMutableTreeNode("Re: Re: Thank You"));
+ unread.add(new DefaultMutableTreeNode("Fwd: Good Joke"));
- personal.add( new DefaultMutableTreeNode("Hi") );
- personal.add( new DefaultMutableTreeNode("Good to hear from you") );
- personal.add( new DefaultMutableTreeNode("Re: Thank You") );
+ personal.add(new DefaultMutableTreeNode("Hi"));
+ personal.add(new DefaultMutableTreeNode("Good to hear from you"));
+ personal.add(new DefaultMutableTreeNode("Re: Thank You"));
- business.add( new DefaultMutableTreeNode("Thanks for your order") );
- business.add( new DefaultMutableTreeNode("Price Quote") );
- business.add( new DefaultMutableTreeNode("Here is the invoice") );
- business.add( new DefaultMutableTreeNode("Project Metal: delivered on time") );
- business.add( new DefaultMutableTreeNode("Your salary raise approved") );
+ business.add(new DefaultMutableTreeNode("Thanks for your order"));
+ business.add(new DefaultMutableTreeNode("Price Quote"));
+ business.add(new DefaultMutableTreeNode("Here is the invoice"));
+ business.add(new DefaultMutableTreeNode(
+ "Project Metal: delivered on time"));
+ business.add(new DefaultMutableTreeNode("Your salary raise approved"));
- spam.add( new DefaultMutableTreeNode("Buy Now") );
- spam.add( new DefaultMutableTreeNode("Make $$$ Now") );
- spam.add( new DefaultMutableTreeNode("HOT HOT HOT") );
- spam.add( new DefaultMutableTreeNode("Buy Now") );
- spam.add( new DefaultMutableTreeNode("Don't Miss This") );
- spam.add( new DefaultMutableTreeNode("Opportunity in Precious Metals") );
- spam.add( new DefaultMutableTreeNode("Buy Now") );
- spam.add( new DefaultMutableTreeNode("Last Chance") );
- spam.add( new DefaultMutableTreeNode("Buy Now") );
- spam.add( new DefaultMutableTreeNode("Make $$$ Now") );
- spam.add( new DefaultMutableTreeNode("To Hot To Handle") );
- spam.add( new DefaultMutableTreeNode("I'm waiting for your call") );
+ spam.add(new DefaultMutableTreeNode("Buy Now"));
+ spam.add(new DefaultMutableTreeNode("Make $$$ Now"));
+ spam.add(new DefaultMutableTreeNode("HOT HOT HOT"));
+ spam.add(new DefaultMutableTreeNode("Buy Now"));
+ spam.add(new DefaultMutableTreeNode("Don't Miss This"));
+ spam.add(new DefaultMutableTreeNode("Opportunity in Precious Metals"));
+ spam.add(new DefaultMutableTreeNode("Buy Now"));
+ spam.add(new DefaultMutableTreeNode("Last Chance"));
+ spam.add(new DefaultMutableTreeNode("Buy Now"));
+ spam.add(new DefaultMutableTreeNode("Make $$$ Now"));
+ spam.add(new DefaultMutableTreeNode("To Hot To Handle"));
+ spam.add(new DefaultMutableTreeNode("I'm waiting for your call"));
JTree tree = new JTree(top);
JScrollPane treeScroller = new JScrollPane(tree);
treeScroller.setBackground(tree.getBackground());
setContentPane(treeScroller);
- setSize( 325, 200);
- setLocation( 75, 75);
+ setSize(325, 200);
+ setLocation(75, 75);
}
-
-
-
}
--- a/jdk/src/share/demo/jfc/Metalworks/MetalworksPrefs.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/MetalworksPrefs.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,50 +29,70 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import java.awt.*;
-import java.awt.event.*;
-import java.beans.*;
-import javax.swing.*;
-import javax.swing.border.*;
-import javax.swing.plaf.metal.*;
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.GridLayout;
+import java.awt.Insets;
+import java.awt.LayoutManager;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import javax.swing.ButtonGroup;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JComboBox;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JRadioButton;
+import javax.swing.JTabbedPane;
+import javax.swing.UIManager;
+import javax.swing.border.TitledBorder;
/**
- * This is dialog which allows users to choose preferences
- *
- * @author Steve Wilson
- */
-public class MetalworksPrefs extends JDialog {
+ * This is dialog which allows users to choose preferences
+ *
+ * @author Steve Wilson
+ * @author Alexander Kouznetsov
+ */
+@SuppressWarnings("serial")
+public final class MetalworksPrefs extends JDialog {
public MetalworksPrefs(JFrame f) {
super(f, "Preferences", true);
JPanel container = new JPanel();
- container.setLayout( new BorderLayout() );
+ container.setLayout(new BorderLayout());
JTabbedPane tabs = new JTabbedPane();
JPanel filters = buildFilterPanel();
JPanel conn = buildConnectingPanel();
- tabs.addTab( "Filters", null, filters );
- tabs.addTab( "Connecting", null, conn );
+ tabs.addTab("Filters", null, filters);
+ tabs.addTab("Connecting", null, conn);
JPanel buttonPanel = new JPanel();
- buttonPanel.setLayout ( new FlowLayout(FlowLayout.RIGHT) );
+ buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- CancelPressed();
- }});
- buttonPanel.add( cancel );
+
+ public void actionPerformed(ActionEvent e) {
+ CancelPressed();
+ }
+ });
+ buttonPanel.add(cancel);
JButton ok = new JButton("OK");
ok.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- OKPressed();
- }});
- buttonPanel.add( ok );
+
+ public void actionPerformed(ActionEvent e) {
+ OKPressed();
+ }
+ });
+ buttonPanel.add(ok);
getRootPane().setDefaultButton(ok);
container.add(tabs, BorderLayout.CENTER);
@@ -85,12 +105,12 @@
public JPanel buildFilterPanel() {
JPanel filters = new JPanel();
- filters.setLayout( new GridLayout(1, 0) );
+ filters.setLayout(new GridLayout(1, 0));
JPanel spamPanel = new JPanel();
spamPanel.setLayout(new ColumnLayout());
- spamPanel.setBorder( new TitledBorder("Spam") );
+ spamPanel.setBorder(new TitledBorder("Spam"));
ButtonGroup spamGroup = new ButtonGroup();
JRadioButton file = new JRadioButton("File in Spam Folder");
JRadioButton delete = new JRadioButton("Auto Delete");
@@ -106,7 +126,7 @@
JPanel autoRespond = new JPanel();
autoRespond.setLayout(new ColumnLayout());
- autoRespond.setBorder( new TitledBorder("Auto Response") );
+ autoRespond.setBorder(new TitledBorder("Auto Response"));
ButtonGroup respondGroup = new ButtonGroup();
JRadioButton none = new JRadioButton("None");
@@ -129,10 +149,10 @@
public JPanel buildConnectingPanel() {
JPanel connectPanel = new JPanel();
- connectPanel.setLayout( new ColumnLayout() );
+ connectPanel.setLayout(new ColumnLayout());
JPanel protoPanel = new JPanel();
- JLabel protoLabel = new JLabel ("Protocol");
+ JLabel protoLabel = new JLabel("Protocol");
JComboBox protocol = new JComboBox();
protocol.addItem("SMTP");
protocol.addItem("IMAP");
@@ -141,7 +161,7 @@
protoPanel.add(protocol);
JPanel attachmentPanel = new JPanel();
- JLabel attachmentLabel = new JLabel ("Attachments");
+ JLabel attachmentLabel = new JLabel("Attachments");
JComboBox attach = new JComboBox();
attach.addItem("Download Always");
attach.addItem("Ask size > 1 Meg");
@@ -152,7 +172,7 @@
JCheckBox autoConn = new JCheckBox("Auto Connect");
JCheckBox compress = new JCheckBox("Use Compression");
- autoConn.setSelected( true );
+ autoConn.setSelected(true);
connectPanel.add(protoPanel);
connectPanel.add(attachmentPanel);
@@ -161,18 +181,16 @@
return connectPanel;
}
-
-
protected void centerDialog() {
Dimension screenSize = this.getToolkit().getScreenSize();
Dimension size = this.getSize();
- screenSize.height = screenSize.height/2;
- screenSize.width = screenSize.width/2;
- size.height = size.height/2;
- size.width = size.width/2;
+ screenSize.height = screenSize.height / 2;
+ screenSize.width = screenSize.width / 2;
+ size.height = size.height / 2;
+ size.width = size.width / 2;
int y = screenSize.height - size.height;
int x = screenSize.width - size.width;
- this.setLocation(x,y);
+ this.setLocation(x, y);
}
public void CancelPressed() {
@@ -182,52 +200,54 @@
public void OKPressed() {
this.setVisible(false);
}
+}
-}
class ColumnLayout implements LayoutManager {
- int xInset = 5;
- int yInset = 5;
- int yGap = 2;
+ int xInset = 5;
+ int yInset = 5;
+ int yGap = 2;
- public void addLayoutComponent(String s, Component c) {}
+ public void addLayoutComponent(String s, Component c) {
+ }
- public void layoutContainer(Container c) {
- Insets insets = c.getInsets();
- int height = yInset + insets.top;
+ public void layoutContainer(Container c) {
+ Insets insets = c.getInsets();
+ int height = yInset + insets.top;
- Component[] children = c.getComponents();
- Dimension compSize = null;
- for (int i = 0; i < children.length; i++) {
- compSize = children[i].getPreferredSize();
- children[i].setSize(compSize.width, compSize.height);
- children[i].setLocation( xInset + insets.left, height);
- height += compSize.height + yGap;
- }
+ Component[] children = c.getComponents();
+ Dimension compSize = null;
+ for (Component child : children) {
+ compSize = child.getPreferredSize();
+ child.setSize(compSize.width, compSize.height);
+ child.setLocation(xInset + insets.left, height);
+ height += compSize.height + yGap;
+ }
- }
+ }
- public Dimension minimumLayoutSize(Container c) {
- Insets insets = c.getInsets();
- int height = yInset + insets.top;
- int width = 0 + insets.left + insets.right;
+ public Dimension minimumLayoutSize(Container c) {
+ Insets insets = c.getInsets();
+ int height = yInset + insets.top;
+ int width = 0 + insets.left + insets.right;
- Component[] children = c.getComponents();
- Dimension compSize = null;
- for (int i = 0; i < children.length; i++) {
- compSize = children[i].getPreferredSize();
- height += compSize.height + yGap;
- width = Math.max(width, compSize.width + insets.left + insets.right + xInset*2);
- }
- height += insets.bottom;
- return new Dimension( width, height);
- }
+ Component[] children = c.getComponents();
+ Dimension compSize = null;
+ for (Component child : children) {
+ compSize = child.getPreferredSize();
+ height += compSize.height + yGap;
+ width = Math.max(width, compSize.width + insets.left + insets.right + xInset
+ * 2);
+ }
+ height += insets.bottom;
+ return new Dimension(width, height);
+ }
- public Dimension preferredLayoutSize(Container c) {
- return minimumLayoutSize(c);
- }
+ public Dimension preferredLayoutSize(Container c) {
+ return minimumLayoutSize(c);
+ }
- public void removeLayoutComponent(Component c) {}
-
+ public void removeLayoutComponent(Component c) {
+ }
}
--- a/jdk/src/share/demo/jfc/Metalworks/PropertiesMetalTheme.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/PropertiesMetalTheme.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,17 +29,15 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-
-import javax.swing.plaf.*;
-import javax.swing.plaf.metal.*;
-import javax.swing.*;
-import javax.swing.border.*;
-import java.awt.*;
-import java.io.*;
-import java.util.*;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+import java.util.StringTokenizer;
+
+import javax.swing.plaf.ColorUIResource;
+import javax.swing.plaf.metal.DefaultMetalTheme;
+
/**
* This class allows you to load a theme from a file.
@@ -57,36 +55,33 @@
* but it could easily be extended to load fonts - or even icons.
*
* @author Steve Wilson
+ * @author Alexander Kouznetsov
*/
public class PropertiesMetalTheme extends DefaultMetalTheme {
private String name = "Custom Theme";
-
private ColorUIResource primary1;
private ColorUIResource primary2;
private ColorUIResource primary3;
-
private ColorUIResource secondary1;
private ColorUIResource secondary2;
private ColorUIResource secondary3;
-
private ColorUIResource black;
private ColorUIResource white;
-
/**
- * pass an inputstream pointing to a properties file.
- * Colors will be initialized to be the same as the DefaultMetalTheme,
- * and then any colors provided in the properties file will override that.
- */
- public PropertiesMetalTheme( InputStream stream ) {
+ * pass an inputstream pointing to a properties file.
+ * Colors will be initialized to be the same as the DefaultMetalTheme,
+ * and then any colors provided in the properties file will override that.
+ */
+ public PropertiesMetalTheme(InputStream stream) {
initColors();
loadProperties(stream);
}
/**
- * Initialize all colors to be the same as the DefaultMetalTheme.
- */
+ * Initialize all colors to be the same as the DefaultMetalTheme.
+ */
private void initColors() {
primary1 = super.getPrimary1();
primary2 = super.getPrimary2();
@@ -101,9 +96,9 @@
}
/**
- * Load the theme name and colors from the properties file
- * Items not defined in the properties file are ignored
- */
+ * Load the theme name and colors from the properties file
+ * Items not defined in the properties file are ignored
+ */
private void loadProperties(InputStream stream) {
Properties prop = new Properties();
try {
@@ -120,7 +115,7 @@
Object colorString = null;
colorString = prop.get("primary1");
- if (colorString != null){
+ if (colorString != null) {
primary1 = parseColor(colorString.toString());
}
@@ -161,22 +156,54 @@
}
- public String getName() { return name; }
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ protected ColorUIResource getPrimary1() {
+ return primary1;
+ }
- protected ColorUIResource getPrimary1() { return primary1; }
- protected ColorUIResource getPrimary2() { return primary2; }
- protected ColorUIResource getPrimary3() { return primary3; }
+ @Override
+ protected ColorUIResource getPrimary2() {
+ return primary2;
+ }
+
+ @Override
+ protected ColorUIResource getPrimary3() {
+ return primary3;
+ }
- protected ColorUIResource getSecondary1() { return secondary1; }
- protected ColorUIResource getSecondary2() { return secondary2; }
- protected ColorUIResource getSecondary3() { return secondary3; }
+ @Override
+ protected ColorUIResource getSecondary1() {
+ return secondary1;
+ }
+
+ @Override
+ protected ColorUIResource getSecondary2() {
+ return secondary2;
+ }
- protected ColorUIResource getBlack() { return black; }
- protected ColorUIResource getWhite() { return white; }
+ @Override
+ protected ColorUIResource getSecondary3() {
+ return secondary3;
+ }
+
+ @Override
+ protected ColorUIResource getBlack() {
+ return black;
+ }
+
+ @Override
+ protected ColorUIResource getWhite() {
+ return white;
+ }
/**
- * parse a comma delimited list of 3 strings into a Color
- */
+ * parse a comma delimited list of 3 strings into a Color
+ */
private ColorUIResource parseColor(String s) {
int red = 0;
int green = 0;
--- a/jdk/src/share/demo/jfc/Metalworks/UISwitchListener.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/UISwitchListener.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,22 +29,21 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import java.awt.*;
-import java.beans.*;
-import java.awt.event.*;
-import javax.swing.*;
-import javax.swing.event.*;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import javax.swing.JComponent;
+import javax.swing.SwingUtilities;
/**
- * This class listens for UISwitches, and updates a given component.
- *
- * @author Steve Wilson
- */
+ * This class listens for UISwitches, and updates a given component.
+ *
+ * @author Steve Wilson
+ * @author Alexander Kouznetsov
+ */
public class UISwitchListener implements PropertyChangeListener {
+
JComponent componentToSwitch;
public UISwitchListener(JComponent c) {
--- a/jdk/src/share/demo/jfc/Metalworks/resources/HelpFiles/credits.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/resources/HelpFiles/credits.html Sun Apr 10 10:23:28 2011 -0700
@@ -5,9 +5,9 @@
</HEAD>
<BODY>
-<H1>Java L&F Credits</H1>
+<H1>Java L&F Credits</H1>
-<P>The Java L&F Engineering team:</P>
+<P>The Java L&F Engineering team:</P>
<UL>
<LI>Mike Albers
@@ -22,12 +22,12 @@
<LI>Harry Vertelney
</UL>
-<P>The Java L&F Designer:</P>
+<P>The Java L&F Designer:</P>
<UL>
<LI>Chris Ryan
</UL>
-<P><A HREF="toc.html"><IMG SRC="back.gif" WIDTH="42" HEIGHT="22" ALIGN="BOTTOM" NATURALSIZEFLAG="3" BORDER="0">Back</A>
+<P><A HREF="toc.html"><IMG alt="Back" SRC="back.gif" WIDTH="42" HEIGHT="22" ALIGN="BOTTOM" BORDER="0">Back</A>
</BODY>
</HTML>
--- a/jdk/src/share/demo/jfc/Metalworks/resources/HelpFiles/metal.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/resources/HelpFiles/metal.html Sun Apr 10 10:23:28 2011 -0700
@@ -7,11 +7,11 @@
<BODY>
<H1>
-About the Java L&F</H1>
-The Java Look and Feel is a cross-platform look & feel being provided by Javasoft.
-Here is some information about the Java L&F you might find useful.
+About the Java L&F</H1>
+The Java Look and Feel is a cross-platform look & feel being provided by Javasoft.
+Here is some information about the Java L&F you might find useful.
-<P>The Java L&F implements all of the basic Swing functionality,
+<P>The Java L&F implements all of the basic Swing functionality,
but also extends it in several areas including:
<UL>
<LI>
@@ -27,27 +27,27 @@
Trees</LI>
</UL>
-</P>
+<P/>
<H1>
Themes</H1>
-<P>One of the first things we learned while implementing the Java L&F
+<P>One of the first things we learned while implementing the Java L&F
was than many developers feel very strongly about how colors are used in
their software. To help accommodate this we created a Theme mechanism
which allows a developer to easily specify the default colors, fonts and
-icons used by the L&F.</P>
+icons used by the L&F.</P>
<P>The theme mechanism is designed to allow developers to create
their own themes. For an example of this, see the themes
-which are included with Metalworks. Note, like all of the L&F packages,
+which are included with Metalworks. Note, like all of the L&F packages,
the metal package is not yet frozen and the theme mechanism may change as
we get developer feedback on how to improve it.</P>
<H1>
Sliders</H1>
-<P>There are several areas where the Java L&F introduces some optional
+<P>There are several areas where the Java L&F introduces some optional
"value-added" features above the base line capabilities of swing.
One is the option of Filled Sliders. These are ideal for things like
-volume controls. To access the Java L&F "value-added" features you
+volume controls. To access the Java L&F "value-added" features you
pass in a token to the component's putClientProperty method. Here
is an example:</P>
@@ -60,12 +60,12 @@
<P>Note that if a UI such as Windows or Motif encounters a property such as
JSlider.fill which is does not understand that property will be ignored.
Thus you don't have to worry about problems which could arise if you switch
-to a different L&F.</P>
+to a different L&F.</P>
<H1>
ToolBars</H1>
<P>Many popular applications support "roll-over" effects on buttons in toolbars.
-The Java L&F provides an easy way to do this. Here is a code snippit:</P>
+The Java L&F provides an easy way to do this. Here is a code snippit:</P>
<PRE>
JToolBar toolbar = new JToolBar();<BR>
@@ -82,7 +82,7 @@
<H1>
Trees</H1>
-<P>Java L&F allows you to control the line style used in the JTree component. Here are some code snippits:</P>
+<P>Java L&F allows you to control the line style used in the JTree component. Here are some code snippits:</P>
<PRE>
JTree myTree = new JTree();
@@ -101,6 +101,6 @@
"Horizontal");
</PRE>
-<P><A HREF="toc.html"><IMG SRC="back.gif" BORDER=0 NATURALSIZEFLAG="3" HEIGHT=22 WIDTH=42 ALIGN=BOTTOM>Back</A>
+<P><A HREF="toc.html"><IMG alt="Back" SRC="back.gif" BORDER=0 HEIGHT=22 WIDTH=42 ALIGN=BOTTOM>Back</A>
</BODY>
</HTML>
--- a/jdk/src/share/demo/jfc/Metalworks/resources/HelpFiles/metalworks.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/resources/HelpFiles/metalworks.html Sun Apr 10 10:23:28 2011 -0700
@@ -8,7 +8,7 @@
<H1>
About Metalworks</H1>
-Metalworks is a simple Swing-based simulated email application. It shows off several features of Swing including: JInternalFrame, JTabbedPane, JFileChooser, JEditorPane and JRadioButtonMenuItem. It is optimized to work with the Java Look & Feel and shows use of several Java L&F specific features including themes.
+Metalworks is a simple Swing-based simulated email application. It shows off several features of Swing including: JInternalFrame, JTabbedPane, JFileChooser, JEditorPane and JRadioButtonMenuItem. It is optimized to work with the Java Look & Feel and shows use of several Java L&F specific features including themes.
<H1>
Metalworks Features</H1>
The functionality of the Metalworks demo is minimal, and many controls are non-functional. They are only intended to show how to construct the UI for such interfaces. Things that do work in the Metalworks demo include:
@@ -28,6 +28,6 @@
-<P><A HREF="toc.html"><IMG SRC="back.gif" BORDER=0 NATURALSIZEFLAG="3" HEIGHT=22 WIDTH=42 ALIGN=BOTTOM>Back</A>
+<P><A HREF="toc.html"><IMG alt="Back" SRC="back.gif" BORDER=0 HEIGHT=22 WIDTH=42 ALIGN=BOTTOM>Back</A>
</BODY>
</HTML>
--- a/jdk/src/share/demo/jfc/Metalworks/resources/HelpFiles/swing.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/resources/HelpFiles/swing.html Sun Apr 10 10:23:28 2011 -0700
@@ -5,7 +5,7 @@
</HEAD>
<BODY>
-<H1><IMG SRC="duke.gif" WIDTH="98" HEIGHT="98" ALIGN="MIDDLE" NATURALSIZEFLAG="3">About Swing</H1>
+ <H1><IMG alt="About Swing" SRC="duke.gif" WIDTH="98" HEIGHT="98" ALIGN="MIDDLE">About Swing</H1>
<P> </P>
@@ -17,6 +17,6 @@
without restarting it and without the developer having to subclass the entire
component set.</P>
-<P><A HREF="toc.html"><IMG SRC="back.gif" WIDTH="42" HEIGHT="22" ALIGN="BOTTOM" NATURALSIZEFLAG="3" BORDER="0">Back</A>
+<P><A HREF="toc.html"><IMG alt="Back" SRC="back.gif" WIDTH="42" HEIGHT="22" ALIGN="BOTTOM" BORDER="0">Back</A>
</BODY>
</HTML>
--- a/jdk/src/share/demo/jfc/Metalworks/resources/HelpFiles/toc.html Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Metalworks/resources/HelpFiles/toc.html Sun Apr 10 10:23:28 2011 -0700
@@ -5,7 +5,7 @@
</HEAD>
<BODY>
-<H1><IMG SRC="javalogo.gif" WIDTH="52" HEIGHT="88" ALIGN="MIDDLE" NATURALSIZEFLAG="3">Metalworks Help</H1>
+ <H1><IMG alt="Help" SRC="javalogo.gif" WIDTH="52" HEIGHT="88" ALIGN="MIDDLE">Metalworks Help</H1>
<P>Welcome to the Metalworks Help files. These are actually HTML files which
you are viewing with the Swing JEditorPane component. Pretty cool, eh? Were
@@ -18,7 +18,7 @@
<UL>
<LI><A HREF="metalworks.html">About Metalworks</A>
- <LI><A HREF="metal.html">About Java L&F</A>
+ <LI><A HREF="metal.html">About Java L&F</A>
<LI><A HREF="swing.html">About Swing</A>
<LI><A HREF="credits.html">Credits</A>
</UL>
--- a/jdk/src/share/demo/jfc/Notepad/ElementTreePanel.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Notepad/ElementTreePanel.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2000, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,17 +29,36 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import javax.swing.*;
-import javax.swing.event.*;
-import javax.swing.text.*;
-import javax.swing.tree.*;
-import javax.swing.undo.*;
-import java.awt.*;
-import java.beans.*;
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
import java.util.*;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTree;
+import javax.swing.SwingConstants;
+import javax.swing.event.CaretEvent;
+import javax.swing.event.CaretListener;
+import javax.swing.event.DocumentEvent;
+import javax.swing.event.DocumentListener;
+import javax.swing.event.TreeSelectionEvent;
+import javax.swing.event.TreeSelectionListener;
+import javax.swing.text.AttributeSet;
+import javax.swing.text.Document;
+import javax.swing.text.Element;
+import javax.swing.text.JTextComponent;
+import javax.swing.text.StyleConstants;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.DefaultTreeCellRenderer;
+import javax.swing.tree.DefaultTreeModel;
+import javax.swing.tree.TreeModel;
+import javax.swing.tree.TreeNode;
+import javax.swing.tree.TreePath;
+
/**
* Displays a tree showing all the elements in a text Document. Selecting
@@ -49,16 +68,20 @@
*
* @author Scott Violet
*/
-public class ElementTreePanel extends JPanel implements CaretListener, DocumentListener, PropertyChangeListener, TreeSelectionListener {
+@SuppressWarnings("serial")
+public class ElementTreePanel extends JPanel implements CaretListener,
+ DocumentListener, PropertyChangeListener, TreeSelectionListener {
+
/** Tree showing the documents element structure. */
- protected JTree tree;
+ protected JTree tree;
/** Text component showing elemenst for. */
- protected JTextComponent editor;
+ protected JTextComponent editor;
/** Model for the tree. */
- protected ElementTreeModel treeModel;
+ protected ElementTreeModel treeModel;
/** Set to true when updatin the selection. */
- protected boolean updatingSelection;
+ protected boolean updatingSelection;
+ @SuppressWarnings("LeakingThisInConstructor")
public ElementTreePanel(JTextComponent editor) {
this.editor = editor;
@@ -67,25 +90,28 @@
// Create the tree.
treeModel = new ElementTreeModel(document);
tree = new JTree(treeModel) {
+
+ @Override
public String convertValueToText(Object value, boolean selected,
- boolean expanded, boolean leaf,
- int row, boolean hasFocus) {
+ boolean expanded, boolean leaf,
+ int row, boolean hasFocus) {
// Should only happen for the root
- if(!(value instanceof Element))
+ if (!(value instanceof Element)) {
return value.toString();
+ }
- Element e = (Element)value;
- AttributeSet as = e.getAttributes().copyAttributes();
- String asString;
+ Element e = (Element) value;
+ AttributeSet as = e.getAttributes().copyAttributes();
+ String asString;
- if(as != null) {
- StringBuffer retBuffer = new StringBuffer("[");
- Enumeration names = as.getAttributeNames();
+ if (as != null) {
+ StringBuilder retBuffer = new StringBuilder("[");
+ Enumeration names = as.getAttributeNames();
- while(names.hasMoreElements()) {
- Object nextName = names.nextElement();
+ while (names.hasMoreElements()) {
+ Object nextName = names.nextElement();
- if(nextName != StyleConstants.ResolveAttribute) {
+ if (nextName != StyleConstants.ResolveAttribute) {
retBuffer.append(" ");
retBuffer.append(nextName);
retBuffer.append("=");
@@ -94,16 +120,16 @@
}
retBuffer.append(" ]");
asString = retBuffer.toString();
+ } else {
+ asString = "[ ]";
}
- else
- asString = "[ ]";
- if(e.isLeaf())
- return e.getName() + " [" + e.getStartOffset() +
- ", " + e.getEndOffset() +"] Attributes: " + asString;
- return e.getName() + " [" + e.getStartOffset() +
- ", " + e.getEndOffset() + "] Attributes: " +
- asString;
+ if (e.isLeaf()) {
+ return e.getName() + " [" + e.getStartOffset() + ", " + e.
+ getEndOffset() + "] Attributes: " + asString;
+ }
+ return e.getName() + " [" + e.getStartOffset() + ", " + e.
+ getEndOffset() + "] Attributes: " + asString;
}
};
tree.addTreeSelectionListener(this);
@@ -117,10 +143,13 @@
// This is a temporary workaround, increase the needed size by 15,
// hoping that will be enough.
tree.setCellRenderer(new DefaultTreeCellRenderer() {
+
+ @Override
public Dimension getPreferredSize() {
Dimension retValue = super.getPreferredSize();
- if(retValue != null)
+ if (retValue != null) {
retValue.width += 15;
+ }
return retValue;
}
});
@@ -139,7 +168,8 @@
add(new JScrollPane(tree), BorderLayout.CENTER);
// Add a label above tree to describe what is being shown
- JLabel label = new JLabel("Elements that make up the current document", SwingConstants.CENTER);
+ JLabel label = new JLabel("Elements that make up the current document",
+ SwingConstants.CENTER);
label.setFont(new Font("Dialog", Font.BOLD, 14));
add(label, BorderLayout.NORTH);
@@ -157,7 +187,7 @@
}
if (this.editor != null) {
- Document oldDoc = this.editor.getDocument();
+ Document oldDoc = this.editor.getDocument();
oldDoc.removeDocumentListener(this);
this.editor.removePropertyChangeListener(this);
@@ -167,9 +197,8 @@
if (editor == null) {
treeModel = null;
tree.setModel(null);
- }
- else {
- Document newDoc = editor.getDocument();
+ } else {
+ Document newDoc = editor.getDocument();
newDoc.addDocumentListener(this);
editor.addPropertyChangeListener(this);
@@ -180,17 +209,15 @@
}
// PropertyChangeListener
-
/**
* Invoked when a property changes. We are only interested in when the
* Document changes to reset the DocumentListener.
*/
public void propertyChange(PropertyChangeEvent e) {
- if (e.getSource() == getEditor() &&
- e.getPropertyName().equals("document")) {
- JTextComponent editor = getEditor();
- Document oldDoc = (Document)e.getOldValue();
- Document newDoc = (Document)e.getNewValue();
+ if (e.getSource() == getEditor() && e.getPropertyName().equals(
+ "document")) {
+ Document oldDoc = (Document) e.getOldValue();
+ Document newDoc = (Document) e.getNewValue();
// Reset the DocumentListener
oldDoc.removeDocumentListener(this);
@@ -202,9 +229,7 @@
}
}
-
// DocumentListener
-
/**
* Gives notification that there was an insert into the document. The
* given range bounds the freshly inserted region.
@@ -236,53 +261,50 @@
}
// CaretListener
-
/**
* Messaged when the selection in the editor has changed. Will update
* the selection in the tree.
*/
public void caretUpdate(CaretEvent e) {
- if(!updatingSelection) {
- JTextComponent editor = getEditor();
- int selBegin = Math.min(e.getDot(), e.getMark());
- int end = Math.max(e.getDot(), e.getMark());
- Vector paths = new Vector();
- TreeModel model = getTreeModel();
- Object root = model.getRoot();
- int rootCount = model.getChildCount(root);
+ if (!updatingSelection) {
+ int selBegin = Math.min(e.getDot(), e.getMark());
+ int end = Math.max(e.getDot(), e.getMark());
+ List<TreePath> paths = new ArrayList<TreePath>();
+ TreeModel model = getTreeModel();
+ Object root = model.getRoot();
+ int rootCount = model.getChildCount(root);
// Build an array of all the paths to all the character elements
// in the selection.
- for(int counter = 0; counter < rootCount; counter++) {
- int start = selBegin;
+ for (int counter = 0; counter < rootCount; counter++) {
+ int start = selBegin;
- while(start <= end) {
- TreePath path = getPathForIndex(start, root,
- (Element)model.getChild(root, counter));
- Element charElement = (Element)path.
- getLastPathComponent();
+ while (start <= end) {
+ TreePath path = getPathForIndex(start, root,
+ (Element) model.getChild(root, counter));
+ Element charElement = (Element) path.getLastPathComponent();
- paths.addElement(path);
- if(start >= charElement.getEndOffset())
+ paths.add(path);
+ if (start >= charElement.getEndOffset()) {
start++;
- else
+ } else {
start = charElement.getEndOffset();
+ }
}
}
// If a path was found, select it (them).
- int numPaths = paths.size();
+ int numPaths = paths.size();
- if(numPaths > 0) {
- TreePath[] pathArray = new TreePath[numPaths];
+ if (numPaths > 0) {
+ TreePath[] pathArray = new TreePath[numPaths];
- paths.copyInto(pathArray);
+ paths.toArray(pathArray);
updatingSelection = true;
try {
getTree().setSelectionPaths(pathArray);
getTree().scrollPathToVisible(pathArray[0]);
- }
- finally {
+ } finally {
updatingSelection = false;
}
}
@@ -290,27 +312,24 @@
}
// TreeSelectionListener
-
/**
- * Called whenever the value of the selection changes.
- * @param e the event that characterizes the change.
- */
+ * Called whenever the value of the selection changes.
+ * @param e the event that characterizes the change.
+ */
public void valueChanged(TreeSelectionEvent e) {
- JTree tree = getTree();
- if(!updatingSelection && tree.getSelectionCount() == 1) {
- TreePath selPath = tree.getSelectionPath();
- Object lastPathComponent = selPath.getLastPathComponent();
+ if (!updatingSelection && tree.getSelectionCount() == 1) {
+ TreePath selPath = tree.getSelectionPath();
+ Object lastPathComponent = selPath.getLastPathComponent();
- if(!(lastPathComponent instanceof DefaultMutableTreeNode)) {
- Element selElement = (Element)lastPathComponent;
+ if (!(lastPathComponent instanceof DefaultMutableTreeNode)) {
+ Element selElement = (Element) lastPathComponent;
updatingSelection = true;
try {
getEditor().select(selElement.getStartOffset(),
- selElement.getEndOffset());
- }
- finally {
+ selElement.getEndOffset());
+ } finally {
updatingSelection = false;
}
}
@@ -318,7 +337,6 @@
}
// Local methods
-
/**
* @return tree showing elements.
*/
@@ -347,15 +365,14 @@
protected void updateTree(DocumentEvent event) {
updatingSelection = true;
try {
- TreeModel model = getTreeModel();
- Object root = model.getRoot();
+ TreeModel model = getTreeModel();
+ Object root = model.getRoot();
- for(int counter = model.getChildCount(root) - 1; counter >= 0;
- counter--) {
- updateTree(event, (Element)model.getChild(root, counter));
+ for (int counter = model.getChildCount(root) - 1; counter >= 0;
+ counter--) {
+ updateTree(event, (Element) model.getChild(root, counter));
}
- }
- finally {
+ } finally {
updatingSelection = false;
}
}
@@ -372,53 +389,50 @@
DocumentEvent.ElementChange ec = event.getChange(element);
if (ec != null) {
- Element[] removed = ec.getChildrenRemoved();
- Element[] added = ec.getChildrenAdded();
- int startIndex = ec.getIndex();
+ Element[] removed = ec.getChildrenRemoved();
+ Element[] added = ec.getChildrenAdded();
+ int startIndex = ec.getIndex();
// Check for removed.
- if(removed != null && removed.length > 0) {
- int[] indices = new int[removed.length];
+ if (removed != null && removed.length > 0) {
+ int[] indices = new int[removed.length];
- for(int counter = 0; counter < removed.length; counter++) {
+ for (int counter = 0; counter < removed.length; counter++) {
indices[counter] = startIndex + counter;
}
- getTreeModel().nodesWereRemoved((TreeNode)element, indices,
- removed);
+ getTreeModel().nodesWereRemoved((TreeNode) element, indices,
+ removed);
}
// check for added
- if(added != null && added.length > 0) {
- int[] indices = new int[added.length];
+ if (added != null && added.length > 0) {
+ int[] indices = new int[added.length];
- for(int counter = 0; counter < added.length; counter++) {
+ for (int counter = 0; counter < added.length; counter++) {
indices[counter] = startIndex + counter;
}
- getTreeModel().nodesWereInserted((TreeNode)element, indices);
+ getTreeModel().nodesWereInserted((TreeNode) element, indices);
}
}
- if(!element.isLeaf()) {
- int startIndex = element.getElementIndex
- (event.getOffset());
- int elementCount = element.getElementCount();
- int endIndex = Math.min(elementCount - 1,
- element.getElementIndex
- (event.getOffset() + event.getLength()));
+ if (!element.isLeaf()) {
+ int startIndex = element.getElementIndex(event.getOffset());
+ int elementCount = element.getElementCount();
+ int endIndex = Math.min(elementCount - 1,
+ element.getElementIndex(event.getOffset()
+ + event.getLength()));
- if(startIndex > 0 && startIndex < elementCount &&
- element.getElement(startIndex).getStartOffset() ==
- event.getOffset()) {
+ if (startIndex > 0 && startIndex < elementCount && element.
+ getElement(startIndex).getStartOffset() == event.getOffset()) {
// Force checking the previous element.
startIndex--;
}
- if(startIndex != -1 && endIndex != -1) {
- for(int counter = startIndex; counter <= endIndex; counter++) {
+ if (startIndex != -1 && endIndex != -1) {
+ for (int counter = startIndex; counter <= endIndex; counter++) {
updateTree(event, element.getElement(counter));
}
}
- }
- else {
+ } else {
// Element is a leaf, assume it changed
- getTreeModel().nodeChanged((TreeNode)element);
+ getTreeModel().nodeChanged((TreeNode) element);
}
}
@@ -426,14 +440,14 @@
* Returns a TreePath to the element at <code>position</code>.
*/
protected TreePath getPathForIndex(int position, Object root,
- Element rootElement) {
- TreePath path = new TreePath(root);
- Element child = rootElement.getElement
- (rootElement.getElementIndex(position));
+ Element rootElement) {
+ TreePath path = new TreePath(root);
+ Element child = rootElement.getElement(rootElement.getElementIndex(
+ position));
path = path.pathByAddingChild(rootElement);
path = path.pathByAddingChild(child);
- while(!child.isLeaf()) {
+ while (!child.isLeaf()) {
child = child.getElement(child.getElementIndex(position));
path = path.pathByAddingChild(child);
}
@@ -456,7 +470,8 @@
* methods have been subclassed, primarily to special case the root.
*/
public static class ElementTreeModel extends DefaultTreeModel {
- protected Element[] rootElements;
+
+ protected Element[] rootElements;
public ElementTreeModel(Document document) {
super(new DefaultMutableTreeNode("root"), false);
@@ -474,13 +489,14 @@
* @param parent a node in the tree, obtained from this data source
* @return the child of <I>parent</I> at index <I>index</I>
*/
+ @Override
public Object getChild(Object parent, int index) {
- if(parent == root)
+ if (parent == root) {
return rootElements[index];
+ }
return super.getChild(parent, index);
}
-
/**
* Returns the number of children of <I>parent</I>. Returns 0
* if the node is a leaf or if it has no children.
@@ -490,13 +506,14 @@
* @param parent a node in the tree, obtained from this data source
* @return the number of children of the node <I>parent</I>
*/
+ @Override
public int getChildCount(Object parent) {
- if(parent == root)
+ if (parent == root) {
return rootElements.length;
+ }
return super.getChildCount(parent);
}
-
/**
* Returns true if <I>node</I> is a leaf. It is possible for
* this method to return false even if <I>node</I> has no
@@ -507,21 +524,25 @@
* @param node a node in the tree, obtained from this data source
* @return true if <I>node</I> is a leaf
*/
+ @Override
public boolean isLeaf(Object node) {
- if(node == root)
+ if (node == root) {
return false;
+ }
return super.isLeaf(node);
}
/**
* Returns the index of child in parent.
*/
+ @Override
public int getIndexOfChild(Object parent, Object child) {
- if(parent == root) {
- for(int counter = rootElements.length - 1; counter >= 0;
- counter--) {
- if(rootElements[counter] == child)
+ if (parent == root) {
+ for (int counter = rootElements.length - 1; counter >= 0;
+ counter--) {
+ if (rootElements[counter] == child) {
return counter;
+ }
}
return -1;
}
@@ -532,18 +553,19 @@
* Invoke this method after you've changed how node is to be
* represented in the tree.
*/
+ @Override
public void nodeChanged(TreeNode node) {
- if(listenerList != null && node != null) {
- TreeNode parent = node.getParent();
+ if (listenerList != null && node != null) {
+ TreeNode parent = node.getParent();
- if(parent == null && node != root) {
+ if (parent == null && node != root) {
parent = root;
}
- if(parent != null) {
- int anIndex = getIndexOfChild(parent, node);
+ if (parent != null) {
+ int anIndex = getIndexOfChild(parent, node);
- if(anIndex != -1) {
- int[] cIndexs = new int[1];
+ if (anIndex != -1) {
+ int[] cIndexs = new int[1];
cIndexs[0] = anIndex;
nodesChanged(parent, cIndexs);
@@ -555,26 +577,28 @@
/**
* Returns the path to a particluar node. This is recursive.
*/
+ @Override
protected TreeNode[] getPathToRoot(TreeNode aNode, int depth) {
- TreeNode[] retNodes;
+ TreeNode[] retNodes;
/* Check for null, in case someone passed in a null node, or
- they passed in an element that isn't rooted at root. */
- if(aNode == null) {
- if(depth == 0)
+ they passed in an element that isn't rooted at root. */
+ if (aNode == null) {
+ if (depth == 0) {
return null;
- else
+ } else {
retNodes = new TreeNode[depth];
- }
- else {
+ }
+ } else {
depth++;
- if(aNode == root)
+ if (aNode == root) {
retNodes = new TreeNode[depth];
- else {
+ } else {
TreeNode parent = aNode.getParent();
- if(parent == null)
+ if (parent == null) {
parent = root;
+ }
retNodes = getPathToRoot(parent, depth);
}
retNodes[retNodes.length - depth] = aNode;
--- a/jdk/src/share/demo/jfc/Notepad/Notepad.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/Notepad/Notepad.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,20 +29,73 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import java.awt.*;
-import java.awt.event.*;
-import java.beans.*;
-import java.io.*;
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.FileDialog;
+import java.awt.Font;
+import java.awt.Frame;
+import java.awt.Graphics;
+import java.awt.Insets;
+import java.awt.event.ActionEvent;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.Writer;
import java.net.URL;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.StringTokenizer;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.BorderFactory;
+import javax.swing.Box;
+import javax.swing.BoxLayout;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JComponent;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JMenu;
+import javax.swing.JMenuBar;
+import javax.swing.JMenuItem;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JProgressBar;
+import javax.swing.JScrollPane;
+import javax.swing.JTextArea;
+import javax.swing.JToolBar;
+import javax.swing.JViewport;
+import javax.swing.SwingUtilities;
+import javax.swing.UIManager;
+import javax.swing.UIManager.LookAndFeelInfo;
+import javax.swing.event.UndoableEditEvent;
+import javax.swing.event.UndoableEditListener;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.Document;
+import javax.swing.text.JTextComponent;
+import javax.swing.text.PlainDocument;
+import javax.swing.text.Segment;
+import javax.swing.text.TextAction;
+import javax.swing.undo.CannotRedoException;
+import javax.swing.undo.CannotUndoException;
+import javax.swing.undo.UndoManager;
-import javax.swing.text.*;
-import javax.swing.undo.*;
-import javax.swing.event.*;
-import javax.swing.*;
/**
* Sample application using the simple text editor component that
@@ -50,22 +103,24 @@
*
* @author Timothy Prinzing
*/
+@SuppressWarnings("serial")
class Notepad extends JPanel {
private static ResourceBundle resources;
- private final static String EXIT_AFTER_PAINT = new String("-exit");
+ private final static String EXIT_AFTER_PAINT = "-exit";
private static boolean exitAfterFirstPaint;
static {
try {
resources = ResourceBundle.getBundle("resources.Notepad",
- Locale.getDefault());
+ Locale.getDefault());
} catch (MissingResourceException mre) {
System.err.println("resources/Notepad.properties not found");
System.exit(1);
}
}
+ @Override
public void paintChildren(Graphics g) {
super.paintChildren(g);
if (exitAfterFirstPaint) {
@@ -73,17 +128,19 @@
}
}
+ @SuppressWarnings("OverridableMethodCallInConstructor")
Notepad() {
super(true);
- // Force SwingSet to come up in the Cross Platform L&F
+ // Trying to set Nimbus look and feel
try {
- UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
- // If you want the System L&F instead, comment out the above line and
- // uncomment the following:
- // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
- } catch (Exception exc) {
- System.err.println("Error loading L&F: " + exc);
+ for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
+ if ("Nimbus".equals(info.getName())) {
+ UIManager.setLookAndFeel(info.getClassName());
+ break;
+ }
+ }
+ } catch (Exception ignored) {
}
setBorder(BorderFactory.createEtchedBorder());
@@ -95,7 +152,7 @@
editor.getDocument().addUndoableEditListener(undoHandler);
// install the command table
- commands = new Hashtable();
+ commands = new HashMap<Object, Action>();
Action[] actions = getActions();
for (int i = 0; i < actions.length; i++) {
Action a = actions[i];
@@ -109,15 +166,17 @@
try {
String vpFlag = resources.getString("ViewportBackingStore");
Boolean bs = Boolean.valueOf(vpFlag);
- port.setBackingStoreEnabled(bs.booleanValue());
- } catch (MissingResourceException mre) {
+ port.setScrollMode(bs.booleanValue()
+ ? JViewport.BACKINGSTORE_SCROLL_MODE
+ : JViewport.BLIT_SCROLL_MODE);
+ } catch (MissingResourceException ignored) {
// just use the viewport default
}
- menuItems = new Hashtable();
+ menuItems = new HashMap<String, JMenuItem>();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
- panel.add("North",createToolbar());
+ panel.add("North", createToolbar());
panel.add("Center", scroller);
add("Center", panel);
add("South", createStatusbar());
@@ -125,28 +184,28 @@
public static void main(String[] args) {
try {
- String vers = System.getProperty("java.version");
- if (vers.compareTo("1.1.2") < 0) {
- System.out.println("!!!WARNING: Swing must be run with a " +
- "1.1.2 or higher version VM!!!");
- }
- if (args.length > 0 && args[0].equals(EXIT_AFTER_PAINT)) {
- exitAfterFirstPaint = true;
- }
- JFrame frame = new JFrame();
- frame.setTitle(resources.getString("Title"));
- frame.setBackground(Color.lightGray);
- frame.getContentPane().setLayout(new BorderLayout());
- Notepad notepad = new Notepad();
- frame.getContentPane().add("Center", notepad);
- frame.setJMenuBar(notepad.createMenubar());
- frame.addWindowListener(new AppCloser());
- frame.pack();
- frame.setSize(500, 600);
- frame.show();
+ if (args.length > 0 && args[0].equals(EXIT_AFTER_PAINT)) {
+ exitAfterFirstPaint = true;
+ }
+ SwingUtilities.invokeAndWait(new Runnable() {
+
+ public void run() {
+ JFrame frame = new JFrame();
+ frame.setTitle(resources.getString("Title"));
+ frame.setBackground(Color.lightGray);
+ frame.getContentPane().setLayout(new BorderLayout());
+ Notepad notepad = new Notepad();
+ frame.getContentPane().add("Center", notepad);
+ frame.setJMenuBar(notepad.createMenubar());
+ frame.addWindowListener(new AppCloser());
+ frame.pack();
+ frame.setSize(500, 600);
+ frame.setVisible(true);
+ }
+ });
} catch (Throwable t) {
- System.out.println("uncaught exception: " + t);
- t.printStackTrace();
+ Logger.getLogger(Notepad.class.getName()).log(Level.SEVERE,
+ "uncaught exception", t);
}
}
@@ -177,6 +236,7 @@
return editor;
}
+
/**
* To shutdown when run as an application. This is a
* fairly lame implementation. A more self-respecting
@@ -184,6 +244,8 @@
* was needed.
*/
protected static final class AppCloser extends WindowAdapter {
+
+ @Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
@@ -239,11 +301,11 @@
* if one wasn't created.
*/
protected JMenuItem getMenuItem(String cmd) {
- return (JMenuItem) menuItems.get(cmd);
+ return menuItems.get(cmd);
}
protected Action getAction(String cmd) {
- return (Action) commands.get(cmd);
+ return commands.get(cmd);
}
protected String getResourceString(String nm) {
@@ -328,10 +390,14 @@
protected JButton createToolbarButton(String key) {
URL url = getResource(key + imageSuffix);
JButton b = new JButton(new ImageIcon(url)) {
- public float getAlignmentY() { return 0.5f; }
+
+ @Override
+ public float getAlignmentY() {
+ return 0.5f;
+ }
};
b.setRequestFocusEnabled(false);
- b.setMargin(new Insets(1,1,1,1));
+ b.setMargin(new Insets(1, 1, 1, 1));
String astr = getResourceString(key + actionSuffix);
if (astr == null) {
@@ -360,15 +426,17 @@
* resource file.
*/
protected String[] tokenize(String input) {
- Vector v = new Vector();
+ List<String> v = new ArrayList<String>();
StringTokenizer t = new StringTokenizer(input);
String cmd[];
- while (t.hasMoreTokens())
- v.addElement(t.nextToken());
+ while (t.hasMoreTokens()) {
+ v.add(t.nextToken());
+ }
cmd = new String[v.size()];
- for (int i = 0; i < cmd.length; i++)
- cmd[i] = (String) v.elementAt(i);
+ for (int i = 0; i < cmd.length; i++) {
+ cmd[i] = v.get(i);
+ }
return cmd;
}
@@ -416,13 +484,16 @@
}
// Yarked from JMenu, ideally this would be public.
+
private class ActionChangedListener implements PropertyChangeListener {
+
JMenuItem menuItem;
ActionChangedListener(JMenuItem mi) {
super();
this.menuItem = mi;
}
+
public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
if (e.getPropertyName().equals(Action.NAME)) {
@@ -434,56 +505,48 @@
}
}
}
-
private JTextComponent editor;
- private Hashtable commands;
- private Hashtable menuItems;
+ private Map<Object, Action> commands;
+ private Map<String, JMenuItem> menuItems;
private JMenuBar menubar;
private JToolBar toolbar;
private JComponent status;
private JFrame elementTreeFrame;
protected ElementTreePanel elementTreePanel;
-
protected FileDialog fileDialog;
-
/**
* Listener for the edits on the current document.
*/
protected UndoableEditListener undoHandler = new UndoHandler();
-
/** UndoManager that we add edits to. */
protected UndoManager undo = new UndoManager();
-
/**
* Suffix applied to the key used in resource file
* lookups for an image.
*/
public static final String imageSuffix = "Image";
-
/**
* Suffix applied to the key used in resource file
* lookups for a label.
*/
public static final String labelSuffix = "Label";
-
/**
* Suffix applied to the key used in resource file
* lookups for an action.
*/
public static final String actionSuffix = "Action";
-
/**
* Suffix applied to the key used in resource file
* lookups for tooltip text.
*/
public static final String tipSuffix = "Tooltip";
-
public static final String openAction = "open";
- public static final String newAction = "new";
+ public static final String newAction = "new";
public static final String saveAction = "save";
public static final String exitAction = "exit";
public static final String showElementTreeAction = "showElementTree";
+
class UndoHandler implements UndoableEditListener {
/**
@@ -497,6 +560,7 @@
}
}
+
/**
* FIXME - I'm not very useful yet
*/
@@ -507,17 +571,14 @@
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
}
+ @Override
public void paint(Graphics g) {
super.paint(g);
}
-
}
-
// --- action implementations -----------------------------------
-
private UndoAction undoAction = new UndoAction();
private RedoAction redoAction = new RedoAction();
-
/**
* Actions defined by the Notepad class
*/
@@ -531,7 +592,9 @@
redoAction
};
+
class UndoAction extends AbstractAction {
+
public UndoAction() {
super("Undo");
setEnabled(false);
@@ -541,26 +604,27 @@
try {
undo.undo();
} catch (CannotUndoException ex) {
- System.out.println("Unable to undo: " + ex);
- ex.printStackTrace();
+ Logger.getLogger(UndoAction.class.getName()).log(Level.SEVERE,
+ "Unable to undo", ex);
}
update();
redoAction.update();
}
protected void update() {
- if(undo.canUndo()) {
+ if (undo.canUndo()) {
setEnabled(true);
putValue(Action.NAME, undo.getUndoPresentationName());
- }
- else {
+ } else {
setEnabled(false);
putValue(Action.NAME, "Undo");
}
}
}
+
class RedoAction extends AbstractAction {
+
public RedoAction() {
super("Redo");
setEnabled(false);
@@ -570,31 +634,32 @@
try {
undo.redo();
} catch (CannotRedoException ex) {
- System.out.println("Unable to redo: " + ex);
- ex.printStackTrace();
+ Logger.getLogger(RedoAction.class.getName()).log(Level.SEVERE,
+ "Unable to redo", ex);
}
update();
undoAction.update();
}
protected void update() {
- if(undo.canRedo()) {
+ if (undo.canRedo()) {
setEnabled(true);
putValue(Action.NAME, undo.getRedoPresentationName());
- }
- else {
+ } else {
setEnabled(false);
putValue(Action.NAME, "Redo");
}
}
}
+
class OpenAction extends NewAction {
OpenAction() {
super(openAction);
}
+ @Override
public void actionPerformed(ActionEvent e) {
Frame frame = getFrame();
JFileChooser chooser = new JFileChooser();
@@ -607,8 +672,9 @@
File f = chooser.getSelectedFile();
if (f.isFile() && f.canRead()) {
Document oldDoc = getEditor().getDocument();
- if(oldDoc != null)
+ if (oldDoc != null) {
oldDoc.removeUndoableEditListener(undoHandler);
+ }
if (elementTreePanel != null) {
elementTreePanel.setEditor(null);
}
@@ -625,6 +691,7 @@
}
}
+
class SaveAction extends AbstractAction {
SaveAction() {
@@ -647,6 +714,7 @@
}
}
+
class NewAction extends AbstractAction {
NewAction() {
@@ -659,8 +727,9 @@
public void actionPerformed(ActionEvent e) {
Document oldDoc = getEditor().getDocument();
- if(oldDoc != null)
+ if (oldDoc != null) {
oldDoc.removeUndoableEditListener(undoHandler);
+ }
getEditor().setDocument(new PlainDocument());
getEditor().getDocument().addUndoableEditListener(undoHandler);
resetUndoManager();
@@ -669,6 +738,7 @@
}
}
+
/**
* Really lame implementation of an exit command
*/
@@ -683,6 +753,7 @@
}
}
+
/**
* Action that brings up a JFrame with a JTree showing the structure
* of the document.
@@ -698,18 +769,19 @@
}
public void actionPerformed(ActionEvent e) {
- if(elementTreeFrame == null) {
+ if (elementTreeFrame == null) {
// Create a frame containing an instance of
// ElementTreePanel.
try {
- String title = resources.getString
- ("ElementTreeFrameTitle");
+ String title = resources.getString("ElementTreeFrameTitle");
elementTreeFrame = new JFrame(title);
} catch (MissingResourceException mre) {
elementTreeFrame = new JFrame();
}
elementTreeFrame.addWindowListener(new WindowAdapter() {
+
+ @Override
public void windowClosing(WindowEvent weeee) {
elementTreeFrame.setVisible(false);
}
@@ -721,10 +793,11 @@
fContentPane.add(elementTreePanel);
elementTreeFrame.pack();
}
- elementTreeFrame.show();
+ elementTreeFrame.setVisible(true);
}
}
+
/**
* Thread to load a file into the text storage model
*/
@@ -736,6 +809,7 @@
this.doc = doc;
}
+ @Override
public void run() {
try {
// initialize the statusbar
@@ -751,22 +825,22 @@
char[] buff = new char[4096];
int nch;
while ((nch = in.read(buff, 0, buff.length)) != -1) {
- doc.insertString(doc.getLength(), new String(buff, 0, nch), null);
+ doc.insertString(doc.getLength(), new String(buff, 0, nch),
+ null);
progress.setValue(progress.getValue() + nch);
}
- }
- catch (IOException e) {
+ } catch (IOException e) {
final String msg = e.getMessage();
SwingUtilities.invokeLater(new Runnable() {
+
public void run() {
JOptionPane.showMessageDialog(getFrame(),
"Could not open file: " + msg,
"Error opening file",
JOptionPane.ERROR_MESSAGE);
- }
+ }
});
- }
- catch (BadLocationException e) {
+ } catch (BadLocationException e) {
System.err.println(e.getMessage());
}
doc.addUndoableEditListener(undoHandler);
@@ -778,21 +852,23 @@
if (elementTreePanel != null) {
SwingUtilities.invokeLater(new Runnable() {
+
public void run() {
elementTreePanel.setEditor(getEditor());
}
});
}
}
-
Document doc;
File f;
}
+
/**
* Thread to save a document to file
*/
class FileSaver extends Thread {
+
Document doc;
File f;
@@ -802,13 +878,15 @@
this.doc = doc;
}
+ @Override
+ @SuppressWarnings("SleepWhileHoldingLock")
public void run() {
try {
// initialize the statusbar
status.removeAll();
JProgressBar progress = new JProgressBar();
progress.setMinimum(0);
- progress.setMaximum((int) doc.getLength());
+ progress.setMaximum(doc.getLength());
status.add(progress);
status.revalidate();
@@ -827,24 +905,25 @@
try {
Thread.sleep(10);
} catch (InterruptedException e) {
- e.printStackTrace();
+ Logger.getLogger(FileSaver.class.getName()).log(
+ Level.SEVERE,
+ null, e);
}
}
out.flush();
out.close();
- }
- catch (IOException e) {
+ } catch (IOException e) {
final String msg = e.getMessage();
SwingUtilities.invokeLater(new Runnable() {
+
public void run() {
JOptionPane.showMessageDialog(getFrame(),
"Could not save file: " + msg,
"Error saving file",
JOptionPane.ERROR_MESSAGE);
- }
+ }
});
- }
- catch (BadLocationException e) {
+ } catch (BadLocationException e) {
System.err.println(e.getMessage());
}
// we are done... get rid of progressbar
--- a/jdk/src/share/demo/jfc/SampleTree/DynamicTreeNode.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/SampleTree/DynamicTreeNode.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,154 +29,154 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.Color;
import java.awt.Font;
-import java.awt.Toolkit;
+import java.awt.GraphicsEnvironment;
import java.util.Random;
+import javax.swing.tree.DefaultMutableTreeNode;
+
/**
- * DynamicTreeNode illustrates one of the possible ways in which dynamic
- * loading can be used in tree. The basic premise behind this is that
- * getChildCount() will be messaged from JTreeModel before any children
- * are asked for. So, the first time getChildCount() is issued the
- * children are loaded.<p>
- * It should be noted that isLeaf will also be messaged from the model.
- * The default behavior of TreeNode is to message getChildCount to
- * determine this. As such, isLeaf is subclassed to always return false.<p>
- * There are others ways this could be accomplished as well. Instead of
- * subclassing TreeNode you could subclass JTreeModel and do the same
- * thing in getChildCount(). Or, if you aren't using TreeNode you could
- * write your own TreeModel implementation.
- * Another solution would be to listen for TreeNodeExpansion events and
- * the first time a node has been expanded post the appropriate insertion
- * events. I would not recommend this approach though, the other two
- * are much simpler and cleaner (and are faster from the perspective of
- * how tree deals with it).
- *
- * NOTE: getAllowsChildren() can be messaged before getChildCount().
- * For this example the nodes always allow children, so it isn't
- * a problem, but if you do support true leaf nodes you may want
- * to check for loading in getAllowsChildren too.
- *
- * @author Scott Violet
- */
+ * DynamicTreeNode illustrates one of the possible ways in which dynamic
+ * loading can be used in tree. The basic premise behind this is that
+ * getChildCount() will be messaged from JTreeModel before any children
+ * are asked for. So, the first time getChildCount() is issued the
+ * children are loaded.<p>
+ * It should be noted that isLeaf will also be messaged from the model.
+ * The default behavior of TreeNode is to message getChildCount to
+ * determine this. As such, isLeaf is subclassed to always return false.<p>
+ * There are others ways this could be accomplished as well. Instead of
+ * subclassing TreeNode you could subclass JTreeModel and do the same
+ * thing in getChildCount(). Or, if you aren't using TreeNode you could
+ * write your own TreeModel implementation.
+ * Another solution would be to listen for TreeNodeExpansion events and
+ * the first time a node has been expanded post the appropriate insertion
+ * events. I would not recommend this approach though, the other two
+ * are much simpler and cleaner (and are faster from the perspective of
+ * how tree deals with it).
+ *
+ * NOTE: getAllowsChildren() can be messaged before getChildCount().
+ * For this example the nodes always allow children, so it isn't
+ * a problem, but if you do support true leaf nodes you may want
+ * to check for loading in getAllowsChildren too.
+ *
+ * @author Scott Violet
+ */
+@SuppressWarnings("serial")
+public class DynamicTreeNode extends DefaultMutableTreeNode {
+ // Class stuff.
-public class DynamicTreeNode extends DefaultMutableTreeNode
-{
- // Class stuff.
/** Number of names. */
- static protected float nameCount;
-
+ protected static float nameCount;
/** Names to use for children. */
- static protected String[] names;
-
+ protected static final String[] NAMES;
/** Potential fonts used to draw with. */
- static protected Font[] fonts;
-
+ protected static Font[] fonts;
/** Used to generate the names. */
- static protected Random nameGen;
-
+ protected static Random nameGen;
/** Number of children to create for each node. */
- static protected final int DefaultChildrenCount = 7;
+ protected static final int DEFAULT_CHILDREN_COUNT = 7;
static {
- String[] fontNames;
+ String[] fontNames;
try {
- fontNames = Toolkit.getDefaultToolkit().getFontList();
+ fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment().
+ getAvailableFontFamilyNames();
+
} catch (Exception e) {
fontNames = null;
}
- if(fontNames == null || fontNames.length == 0) {
- names = new String[] {"Mark Andrews", "Tom Ball", "Alan Chung",
- "Rob Davis", "Jeff Dinkins",
- "Amy Fowler", "James Gosling",
- "David Karlton", "Dave Kloba",
- "Dave Moore", "Hans Muller",
- "Rick Levenson", "Tim Prinzing",
- "Chester Rose", "Ray Ryan",
- "Georges Saab", "Scott Violet",
- "Kathy Walrath", "Arnaud Weber" };
- }
- else {
+ if (fontNames == null || fontNames.length == 0) {
+ NAMES = new String[] { "Mark Andrews", "Tom Ball", "Alan Chung",
+ "Rob Davis", "Jeff Dinkins",
+ "Amy Fowler", "James Gosling",
+ "David Karlton", "Dave Kloba",
+ "Dave Moore", "Hans Muller",
+ "Rick Levenson", "Tim Prinzing",
+ "Chester Rose", "Ray Ryan",
+ "Georges Saab", "Scott Violet",
+ "Kathy Walrath", "Arnaud Weber" };
+ } else {
/* Create the Fonts, creating fonts is slow, much better to
- do it once. */
- int fontSize = 12;
+ do it once. */
+ int fontSize = 12;
- names = fontNames;
- fonts = new Font[names.length];
- for(int counter = 0, maxCounter = names.length;
- counter < maxCounter; counter++) {
+ NAMES = fontNames;
+ fonts = new Font[NAMES.length];
+ for (int counter = 0, maxCounter = NAMES.length;
+ counter < maxCounter; counter++) {
try {
fonts[counter] = new Font(fontNames[counter], 0, fontSize);
- }
- catch (Exception e) {
+ } catch (Exception e) {
fonts[counter] = null;
}
fontSize = ((fontSize + 2 - 12) % 12) + 12;
}
}
- nameCount = (float)names.length;
+ nameCount = (float) NAMES.length;
nameGen = new Random(System.currentTimeMillis());
}
-
-
/** Have the children of this node been loaded yet? */
- protected boolean hasLoaded;
+ protected boolean hasLoaded;
/**
- * Constructs a new DynamicTreeNode instance with o as the user
- * object.
- */
+ * Constructs a new DynamicTreeNode instance with o as the user
+ * object.
+ */
public DynamicTreeNode(Object o) {
super(o);
}
+ @Override
public boolean isLeaf() {
return false;
}
/**
- * If hasLoaded is false, meaning the children have not yet been
- * loaded, loadChildren is messaged and super is messaged for
- * the return value.
- */
+ * If hasLoaded is false, meaning the children have not yet been
+ * loaded, loadChildren is messaged and super is messaged for
+ * the return value.
+ */
+ @Override
public int getChildCount() {
- if(!hasLoaded) {
+ if (!hasLoaded) {
loadChildren();
}
return super.getChildCount();
}
/**
- * Messaged the first time getChildCount is messaged. Creates
- * children with random names from names.
- */
+ * Messaged the first time getChildCount is messaged. Creates
+ * children with random names from names.
+ */
protected void loadChildren() {
- DynamicTreeNode newNode;
- Font font;
- int randomIndex;
- SampleData data;
+ DynamicTreeNode newNode;
+ Font font;
+ int randomIndex;
+ SampleData data;
- for(int counter = 0; counter < DynamicTreeNode.DefaultChildrenCount;
- counter++) {
- randomIndex = (int)(nameGen.nextFloat() * nameCount);
- if(fonts != null)
+ for (int counter = 0; counter < DynamicTreeNode.DEFAULT_CHILDREN_COUNT;
+ counter++) {
+ randomIndex = (int) (nameGen.nextFloat() * nameCount);
+ String displayString = NAMES[randomIndex];
+ if (fonts == null || fonts[randomIndex].canDisplayUpTo(displayString)
+ != -1) {
+ font = null;
+ } else {
font = fonts[randomIndex];
- else
- font = null;
- if(counter % 2 == 0)
- data = new SampleData(font, Color.red, names[randomIndex]);
- else
- data = new SampleData(font, Color.blue, names[randomIndex]);
+ }
+
+ if (counter % 2 == 0) {
+ data = new SampleData(font, Color.red, displayString);
+ } else {
+ data = new SampleData(font, Color.blue, displayString);
+ }
newNode = new DynamicTreeNode(data);
/* Don't use add() here, add calls insert(newNode, getChildCount())
- so if you want to use add, just be sure to set hasLoaded = true
- first. */
+ so if you want to use add, just be sure to set hasLoaded = true
+ first. */
insert(newNode, counter);
}
/* This node has now been loaded, mark it so. */
--- a/jdk/src/share/demo/jfc/SampleTree/SampleData.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/SampleTree/SampleData.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,32 +29,27 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
import java.awt.Color;
import java.awt.Font;
+
/**
- * @author Scott Violet
- */
+ * @author Scott Violet
+ */
+public class SampleData extends Object {
-public class SampleData extends Object
-{
/** Font used for drawing. */
- protected Font font;
-
+ protected Font font;
/** Color used for text. */
- protected Color color;
-
+ protected Color color;
/** Value to display. */
- protected String string;
-
+ protected String string;
/**
- * Constructs a new instance of SampleData with the passed in
- * arguments.
- */
+ * Constructs a new instance of SampleData with the passed in
+ * arguments.
+ */
public SampleData(Font newFont, Color newColor, String newString) {
font = newFont;
color = newColor;
@@ -62,47 +57,48 @@
}
/**
- * Sets the font that is used to represent this object.
- */
+ * Sets the font that is used to represent this object.
+ */
public void setFont(Font newFont) {
font = newFont;
}
/**
- * Returns the Font used to represent this object.
- */
+ * Returns the Font used to represent this object.
+ */
public Font getFont() {
return font;
}
/**
- * Sets the color used to draw the text.
- */
+ * Sets the color used to draw the text.
+ */
public void setColor(Color newColor) {
color = newColor;
}
/**
- * Returns the color used to draw the text.
- */
+ * Returns the color used to draw the text.
+ */
public Color getColor() {
return color;
}
/**
- * Sets the string to display for this object.
- */
+ * Sets the string to display for this object.
+ */
public void setString(String newString) {
string = newString;
}
/**
- * Returnes the string to display for this object.
- */
+ * Returnes the string to display for this object.
+ */
public String string() {
return string;
}
+ @Override
public String toString() {
return string;
}
--- a/jdk/src/share/demo/jfc/SampleTree/SampleTree.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/SampleTree/SampleTree.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,9 +29,10 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
+import java.lang.reflect.InvocationTargetException;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.BorderLayout;
@@ -40,58 +41,57 @@
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
-import java.awt.event.WindowAdapter;
-import java.awt.event.WindowEvent;
import java.util.*;
+import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.*;
import javax.swing.tree.*;
+
/**
- * A demo for illustrating how to do different things with JTree.
- * The data that this displays is rather boring, that is each node will
- * have 7 children that have random names based on the fonts. Each node
- * is then drawn with that font and in a different color.
- * While the data isn't interesting the example illustrates a number
- * of things:
- *
- * For an example of dynamicaly loading children refer to DynamicTreeNode.
- * For an example of adding/removing/inserting/reloading refer to the inner
- * classes of this class, AddAction, RemovAction, InsertAction and
- * ReloadAction.
- * For an example of creating your own cell renderer refer to
- * SampleTreeCellRenderer.
- * For an example of subclassing JTreeModel for editing refer to
- * SampleTreeModel.
- *
- * @author Scott Violet
- */
+ * A demo for illustrating how to do different things with JTree.
+ * The data that this displays is rather boring, that is each node will
+ * have 7 children that have random names based on the fonts. Each node
+ * is then drawn with that font and in a different color.
+ * While the data isn't interesting the example illustrates a number
+ * of things:
+ *
+ * For an example of dynamicaly loading children refer to DynamicTreeNode.
+ * For an example of adding/removing/inserting/reloading refer to the inner
+ * classes of this class, AddAction, RemovAction, InsertAction and
+ * ReloadAction.
+ * For an example of creating your own cell renderer refer to
+ * SampleTreeCellRenderer.
+ * For an example of subclassing JTreeModel for editing refer to
+ * SampleTreeModel.
+ *
+ * @author Scott Violet
+ */
+public final class SampleTree {
-public class SampleTree
-{
/** Window for showing Tree. */
- protected JFrame frame;
+ protected JFrame frame;
/** Tree used for the example. */
- protected JTree tree;
+ protected JTree tree;
/** Tree model. */
- protected DefaultTreeModel treeModel;
+ protected DefaultTreeModel treeModel;
/**
- * Constructs a new instance of SampleTree.
- */
+ * Constructs a new instance of SampleTree.
+ */
public SampleTree() {
- // Force SampleTree to come up in the Cross Platform L&F
+ // Trying to set Nimbus look and feel
try {
- UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
- // If you want the System L&F instead, comment out the above line and
- // uncomment the following:
- // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
- } catch (Exception exc) {
- System.err.println("Error loading L&F: " + exc);
+ for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
+ if ("Nimbus".equals(info.getName())) {
+ UIManager.setLookAndFeel(info.getClassName());
+ break;
+ }
+ }
+ } catch (Exception ignored) {
}
-
- JMenuBar menuBar = constructMenuBar();
- JPanel panel = new JPanel(true);
+ JMenuBar menuBar = constructMenuBar();
+ JPanel panel = new JPanel(true);
frame = new JFrame("SampleTree");
frame.getContentPane().add("Center", panel);
@@ -106,18 +106,18 @@
tree = new JTree(treeModel);
/* Enable tool tips for the tree, without this tool tips will not
- be picked up. */
+ be picked up. */
ToolTipManager.sharedInstance().registerComponent(tree);
/* Make the tree use an instance of SampleTreeCellRenderer for
- drawing. */
+ drawing. */
tree.setCellRenderer(new SampleTreeCellRenderer());
/* Make tree ask for the height of each row. */
tree.setRowHeight(-1);
/* Put the Tree in a scroller. */
- JScrollPane sp = new JScrollPane();
+ JScrollPane sp = new JScrollPane();
sp.setPreferredSize(new Dimension(300, 300));
sp.getViewport().add(tree);
@@ -126,19 +126,18 @@
panel.add("Center", sp);
panel.add("South", constructOptionsPanel());
- frame.addWindowListener( new WindowAdapter() {
- public void windowClosing(WindowEvent e) {System.exit(0);}});
-
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
- frame.show();
+ frame.setVisible(true);
}
/** Constructs a JPanel containing check boxes for the different
- * options that tree supports. */
+ * options that tree supports. */
+ @SuppressWarnings("serial")
private JPanel constructOptionsPanel() {
- JCheckBox aCheckbox;
- JPanel retPanel = new JPanel(false);
- JPanel borderPane = new JPanel(false);
+ JCheckBox aCheckbox;
+ JPanel retPanel = new JPanel(false);
+ JPanel borderPane = new JPanel(false);
borderPane.setLayout(new BorderLayout());
retPanel.setLayout(new FlowLayout());
@@ -162,39 +161,54 @@
borderPane.add(retPanel, BorderLayout.CENTER);
/* Create a set of radio buttons that dictate what selection should
- be allowed in the tree. */
- ButtonGroup group = new ButtonGroup();
- JPanel buttonPane = new JPanel(false);
- JRadioButton button;
+ be allowed in the tree. */
+ ButtonGroup group = new ButtonGroup();
+ JPanel buttonPane = new JPanel(false);
+ JRadioButton button;
buttonPane.setLayout(new FlowLayout());
buttonPane.setBorder(new TitledBorder("Selection Mode"));
button = new JRadioButton("Single");
button.addActionListener(new AbstractAction() {
- public boolean isEnabled() { return true; }
+
+ @Override
+ public boolean isEnabled() {
+ return true;
+ }
+
public void actionPerformed(ActionEvent e) {
- tree.getSelectionModel().setSelectionMode
- (TreeSelectionModel.SINGLE_TREE_SELECTION);
+ tree.getSelectionModel().setSelectionMode(
+ TreeSelectionModel.SINGLE_TREE_SELECTION);
}
});
group.add(button);
buttonPane.add(button);
button = new JRadioButton("Contiguous");
button.addActionListener(new AbstractAction() {
- public boolean isEnabled() { return true; }
+
+ @Override
+ public boolean isEnabled() {
+ return true;
+ }
+
public void actionPerformed(ActionEvent e) {
- tree.getSelectionModel().setSelectionMode
- (TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
+ tree.getSelectionModel().setSelectionMode(
+ TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
}
});
group.add(button);
buttonPane.add(button);
button = new JRadioButton("Discontiguous");
button.addActionListener(new AbstractAction() {
- public boolean isEnabled() { return true; }
+
+ @Override
+ public boolean isEnabled() {
+ return true;
+ }
+
public void actionPerformed(ActionEvent e) {
- tree.getSelectionModel().setSelectionMode
- (TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
+ tree.getSelectionModel().setSelectionMode(
+ TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
}
});
button.setSelected(true);
@@ -209,33 +223,33 @@
/*
JPanel clickPanel = new JPanel();
Object[] values = { "Never", new Integer(1),
- new Integer(2), new Integer(3) };
+ new Integer(2), new Integer(3) };
final JComboBox clickCBox = new JComboBox(values);
clickPanel.setLayout(new FlowLayout());
clickPanel.add(new JLabel("Click count to expand:"));
clickCBox.setSelectedIndex(2);
clickCBox.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent ae) {
- Object selItem = clickCBox.getSelectedItem();
+ public void actionPerformed(ActionEvent ae) {
+ Object selItem = clickCBox.getSelectedItem();
- if(selItem instanceof Integer)
- tree.setToggleClickCount(((Integer)selItem).intValue());
- else // Don't toggle
- tree.setToggleClickCount(0);
- }
+ if(selItem instanceof Integer)
+ tree.setToggleClickCount(((Integer)selItem).intValue());
+ else // Don't toggle
+ tree.setToggleClickCount(0);
+ }
});
clickPanel.add(clickCBox);
borderPane.add(clickPanel, BorderLayout.NORTH);
-*/
+ */
return borderPane;
}
/** Construct a menu. */
private JMenuBar constructMenuBar() {
- JMenu menu;
- JMenuBar menuBar = new JMenuBar();
- JMenuItem menuItem;
+ JMenu menu;
+ JMenuBar menuBar = new JMenuBar();
+ JMenuItem menuItem;
/* Good ol exit. */
menu = new JMenu("File");
@@ -243,9 +257,11 @@
menuItem = menu.add(new JMenuItem("Exit"));
menuItem.addActionListener(new ActionListener() {
+
public void actionPerformed(ActionEvent e) {
System.exit(0);
- }});
+ }
+ });
/* Tree related stuff. */
menu = new JMenu("Tree");
@@ -267,14 +283,15 @@
}
/**
- * Returns the TreeNode instance that is selected in the tree.
- * If nothing is selected, null is returned.
- */
+ * Returns the TreeNode instance that is selected in the tree.
+ * If nothing is selected, null is returned.
+ */
protected DefaultMutableTreeNode getSelectedNode() {
- TreePath selPath = tree.getSelectionPath();
+ TreePath selPath = tree.getSelectionPath();
- if(selPath != null)
- return (DefaultMutableTreeNode)selPath.getLastPathComponent();
+ if (selPath != null) {
+ return (DefaultMutableTreeNode) selPath.getLastPathComponent();
+ }
return null;
}
@@ -290,133 +307,136 @@
return new DynamicTreeNode(new SampleData(null, Color.black, name));
}
+
/**
- * AddAction is used to add a new item after the selected item.
- */
- class AddAction extends Object implements ActionListener
- {
+ * AddAction is used to add a new item after the selected item.
+ */
+ class AddAction extends Object implements ActionListener {
+
/** Number of nodes that have been added. */
- public int addCount;
+ public int addCount;
/**
- * Messaged when the user clicks on the Add menu item.
- * Determines the selection from the Tree and adds an item
- * after that. If nothing is selected, an item is added to
- * the root.
- */
+ * Messaged when the user clicks on the Add menu item.
+ * Determines the selection from the Tree and adds an item
+ * after that. If nothing is selected, an item is added to
+ * the root.
+ */
public void actionPerformed(ActionEvent e) {
- DefaultMutableTreeNode lastItem = getSelectedNode();
- DefaultMutableTreeNode parent;
+ DefaultMutableTreeNode lastItem = getSelectedNode();
+ DefaultMutableTreeNode parent;
/* Determine where to create the new node. */
- if(lastItem != null) {
- parent = (DefaultMutableTreeNode)lastItem.getParent();
- if(parent == null) {
- parent = (DefaultMutableTreeNode)treeModel.getRoot();
+ if (lastItem != null) {
+ parent = (DefaultMutableTreeNode) lastItem.getParent();
+ if (parent == null) {
+ parent = (DefaultMutableTreeNode) treeModel.getRoot();
lastItem = null;
}
+ } else {
+ parent = (DefaultMutableTreeNode) treeModel.getRoot();
}
- else
- parent = (DefaultMutableTreeNode)treeModel.getRoot();
if (parent == null) {
// new root
- treeModel.setRoot(createNewNode("Added " +
- Integer.toString(addCount++)));
- }
- else {
- int newIndex;
- if(lastItem == null)
+ treeModel.setRoot(createNewNode("Added " + Integer.toString(
+ addCount++)));
+ } else {
+ int newIndex;
+ if (lastItem == null) {
newIndex = treeModel.getChildCount(parent);
- else
+ } else {
newIndex = parent.getIndex(lastItem) + 1;
+ }
/* Let the treemodel know. */
- treeModel.insertNodeInto(createNewNode("Added " +
- Integer.toString(addCount++)),
- parent, newIndex);
+ treeModel.insertNodeInto(createNewNode("Added " + Integer.
+ toString(addCount++)),
+ parent, newIndex);
}
}
} // End of SampleTree.AddAction
/**
- * InsertAction is used to insert a new item before the selected item.
- */
- class InsertAction extends Object implements ActionListener
- {
+ * InsertAction is used to insert a new item before the selected item.
+ */
+ class InsertAction extends Object implements ActionListener {
+
/** Number of nodes that have been added. */
- public int insertCount;
+ public int insertCount;
/**
- * Messaged when the user clicks on the Insert menu item.
- * Determines the selection from the Tree and inserts an item
- * after that. If nothing is selected, an item is added to
- * the root.
- */
+ * Messaged when the user clicks on the Insert menu item.
+ * Determines the selection from the Tree and inserts an item
+ * after that. If nothing is selected, an item is added to
+ * the root.
+ */
public void actionPerformed(ActionEvent e) {
- DefaultMutableTreeNode lastItem = getSelectedNode();
- DefaultMutableTreeNode parent;
+ DefaultMutableTreeNode lastItem = getSelectedNode();
+ DefaultMutableTreeNode parent;
/* Determine where to create the new node. */
- if(lastItem != null) {
- parent = (DefaultMutableTreeNode)lastItem.getParent();
- if(parent == null) {
- parent = (DefaultMutableTreeNode)treeModel.getRoot();
+ if (lastItem != null) {
+ parent = (DefaultMutableTreeNode) lastItem.getParent();
+ if (parent == null) {
+ parent = (DefaultMutableTreeNode) treeModel.getRoot();
lastItem = null;
}
+ } else {
+ parent = (DefaultMutableTreeNode) treeModel.getRoot();
}
- else
- parent = (DefaultMutableTreeNode)treeModel.getRoot();
if (parent == null) {
// new root
- treeModel.setRoot(createNewNode("Inserted " +
- Integer.toString(insertCount++)));
- }
- else {
- int newIndex;
+ treeModel.setRoot(createNewNode("Inserted " + Integer.toString(
+ insertCount++)));
+ } else {
+ int newIndex;
- if(lastItem == null)
+ if (lastItem == null) {
newIndex = treeModel.getChildCount(parent);
- else
+ } else {
newIndex = parent.getIndex(lastItem);
+ }
/* Let the treemodel know. */
- treeModel.insertNodeInto(createNewNode("Inserted " +
- Integer.toString(insertCount++)),
- parent, newIndex);
+ treeModel.insertNodeInto(createNewNode("Inserted " + Integer.
+ toString(insertCount++)),
+ parent, newIndex);
}
}
} // End of SampleTree.InsertAction
/**
- * ReloadAction is used to reload from the selected node. If nothing
- * is selected, reload is not issued.
- */
- class ReloadAction extends Object implements ActionListener
- {
+ * ReloadAction is used to reload from the selected node. If nothing
+ * is selected, reload is not issued.
+ */
+ class ReloadAction extends Object implements ActionListener {
+
/**
- * Messaged when the user clicks on the Reload menu item.
- * Determines the selection from the Tree and asks the treemodel
- * to reload from that node.
- */
+ * Messaged when the user clicks on the Reload menu item.
+ * Determines the selection from the Tree and asks the treemodel
+ * to reload from that node.
+ */
public void actionPerformed(ActionEvent e) {
- DefaultMutableTreeNode lastItem = getSelectedNode();
+ DefaultMutableTreeNode lastItem = getSelectedNode();
- if(lastItem != null)
+ if (lastItem != null) {
treeModel.reload(lastItem);
+ }
}
} // End of SampleTree.ReloadAction
+
/**
- * RemoveAction removes the selected node from the tree. If
- * The root or nothing is selected nothing is removed.
- */
- class RemoveAction extends Object implements ActionListener
- {
+ * RemoveAction removes the selected node from the tree. If
+ * The root or nothing is selected nothing is removed.
+ */
+ class RemoveAction extends Object implements ActionListener {
+
/**
- * Removes the selected item as long as it isn't root.
- */
+ * Removes the selected item as long as it isn't root.
+ */
public void actionPerformed(ActionEvent e) {
TreePath[] selected = getSelectedPaths();
@@ -451,19 +471,17 @@
paths[counter] = null;
}
treeModel.setRoot(null);
- }
- else {
+ } else {
// Find the siblings of path.
TreePath parent = path.getParentPath();
- MutableTreeNode parentNode = (MutableTreeNode)parent.
- getLastPathComponent();
- ArrayList toRemove = new ArrayList();
- int depth = parent.getPathCount();
+ MutableTreeNode parentNode = (MutableTreeNode) parent.
+ getLastPathComponent();
+ ArrayList<TreePath> toRemove = new ArrayList<TreePath>();
// First pass, find paths with a parent TreePath of parent
for (int counter = paths.length - 1; counter >= 0; counter--) {
- if (paths[counter] != null && paths[counter].
- getParentPath().equals(parent)) {
+ if (paths[counter] != null && paths[counter].getParentPath().
+ equals(parent)) {
toRemove.add(paths[counter]);
paths[counter] = null;
}
@@ -477,9 +495,9 @@
for (int counter = paths.length - 1; counter >= 0; counter--) {
if (paths[counter] != null) {
for (int rCounter = rCount - 1; rCounter >= 0;
- rCounter--) {
- if (((TreePath)toRemove.get(rCounter)).
- isDescendant(paths[counter])) {
+ rCounter--) {
+ if ((toRemove.get(rCounter)).isDescendant(
+ paths[counter])) {
paths[counter] = null;
}
}
@@ -493,10 +511,10 @@
int[] indices = new int[rCount];
Object[] removedNodes = new Object[rCount];
for (int counter = rCount - 1; counter >= 0; counter--) {
- removedNodes[counter] = ((TreePath)toRemove.get(counter)).
- getLastPathComponent();
- indices[counter] = treeModel.getIndexOfChild
- (parentNode, removedNodes[counter]);
+ removedNodes[counter] = (toRemove.get(counter)).
+ getLastPathComponent();
+ indices[counter] = treeModel.getIndexOfChild(parentNode,
+ removedNodes[counter]);
parentNode.remove(indices[counter]);
}
treeModel.nodesWereRemoved(parentNode, indices, removedNodes);
@@ -522,8 +540,7 @@
return shallowestPath;
}
}
- }
- else {
+ } else {
shallowestPath = paths[counter];
shallowest = paths[counter].getPathCount();
}
@@ -540,67 +557,70 @@
* This is actually rather expensive, it would be more efficient
* to extract the indices and then do the comparision.
*/
- private class PositionComparator implements Comparator {
- public int compare(Object o1, Object o2) {
- TreePath p1 = (TreePath)o1;
- int o1Index = treeModel.getIndexOfChild(p1.getParentPath().
- getLastPathComponent(), p1.getLastPathComponent());
- TreePath p2 = (TreePath)o2;
- int o2Index = treeModel.getIndexOfChild(p2.getParentPath().
- getLastPathComponent(), p2.getLastPathComponent());
- return o1Index - o2Index;
- }
+ private class PositionComparator implements Comparator<TreePath> {
- public boolean equals(Object obj) {
- return super.equals(obj);
+ public int compare(TreePath p1, TreePath p2) {
+ int p1Index = treeModel.getIndexOfChild(p1.getParentPath().
+ getLastPathComponent(), p1.getLastPathComponent());
+ int p2Index = treeModel.getIndexOfChild(p2.getParentPath().
+ getLastPathComponent(), p2.getLastPathComponent());
+ return p1Index - p2Index;
}
}
-
} // End of SampleTree.RemoveAction
/**
- * ShowHandlesChangeListener implements the ChangeListener interface
- * to toggle the state of showing the handles in the tree.
- */
- class ShowHandlesChangeListener extends Object implements ChangeListener
- {
+ * ShowHandlesChangeListener implements the ChangeListener interface
+ * to toggle the state of showing the handles in the tree.
+ */
+ class ShowHandlesChangeListener extends Object implements ChangeListener {
+
public void stateChanged(ChangeEvent e) {
- tree.setShowsRootHandles(((JCheckBox)e.getSource()).isSelected());
+ tree.setShowsRootHandles(((JCheckBox) e.getSource()).isSelected());
}
-
} // End of class SampleTree.ShowHandlesChangeListener
/**
- * ShowRootChangeListener implements the ChangeListener interface
- * to toggle the state of showing the root node in the tree.
- */
- class ShowRootChangeListener extends Object implements ChangeListener
- {
+ * ShowRootChangeListener implements the ChangeListener interface
+ * to toggle the state of showing the root node in the tree.
+ */
+ class ShowRootChangeListener extends Object implements ChangeListener {
+
public void stateChanged(ChangeEvent e) {
- tree.setRootVisible(((JCheckBox)e.getSource()).isSelected());
+ tree.setRootVisible(((JCheckBox) e.getSource()).isSelected());
}
-
} // End of class SampleTree.ShowRootChangeListener
/**
- * TreeEditableChangeListener implements the ChangeListener interface
- * to toggle between allowing editing and now allowing editing in
- * the tree.
- */
- class TreeEditableChangeListener extends Object implements ChangeListener
- {
+ * TreeEditableChangeListener implements the ChangeListener interface
+ * to toggle between allowing editing and now allowing editing in
+ * the tree.
+ */
+ class TreeEditableChangeListener extends Object implements ChangeListener {
+
public void stateChanged(ChangeEvent e) {
- tree.setEditable(((JCheckBox)e.getSource()).isSelected());
+ tree.setEditable(((JCheckBox) e.getSource()).isSelected());
}
-
} // End of class SampleTree.TreeEditableChangeListener
+ public static void main(String args[]) {
+ try {
+ SwingUtilities.invokeAndWait(new Runnable() {
- static public void main(String args[]) {
- new SampleTree();
+ @SuppressWarnings(value = "ResultOfObjectAllocationIgnored")
+ public void run() {
+ new SampleTree();
+ }
+ });
+ } catch (InterruptedException ex) {
+ Logger.getLogger(SampleTree.class.getName()).log(Level.SEVERE, null,
+ ex);
+ } catch (InvocationTargetException ex) {
+ Logger.getLogger(SampleTree.class.getName()).log(Level.SEVERE, null,
+ ex);
+ }
}
-
}
--- a/jdk/src/share/demo/jfc/SampleTree/SampleTreeCellRenderer.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/SampleTree/SampleTreeCellRenderer.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,8 +29,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
import javax.swing.Icon;
import javax.swing.ImageIcon;
@@ -42,48 +40,56 @@
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
+import javax.swing.UIManager;
-public class SampleTreeCellRenderer extends JLabel implements TreeCellRenderer
-{
+
+@SuppressWarnings("serial")
+public class SampleTreeCellRenderer extends JLabel implements TreeCellRenderer {
+
/** Font used if the string to be displayed isn't a font. */
- static protected Font defaultFont;
+ protected static Font defaultFont;
/** Icon to use when the item is collapsed. */
- static protected ImageIcon collapsedIcon;
+ protected static ImageIcon collapsedIcon;
/** Icon to use when the item is expanded. */
- static protected ImageIcon expandedIcon;
-
+ protected static ImageIcon expandedIcon;
/** Color to use for the background when selected. */
- static protected final Color SelectedBackgroundColor = Color.yellow;//new Color(0, 0, 128);
+ protected static final Color SELECTED_BACKGROUND_COLOR;
- static
- {
+ static {
+ if ("Nimbus".equals(UIManager.getLookAndFeel().getName())) {
+ SELECTED_BACKGROUND_COLOR = new Color(0, 0,
+ 0, 0);
+ } else {
+ SELECTED_BACKGROUND_COLOR = Color.YELLOW;
+ }
try {
defaultFont = new Font("SansSerif", 0, 12);
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
try {
- collapsedIcon = new ImageIcon(SampleTreeCellRenderer.class.getResource("/resources/images/collapsed.gif"));
- expandedIcon = new ImageIcon(SampleTreeCellRenderer.class.getResource("/resources/images/expanded.gif"));
+ collapsedIcon = new ImageIcon(SampleTreeCellRenderer.class.
+ getResource("/resources/images/collapsed.gif"));
+ expandedIcon = new ImageIcon(SampleTreeCellRenderer.class.
+ getResource("/resources/images/expanded.gif"));
} catch (Exception e) {
System.out.println("Couldn't load images: " + e);
}
}
-
/** Whether or not the item that was last configured is selected. */
- protected boolean selected;
+ protected boolean selected;
/**
- * This is messaged from JTree whenever it needs to get the size
- * of the component or it wants to draw it.
- * This attempts to set the font based on value, which will be
- * a TreeNode.
- */
+ * This is messaged from JTree whenever it needs to get the size
+ * of the component or it wants to draw it.
+ * This attempts to set the font based on value, which will be
+ * a TreeNode.
+ */
public Component getTreeCellRendererComponent(JTree tree, Object value,
- boolean selected, boolean expanded,
- boolean leaf, int row,
- boolean hasFocus) {
- Font font;
- String stringValue = tree.convertValueToText(value, selected,
- expanded, leaf, row, hasFocus);
+ boolean selected, boolean expanded,
+ boolean leaf, int row,
+ boolean hasFocus) {
+ String stringValue = tree.convertValueToText(value, selected,
+ expanded, leaf, row, hasFocus);
/* Set the text. */
setText(stringValue);
@@ -91,24 +97,27 @@
setToolTipText(stringValue);
/* Set the image. */
- if(expanded)
+ if (expanded) {
setIcon(expandedIcon);
- else if(!leaf)
+ } else if (!leaf) {
setIcon(collapsedIcon);
- else
+ } else {
setIcon(null);
+ }
/* Set the color and the font based on the SampleData userObject. */
- SampleData userObject = (SampleData)((DefaultMutableTreeNode)value)
- .getUserObject();
- if(hasFocus)
- setForeground(Color.cyan);
- else
+ SampleData userObject = (SampleData) ((DefaultMutableTreeNode) value).
+ getUserObject();
+ if (hasFocus) {
+ setForeground(UIManager.getColor("Tree.selectionForeground"));
+ } else {
setForeground(userObject.getColor());
- if(userObject.getFont() == null)
+ }
+ if (userObject.getFont() == null) {
setFont(defaultFont);
- else
+ } else {
setFont(userObject.getFont());
+ }
/* Update the selected flag for the next paint. */
this.selected = selected;
@@ -117,36 +126,36 @@
}
/**
- * paint is subclassed to draw the background correctly. JLabel
- * currently does not allow backgrounds other than white, and it
- * will also fill behind the icon. Something that isn't desirable.
- */
+ * paint is subclassed to draw the background correctly. JLabel
+ * currently does not allow backgrounds other than white, and it
+ * will also fill behind the icon. Something that isn't desirable.
+ */
+ @Override
public void paint(Graphics g) {
- Color bColor;
- Icon currentI = getIcon();
+ Color bColor;
+ Icon currentI = getIcon();
- if(selected)
- bColor = SelectedBackgroundColor;
- else if(getParent() != null)
- /* Pick background color up from parent (which will come from
- the JTree we're contained in). */
+ if (selected) {
+ bColor = SELECTED_BACKGROUND_COLOR;
+ } else if (getParent() != null) /* Pick background color up from parent (which will come from
+ the JTree we're contained in). */ {
bColor = getParent().getBackground();
- else
+ } else {
bColor = getBackground();
+ }
g.setColor(bColor);
- if(currentI != null && getText() != null) {
- int offset = (currentI.getIconWidth() + getIconTextGap());
+ if (currentI != null && getText() != null) {
+ int offset = (currentI.getIconWidth() + getIconTextGap());
if (getComponentOrientation().isLeftToRight()) {
g.fillRect(offset, 0, getWidth() - 1 - offset,
- getHeight() - 1);
- }
- else {
+ getHeight() - 1);
+ } else {
g.fillRect(0, 0, getWidth() - 1 - offset, getHeight() - 1);
}
+ } else {
+ g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
}
- else
- g.fillRect(0, 0, getWidth()-1, getHeight()-1);
super.paint(g);
}
}
--- a/jdk/src/share/demo/jfc/SampleTree/SampleTreeModel.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/SampleTree/SampleTreeModel.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,8 +29,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
@@ -38,40 +36,43 @@
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.Color;
+
/**
- * SampleTreeModel extends JTreeModel to extends valueForPathChanged.
- * This method is called as a result of the user editing a value in
- * the tree. If you allow editing in your tree, are using TreeNodes
- * and the user object of the TreeNodes is not a String, then you're going
- * to have to subclass JTreeModel as this example does.
- *
- * @author Scott Violet
- */
+ * SampleTreeModel extends JTreeModel to extends valueForPathChanged.
+ * This method is called as a result of the user editing a value in
+ * the tree. If you allow editing in your tree, are using TreeNodes
+ * and the user object of the TreeNodes is not a String, then you're going
+ * to have to subclass JTreeModel as this example does.
+ *
+ * @author Scott Violet
+ */
+@SuppressWarnings("serial")
+public class SampleTreeModel extends DefaultTreeModel {
-public class SampleTreeModel extends DefaultTreeModel
-{
/**
- * Creates a new instance of SampleTreeModel with newRoot set
- * to the root of this model.
- */
+ * Creates a new instance of SampleTreeModel with newRoot set
+ * to the root of this model.
+ */
public SampleTreeModel(TreeNode newRoot) {
super(newRoot);
}
/**
- * Subclassed to message setString() to the changed path item.
- */
+ * Subclassed to message setString() to the changed path item.
+ */
+ @Override
public void valueForPathChanged(TreePath path, Object newValue) {
/* Update the user object. */
- DefaultMutableTreeNode aNode = (DefaultMutableTreeNode)path.getLastPathComponent();
- SampleData sampleData = (SampleData)aNode.getUserObject();
+ DefaultMutableTreeNode aNode = (DefaultMutableTreeNode) path.
+ getLastPathComponent();
+ SampleData sampleData = (SampleData) aNode.getUserObject();
- sampleData.setString((String)newValue);
+ sampleData.setString((String) newValue);
/* UUUhhhhh, pretty colors. */
sampleData.setColor(Color.green);
/* Since we've changed how the data is to be displayed, message
- nodeChanged. */
+ nodeChanged. */
nodeChanged(aNode);
}
}
--- a/jdk/src/share/demo/jfc/SwingApplet/SwingApplet.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/SwingApplet/SwingApplet.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,42 +29,59 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import java.awt.*;
-import java.awt.event.*;
-import java.net.*;
-import java.applet.*;
-import javax.swing.*;
+import java.awt.FlowLayout;
+import java.lang.reflect.InvocationTargetException;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import javax.swing.JApplet;
+import javax.swing.JButton;
+import javax.swing.SwingUtilities;
+import javax.swing.UIManager;
+
/**
* A very simple applet.
*/
+@SuppressWarnings("serial")
public class SwingApplet extends JApplet {
JButton button;
- public void init() {
-
- // Force SwingApplet to come up in the System L&F
- String laf = UIManager.getSystemLookAndFeelClassName();
+ private void initUI() {
+ // Trying to set Nimbus look and feel
try {
- UIManager.setLookAndFeel(laf);
- // If you want the Cross Platform L&F instead, comment out the above line and
- // uncomment the following:
- // UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
- } catch (UnsupportedLookAndFeelException exc) {
- System.err.println("Warning: UnsupportedLookAndFeel: " + laf);
- } catch (Exception exc) {
- System.err.println("Error loading " + laf + ": " + exc);
+ UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
+ } catch (Exception ex) {
+ Logger.getLogger(SwingApplet.class.getName()).
+ log(Level.SEVERE, "Failed to apply Nimbus look and feel", ex);
}
-
getContentPane().setLayout(new FlowLayout());
button = new JButton("Hello, I'm a Swing Button!");
getContentPane().add(button);
+ getContentPane().doLayout();
}
+ @Override
+ public void init() {
+ try {
+ SwingUtilities.invokeAndWait(new Runnable() {
+
+ @Override
+ public void run() {
+ initUI();
+ }
+ });
+ } catch (InterruptedException ex) {
+ Logger.getLogger(SwingApplet.class.getName()).
+ log(Level.SEVERE, null, ex);
+ } catch (InvocationTargetException ex) {
+ Logger.getLogger(SwingApplet.class.getName()).
+ log(Level.SEVERE, null, ex);
+ }
+ }
+
+ @Override
public void stop() {
if (button != null) {
getContentPane().remove(button);
--- a/jdk/src/share/demo/jfc/TableExample/JDBCAdapter.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/TableExample/JDBCAdapter.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,46 +29,50 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.List;
+import javax.swing.table.AbstractTableModel;
+
/**
* An adaptor, transforming the JDBC interface to the TableModel interface.
*
* @author Philip Milne
*/
-
-import java.util.Vector;
-import java.sql.*;
-import javax.swing.table.AbstractTableModel;
-import javax.swing.event.TableModelEvent;
-
+@SuppressWarnings("serial")
public class JDBCAdapter extends AbstractTableModel {
- Connection connection;
- Statement statement;
- ResultSet resultSet;
- String[] columnNames = {};
- Vector rows = new Vector();
- ResultSetMetaData metaData;
+
+ Connection connection;
+ Statement statement;
+ ResultSet resultSet;
+ String[] columnNames = {};
+ List<List<Object>> rows = new ArrayList<List<Object>>();
+ ResultSetMetaData metaData;
public JDBCAdapter(String url, String driverName,
- String user, String passwd) {
+ String user, String passwd) {
try {
Class.forName(driverName);
System.out.println("Opening db connection");
connection = DriverManager.getConnection(url, user, passwd);
statement = connection.createStatement();
- }
- catch (ClassNotFoundException ex) {
+ } catch (ClassNotFoundException ex) {
System.err.println("Cannot find the database driver classes.");
System.err.println(ex);
- }
- catch (SQLException ex) {
+ } catch (SQLException ex) {
System.err.println("Cannot connect to this database.");
System.err.println(ex);
}
- }
+ }
public void executeQuery(String query) {
if (connection == null || statement == null) {
@@ -79,27 +83,28 @@
resultSet = statement.executeQuery(query);
metaData = resultSet.getMetaData();
- int numberOfColumns = metaData.getColumnCount();
+ int numberOfColumns = metaData.getColumnCount();
columnNames = new String[numberOfColumns];
// Get the column names and cache them.
// Then we can close the connection.
- for(int column = 0; column < numberOfColumns; column++) {
- columnNames[column] = metaData.getColumnLabel(column+1);
+ for (int column = 0; column < numberOfColumns; column++) {
+ columnNames[column] = metaData.getColumnLabel(column + 1);
}
// Get all rows.
- rows = new Vector();
+ rows = new ArrayList<List<Object>>();
while (resultSet.next()) {
- Vector newRow = new Vector();
+ List<Object> newRow = new ArrayList<Object>();
for (int i = 1; i <= getColumnCount(); i++) {
- newRow.addElement(resultSet.getObject(i));
+ newRow.add(resultSet.getObject(i));
}
- rows.addElement(newRow);
+ rows.add(newRow);
}
// close(); Need to copy the metaData, bug in jdbc:odbc driver.
- fireTableChanged(null); // Tell the listeners a new table has arrived.
- }
- catch (SQLException ex) {
+
+ // Tell the listeners a new table has arrived.
+ fireTableChanged(null);
+ } catch (SQLException ex) {
System.err.println(ex);
}
}
@@ -111,6 +116,7 @@
connection.close();
}
+ @Override
protected void finalize() throws Throwable {
close();
super.finalize();
@@ -121,9 +127,8 @@
// Implementation of the TableModel Interface
//
//////////////////////////////////////////////////////////////////////////
-
// MetaData
-
+ @Override
public String getColumnName(int column) {
if (columnNames[column] != null) {
return columnNames[column];
@@ -132,49 +137,49 @@
}
}
- public Class getColumnClass(int column) {
+ @Override
+ public Class<?> getColumnClass(int column) {
int type;
try {
- type = metaData.getColumnType(column+1);
- }
- catch (SQLException e) {
+ type = metaData.getColumnType(column + 1);
+ } catch (SQLException e) {
return super.getColumnClass(column);
}
- switch(type) {
- case Types.CHAR:
- case Types.VARCHAR:
- case Types.LONGVARCHAR:
- return String.class;
+ switch (type) {
+ case Types.CHAR:
+ case Types.VARCHAR:
+ case Types.LONGVARCHAR:
+ return String.class;
- case Types.BIT:
- return Boolean.class;
+ case Types.BIT:
+ return Boolean.class;
- case Types.TINYINT:
- case Types.SMALLINT:
- case Types.INTEGER:
- return Integer.class;
+ case Types.TINYINT:
+ case Types.SMALLINT:
+ case Types.INTEGER:
+ return Integer.class;
- case Types.BIGINT:
- return Long.class;
+ case Types.BIGINT:
+ return Long.class;
- case Types.FLOAT:
- case Types.DOUBLE:
- return Double.class;
+ case Types.FLOAT:
+ case Types.DOUBLE:
+ return Double.class;
- case Types.DATE:
- return java.sql.Date.class;
+ case Types.DATE:
+ return java.sql.Date.class;
- default:
- return Object.class;
+ default:
+ return Object.class;
}
}
+ @Override
public boolean isCellEditable(int row, int column) {
try {
- return metaData.isWritable(column+1);
- }
- catch (SQLException e) {
+ return metaData.isWritable(column + 1);
+ } catch (SQLException e) {
return false;
}
}
@@ -184,14 +189,13 @@
}
// Data methods
-
public int getRowCount() {
return rows.size();
}
public Object getValueAt(int aRow, int aColumn) {
- Vector row = (Vector)rows.elementAt(aRow);
- return row.elementAt(aColumn);
+ List<Object> row = rows.get(aRow);
+ return row.get(aColumn);
}
public String dbRepresentation(int column, Object value) {
@@ -202,43 +206,42 @@
}
try {
- type = metaData.getColumnType(column+1);
- }
- catch (SQLException e) {
+ type = metaData.getColumnType(column + 1);
+ } catch (SQLException e) {
return value.toString();
}
- switch(type) {
- case Types.INTEGER:
- case Types.DOUBLE:
- case Types.FLOAT:
- return value.toString();
- case Types.BIT:
- return ((Boolean)value).booleanValue() ? "1" : "0";
- case Types.DATE:
- return value.toString(); // This will need some conversion.
- default:
- return "\""+value.toString()+"\"";
+ switch (type) {
+ case Types.INTEGER:
+ case Types.DOUBLE:
+ case Types.FLOAT:
+ return value.toString();
+ case Types.BIT:
+ return ((Boolean) value).booleanValue() ? "1" : "0";
+ case Types.DATE:
+ return value.toString(); // This will need some conversion.
+ default:
+ return "\"" + value.toString() + "\"";
}
}
+ @Override
public void setValueAt(Object value, int row, int column) {
try {
- String tableName = metaData.getTableName(column+1);
+ String tableName = metaData.getTableName(column + 1);
// Some of the drivers seem buggy, tableName should not be null.
if (tableName == null) {
System.out.println("Table name returned null.");
}
String columnName = getColumnName(column);
String query =
- "update "+tableName+
- " set "+columnName+" = "+dbRepresentation(column, value)+
- " where ";
+ "update " + tableName + " set " + columnName + " = "
+ + dbRepresentation(column, value) + " where ";
// We don't have a model of the schema so we don't know the
// primary keys or which columns to lock on. To demonstrate
// that editing is possible, we'll just lock on everything.
- for(int col = 0; col<getColumnCount(); col++) {
+ for (int col = 0; col < getColumnCount(); col++) {
String colName = getColumnName(col);
if (colName.equals("")) {
continue;
@@ -246,19 +249,18 @@
if (col != 0) {
query = query + " and ";
}
- query = query + colName +" = "+
- dbRepresentation(col, getValueAt(row, col));
+ query = query + colName + " = " + dbRepresentation(col,
+ getValueAt(row, col));
}
System.out.println(query);
System.out.println("Not sending update to database");
// statement.executeQuery(query);
- }
- catch (SQLException e) {
+ } catch (SQLException e) {
// e.printStackTrace();
System.err.println("Update failed");
}
- Vector dataRow = (Vector)rows.elementAt(row);
- dataRow.setElementAt(value, column);
+ List<Object> dataRow = rows.get(row);
+ dataRow.set(column, value);
}
}
--- a/jdk/src/share/demo/jfc/TableExample/OldJTable.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/TableExample/OldJTable.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,28 +29,26 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
-import java.lang.Thread;
-import java.util.*;
-import java.awt.*;
-import java.awt.event.*;
-import javax.swing.*;
-import javax.swing.event.*;
-import javax.swing.plaf.*;
-import javax.swing.table.*;
+import java.util.EventObject;
+import java.util.List;
+import javax.swing.JTable;
+import javax.swing.table.DefaultTableModel;
+import javax.swing.table.TableCellEditor;
+import javax.swing.table.TableCellRenderer;
+import javax.swing.table.TableColumn;
/**
* The OldJTable is an unsupported class containing some methods that were
* deleted from the JTable between releases 0.6 and 0.7
*/
+@SuppressWarnings("serial")
public class OldJTable extends JTable
{
/*
- * A new convenience method returning the index of the column in the co-ordinate
- * space of the view.
+ * A new convenience method returning the index of the column in the
+ * co-ordinate space of the view.
*/
public int getColumnIndex(Object identifier) {
return getColumnModel().getColumnIndex(identifier);
@@ -65,7 +63,7 @@
return addColumn(columnIdentifier, width, null, null, null);
}
- public TableColumn addColumn(Object columnIdentifier, Vector columnData) {
+ public TableColumn addColumn(Object columnIdentifier, List columnData) {
return addColumn(columnIdentifier, -1, null, null, columnData);
}
@@ -79,16 +77,17 @@
public TableColumn addColumn(Object columnIdentifier, int width,
TableCellRenderer renderer,
- TableCellEditor editor, Vector columnData) {
+ TableCellEditor editor, List columnData) {
checkDefaultTableModel();
// Set up the model side first
DefaultTableModel m = (DefaultTableModel)getModel();
- m.addColumn(columnIdentifier, columnData);
+ m.addColumn(columnIdentifier, columnData.toArray());
// The column will have been added to the end, so the index of the
// column in the model is the last element.
- TableColumn newColumn = new TableColumn(m.getColumnCount()-1, width, renderer, editor);
+ TableColumn newColumn = new TableColumn(
+ m.getColumnCount()-1, width, renderer, editor);
super.addColumn(newColumn);
return newColumn;
}
@@ -104,9 +103,9 @@
((DefaultTableModel)getModel()).addRow(rowData);
}
- public void addRow(Vector rowData) {
+ public void addRow(List rowData) {
checkDefaultTableModel();
- ((DefaultTableModel)getModel()).addRow(rowData);
+ ((DefaultTableModel)getModel()).addRow(rowData.toArray());
}
public void removeRow(int rowIndex) {
@@ -124,9 +123,9 @@
((DefaultTableModel)getModel()).insertRow(rowIndex, rowData);
}
- public void insertRow(int rowIndex, Vector rowData) {
+ public void insertRow(int rowIndex, List rowData) {
checkDefaultTableModel();
- ((DefaultTableModel)getModel()).insertRow(rowIndex, rowData);
+ ((DefaultTableModel)getModel()).insertRow(rowIndex, rowData.toArray());
}
public void setNumRows(int newSize) {
@@ -134,9 +133,10 @@
((DefaultTableModel)getModel()).setNumRows(newSize);
}
- public void setDataVector(Vector newData, Vector columnIds) {
+ public void setDataVector(Object[][] newData, List columnIds) {
checkDefaultTableModel();
- ((DefaultTableModel)getModel()).setDataVector(newData, columnIds);
+ ((DefaultTableModel)getModel()).setDataVector(
+ newData, columnIds.toArray());
}
public void setDataVector(Object[][] newData, Object[] columnIds) {
@@ -154,11 +154,11 @@
//
public Object getValueAt(Object columnIdentifier, int rowIndex) {
- return super.getValueAt(rowIndex, getColumnIndex(columnIdentifier));
+ return super.getValueAt(rowIndex, getColumnIndex(columnIdentifier));
}
public boolean isCellEditable(Object columnIdentifier, int rowIndex) {
- return super.isCellEditable(rowIndex, getColumnIndex(columnIdentifier));
+ return super.isCellEditable(rowIndex, getColumnIndex(columnIdentifier));
}
public void setValueAt(Object aValue, Object columnIdentifier, int rowIndex) {
@@ -217,7 +217,8 @@
public TableColumn addColumn(int modelColumn, int width,
TableCellRenderer renderer,
TableCellEditor editor) {
- TableColumn newColumn = new TableColumn(modelColumn, width, renderer, editor);
+ TableColumn newColumn = new TableColumn(
+ modelColumn, width, renderer, editor);
addColumn(newColumn);
return newColumn;
}
--- a/jdk/src/share/demo/jfc/TableExample/TableExample.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/TableExample/TableExample.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,8 +29,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
/**
* A a UI around the JDBCAdaptor, allowing database data to be interactively
@@ -41,41 +39,56 @@
*
* @author Philip Milne
*/
-
-import java.applet.Applet;
-import java.awt.*;
-import java.awt.event.*;
-import javax.swing.*;
-import javax.swing.table.*;
-import javax.swing.event.*;
-import javax.swing.border.*;
-
-public class TableExample implements LayoutManager {
- static String[] ConnectOptionNames = { "Connect" };
- static String ConnectTitle = "Connection Information";
-
- Dimension origin = new Dimension(0, 0);
-
- JButton fetchButton;
- JButton showConnectionInfoButton;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.Dimension;
+import java.awt.GridLayout;
+import java.awt.LayoutManager;
+import java.awt.Rectangle;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import javax.swing.BoxLayout;
+import javax.swing.JButton;
+import javax.swing.JComponent;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTable;
+import javax.swing.JTextArea;
+import javax.swing.JTextField;
+import javax.swing.UIManager;
+import javax.swing.UIManager.LookAndFeelInfo;
+import javax.swing.border.BevelBorder;
- JPanel connectionPanel;
- JFrame frame; // The query/results window.
+
+public final class TableExample implements LayoutManager {
- JLabel userNameLabel;
- JTextField userNameField;
- JLabel passwordLabel;
- JTextField passwordField;
+ static String[] ConnectOptionNames = { "Connect" };
+ static String ConnectTitle = "Connection Information";
+ Dimension origin = new Dimension(0, 0);
+ JButton fetchButton;
+ JButton showConnectionInfoButton;
+ JPanel connectionPanel;
+ JFrame frame; // The query/results window.
+ JLabel userNameLabel;
+ JTextField userNameField;
+ JLabel passwordLabel;
+ JTextField passwordField;
// JLabel queryLabel;
- JTextArea queryTextArea;
- JComponent queryAggregate;
- JLabel serverLabel;
- JTextField serverField;
- JLabel driverLabel;
- JTextField driverField;
-
- JPanel mainPanel;
-
+ JTextArea queryTextArea;
+ JComponent queryAggregate;
+ JLabel serverLabel;
+ JTextField serverField;
+ JLabel driverLabel;
+ JTextField driverField;
+ JPanel mainPanel;
TableSorter sorter;
JDBCAdapter dataBase;
JScrollPane tableAggregate;
@@ -85,14 +98,15 @@
* If the user clicks on the 'Connect' button the connection is reset.
*/
void activateConnectionDialog() {
- if(JOptionPane.showOptionDialog(tableAggregate, connectionPanel, ConnectTitle,
- JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
- null, ConnectOptionNames, ConnectOptionNames[0]) == 0) {
+ if (JOptionPane.showOptionDialog(tableAggregate, connectionPanel,
+ ConnectTitle,
+ JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
+ null, ConnectOptionNames, ConnectOptionNames[0]) == 0) {
connect();
frame.setVisible(true);
+ } else if (!frame.isVisible()) {
+ System.exit(0);
}
- else if(!frame.isVisible())
- System.exit(0);
}
/**
@@ -102,21 +116,21 @@
public void createConnectionDialog() {
// Create the labels and text fields.
userNameLabel = new JLabel("User name: ", JLabel.RIGHT);
- userNameField = new JTextField("guest");
+ userNameField = new JTextField("app");
passwordLabel = new JLabel("Password: ", JLabel.RIGHT);
- passwordField = new JTextField("trustworthy");
+ passwordField = new JTextField("app");
serverLabel = new JLabel("Database URL: ", JLabel.RIGHT);
- serverField = new JTextField("jdbc:sybase://dbtest:1455/pubs2");
+ serverField = new JTextField("jdbc:derby://localhost:1527/sample");
driverLabel = new JLabel("Driver: ", JLabel.RIGHT);
- driverField = new JTextField("connect.sybase.SybaseDriver");
+ driverField = new JTextField("org.apache.derby.jdbc.ClientDriver");
connectionPanel = new JPanel(false);
connectionPanel.setLayout(new BoxLayout(connectionPanel,
- BoxLayout.X_AXIS));
+ BoxLayout.X_AXIS));
JPanel namePanel = new JPanel(false);
namePanel.setLayout(new GridLayout(0, 1));
@@ -145,22 +159,22 @@
// Create the buttons.
showConnectionInfoButton = new JButton("Configuration");
showConnectionInfoButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- activateConnectionDialog();
- }
+
+ public void actionPerformed(ActionEvent e) {
+ activateConnectionDialog();
}
- );
+ });
fetchButton = new JButton("Fetch");
fetchButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- fetch();
- }
+
+ public void actionPerformed(ActionEvent e) {
+ fetch();
}
- );
+ });
// Create the query text area and label.
- queryTextArea = new JTextArea("SELECT * FROM titles", 25, 25);
+ queryTextArea = new JTextArea("SELECT * FROM APP.CUSTOMER", 25, 25);
queryAggregate = new JScrollPane(queryTextArea);
queryAggregate.setBorder(new BevelBorder(BevelBorder.LOWERED));
@@ -178,7 +192,12 @@
// Create a Frame and put the main panel in it.
frame = new JFrame("TableExample");
frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {System.exit(0);}});
+
+ @Override
+ public void windowClosing(WindowEvent e) {
+ System.exit(0);
+ }
+ });
frame.setBackground(Color.lightGray);
frame.getContentPane().add(mainPanel);
frame.pack();
@@ -189,13 +208,13 @@
}
public void connect() {
- dataBase = new JDBCAdapter(
- serverField.getText(),
- driverField.getText(),
- userNameField.getText(),
- passwordField.getText());
- sorter.setModel(dataBase);
- }
+ dataBase = new JDBCAdapter(
+ serverField.getText(),
+ driverField.getText(),
+ userNameField.getText(),
+ passwordField.getText());
+ sorter.setModel(dataBase);
+ }
public void fetch() {
dataBase.executeQuery(queryTextArea.getText());
@@ -221,25 +240,48 @@
}
public static void main(String s[]) {
+ // Trying to set Nimbus look and feel
+ try {
+ for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
+ if ("Nimbus".equals(info.getName())) {
+ UIManager.setLookAndFeel(info.getClassName());
+ break;
+ }
+ }
+ } catch (Exception ex) {
+ Logger.getLogger(TableExample.class.getName()).log(Level.SEVERE,
+ "Failed to apply Nimbus look and feel", ex);
+ }
+
new TableExample();
}
- public Dimension preferredLayoutSize(Container c){return origin;}
- public Dimension minimumLayoutSize(Container c){return origin;}
- public void addLayoutComponent(String s, Component c) {}
- public void removeLayoutComponent(Component c) {}
+ public Dimension preferredLayoutSize(Container c) {
+ return origin;
+ }
+
+ public Dimension minimumLayoutSize(Container c) {
+ return origin;
+ }
+
+ public void addLayoutComponent(String s, Component c) {
+ }
+
+ public void removeLayoutComponent(Component c) {
+ }
+
public void layoutContainer(Container c) {
Rectangle b = c.getBounds();
int topHeight = 90;
int inset = 4;
- showConnectionInfoButton.setBounds(b.width-2*inset-120, inset, 120, 25);
- fetchButton.setBounds(b.width-2*inset-120, 60, 120, 25);
+ showConnectionInfoButton.setBounds(b.width - 2 * inset - 120, inset, 120,
+ 25);
+ fetchButton.setBounds(b.width - 2 * inset - 120, 60, 120, 25);
// queryLabel.setBounds(10, 10, 100, 25);
- queryAggregate.setBounds(inset, inset, b.width-2*inset - 150, 80);
+ queryAggregate.setBounds(inset, inset, b.width - 2 * inset - 150, 80);
tableAggregate.setBounds(new Rectangle(inset,
- inset + topHeight,
- b.width-2*inset,
- b.height-2*inset - topHeight));
+ inset + topHeight,
+ b.width - 2 * inset,
+ b.height - 2 * inset - topHeight));
}
-
}
--- a/jdk/src/share/demo/jfc/TableExample/TableExample2.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/TableExample/TableExample2.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,28 +29,36 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
+
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.awt.Dimension;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import javax.swing.JFrame;
+import javax.swing.JScrollPane;
+import javax.swing.JTable;
+import javax.swing.UIManager;
+import javax.swing.UIManager.LookAndFeelInfo;
+
/**
* A minimal example, using the JTable to view data from a database.
*
* @author Philip Milne
*/
-
-import javax.swing.*;
-
-import java.awt.event.WindowAdapter;
-import java.awt.event.WindowEvent;
-import java.awt.Dimension;
-
public class TableExample2 {
public TableExample2(String URL, String driver, String user,
- String passwd, String query) {
+ String passwd, String query) {
JFrame frame = new JFrame("Table");
frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {System.exit(0);}});
+
+ @Override
+ public void windowClosing(WindowEvent e) {
+ System.exit(0);
+ }
+ });
JDBCAdapter dt = new JDBCAdapter(URL, driver, user, passwd);
dt.executeQuery(query);
@@ -68,9 +76,26 @@
public static void main(String[] args) {
if (args.length != 5) {
System.err.println("Needs database parameters eg. ...");
- System.err.println("java TableExample2 \"jdbc:sybase://dbtest:1455/pubs2\" \"connect.sybase.SybaseDriver\" guest trustworthy \"select * from titles\"");
+ System.err.println(
+ "java TableExample2 \"jdbc:derby://localhost:1527/sample\" "
+ + "org.apache.derby.jdbc.ClientDriver app app "
+ + "\"select * from app.customer\"");
return;
}
+
+ // Trying to set Nimbus look and feel
+ try {
+ for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
+ if ("Nimbus".equals(info.getName())) {
+ UIManager.setLookAndFeel(info.getClassName());
+ break;
+ }
+ }
+ } catch (Exception ex) {
+ Logger.getLogger(TableExample2.class.getName()).log(Level.SEVERE,
+ "Failed to apply Nimbus look and feel", ex);
+ }
+
new TableExample2(args[0], args[1], args[2], args[3], args[4]);
}
}
--- a/jdk/src/share/demo/jfc/TableExample/TableExample3.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/TableExample/TableExample3.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,8 +29,17 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
+
+import javax.swing.*;
+import javax.swing.table.*;
+
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.awt.Dimension;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import javax.swing.UIManager.LookAndFeelInfo;
+
/**
* An example showing the JTable with a dataModel that is not derived
@@ -39,70 +48,92 @@
*
* @author Philip Milne
*/
-
-import javax.swing.*;
-import javax.swing.table.*;
-
-import java.awt.event.WindowAdapter;
-import java.awt.event.WindowEvent;
-import java.awt.Dimension;
-
public class TableExample3 {
public TableExample3() {
JFrame frame = new JFrame("Table");
frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {System.exit(0);}});
+
+ @Override
+ public void windowClosing(WindowEvent e) {
+ System.exit(0);
+ }
+ });
// Take the dummy data from SwingSet.
- final String[] names = {"First Name", "Last Name", "Favorite Color",
- "Favorite Number", "Vegetarian"};
+ final String[] names = { "First Name", "Last Name", "Favorite Color",
+ "Favorite Number", "Vegetarian" };
final Object[][] data = {
- {"Mark", "Andrews", "Red", new Integer(2), Boolean.TRUE},
- {"Tom", "Ball", "Blue", new Integer(99), Boolean.FALSE},
- {"Alan", "Chung", "Green", new Integer(838), Boolean.FALSE},
- {"Jeff", "Dinkins", "Turquois", new Integer(8), Boolean.TRUE},
- {"Amy", "Fowler", "Yellow", new Integer(3), Boolean.FALSE},
- {"Brian", "Gerhold", "Green", new Integer(0), Boolean.FALSE},
- {"James", "Gosling", "Pink", new Integer(21), Boolean.FALSE},
- {"David", "Karlton", "Red", new Integer(1), Boolean.FALSE},
- {"Dave", "Kloba", "Yellow", new Integer(14), Boolean.FALSE},
- {"Peter", "Korn", "Purple", new Integer(12), Boolean.FALSE},
- {"Phil", "Milne", "Purple", new Integer(3), Boolean.FALSE},
- {"Dave", "Moore", "Green", new Integer(88), Boolean.FALSE},
- {"Hans", "Muller", "Maroon", new Integer(5), Boolean.FALSE},
- {"Rick", "Levenson", "Blue", new Integer(2), Boolean.FALSE},
- {"Tim", "Prinzing", "Blue", new Integer(22), Boolean.FALSE},
- {"Chester", "Rose", "Black", new Integer(0), Boolean.FALSE},
- {"Ray", "Ryan", "Gray", new Integer(77), Boolean.FALSE},
- {"Georges", "Saab", "Red", new Integer(4), Boolean.FALSE},
- {"Willie", "Walker", "Phthalo Blue", new Integer(4), Boolean.FALSE},
- {"Kathy", "Walrath", "Blue", new Integer(8), Boolean.FALSE},
- {"Arnaud", "Weber", "Green", new Integer(44), Boolean.FALSE}
+ { "Mark", "Andrews", "Red", new Integer(2), Boolean.TRUE },
+ { "Tom", "Ball", "Blue", new Integer(99), Boolean.FALSE },
+ { "Alan", "Chung", "Green", new Integer(838), Boolean.FALSE },
+ { "Jeff", "Dinkins", "Turquois", new Integer(8), Boolean.TRUE },
+ { "Amy", "Fowler", "Yellow", new Integer(3), Boolean.FALSE },
+ { "Brian", "Gerhold", "Green", new Integer(0), Boolean.FALSE },
+ { "James", "Gosling", "Pink", new Integer(21), Boolean.FALSE },
+ { "David", "Karlton", "Red", new Integer(1), Boolean.FALSE },
+ { "Dave", "Kloba", "Yellow", new Integer(14), Boolean.FALSE },
+ { "Peter", "Korn", "Purple", new Integer(12), Boolean.FALSE },
+ { "Phil", "Milne", "Purple", new Integer(3), Boolean.FALSE },
+ { "Dave", "Moore", "Green", new Integer(88), Boolean.FALSE },
+ { "Hans", "Muller", "Maroon", new Integer(5), Boolean.FALSE },
+ { "Rick", "Levenson", "Blue", new Integer(2), Boolean.FALSE },
+ { "Tim", "Prinzing", "Blue", new Integer(22), Boolean.FALSE },
+ { "Chester", "Rose", "Black", new Integer(0), Boolean.FALSE },
+ { "Ray", "Ryan", "Gray", new Integer(77), Boolean.FALSE },
+ { "Georges", "Saab", "Red", new Integer(4), Boolean.FALSE },
+ { "Willie", "Walker", "Phthalo Blue", new Integer(4), Boolean.FALSE },
+ { "Kathy", "Walrath", "Blue", new Integer(8), Boolean.FALSE },
+ { "Arnaud", "Weber", "Green", new Integer(44), Boolean.FALSE }
};
// Create a model of the data.
+ @SuppressWarnings("serial")
TableModel dataModel = new AbstractTableModel() {
// These methods always need to be implemented.
- public int getColumnCount() { return names.length; }
- public int getRowCount() { return data.length;}
- public Object getValueAt(int row, int col) {return data[row][col];}
+
+ public int getColumnCount() {
+ return names.length;
+ }
+
+ public int getRowCount() {
+ return data.length;
+ }
+
+ public Object getValueAt(int row, int col) {
+ return data[row][col];
+ }
// The default implementations of these methods in
// AbstractTableModel would work, but we can refine them.
- public String getColumnName(int column) {return names[column];}
- public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
- public boolean isCellEditable(int row, int col) {return (col==4);}
+ @Override
+ public String getColumnName(int column) {
+ return names[column];
+ }
+
+ @Override
+ public Class getColumnClass(int col) {
+ return getValueAt(0, col).getClass();
+ }
+
+ @Override
+ public boolean isCellEditable(int row, int col) {
+ return (col == 4);
+ }
+
+ @Override
public void setValueAt(Object aValue, int row, int column) {
data[row][column] = aValue;
}
- };
+ };
- // Instead of making the table display the data as it would normally with:
+ // Instead of making the table display the data as it would normally
+ // with:
// JTable tableView = new JTable(dataModel);
- // Add a sorter, by using the following three lines instead of the one above.
- TableSorter sorter = new TableSorter(dataModel);
- JTable tableView = new JTable(sorter);
+ // Add a sorter, by using the following three lines instead of the one
+ // above.
+ TableSorter sorter = new TableSorter(dataModel);
+ JTable tableView = new JTable(sorter);
sorter.addMouseListenerToHeaderInTable(tableView);
JScrollPane scrollpane = new JScrollPane(tableView);
@@ -114,6 +145,18 @@
}
public static void main(String[] args) {
+ // Trying to set Nimbus look and feel
+ try {
+ for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
+ if ("Nimbus".equals(info.getName())) {
+ UIManager.setLookAndFeel(info.getClassName());
+ break;
+ }
+ }
+ } catch (Exception ex) {
+ Logger.getLogger(TableExample3.class.getName()).log(Level.SEVERE,
+ "Failed to apply Nimbus look and feel", ex);
+ }
new TableExample3();
}
}
--- a/jdk/src/share/demo/jfc/TableExample/TableExample4.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/TableExample/TableExample4.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,8 +29,18 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
+
+import javax.swing.*;
+import javax.swing.table.*;
+import javax.swing.border.*;
+import java.awt.Dimension;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.awt.Color;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import javax.swing.UIManager.LookAndFeelInfo;
+
/**
* Another JTable example, showing how column attributes can be refined
@@ -40,72 +50,91 @@
*
* @author Philip Milne
*/
-
-import javax.swing.*;
-import javax.swing.table.*;
-import javax.swing.border.*;
-
-import java.awt.Dimension;
-import java.awt.event.WindowAdapter;
-import java.awt.event.WindowEvent;
-import java.awt.Color;
-
public class TableExample4 {
public TableExample4() {
JFrame frame = new JFrame("Table");
frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {System.exit(0);}});
+
+ @Override
+ public void windowClosing(WindowEvent e) {
+ System.exit(0);
+ }
+ });
// Take the dummy data from SwingSet.
- final String[] names = {"First Name", "Last Name", "Favorite Color",
- "Favorite Number", "Vegetarian"};
+ final String[] names = { "First Name", "Last Name", "Favorite Color",
+ "Favorite Number", "Vegetarian" };
final Object[][] data = {
- {"Mark", "Andrews", "Red", new Integer(2), Boolean.TRUE},
- {"Tom", "Ball", "Blue", new Integer(99), Boolean.FALSE},
- {"Alan", "Chung", "Green", new Integer(838), Boolean.FALSE},
- {"Jeff", "Dinkins", "Turquois", new Integer(8), Boolean.TRUE},
- {"Amy", "Fowler", "Yellow", new Integer(3), Boolean.FALSE},
- {"Brian", "Gerhold", "Green", new Integer(0), Boolean.FALSE},
- {"James", "Gosling", "Pink", new Integer(21), Boolean.FALSE},
- {"David", "Karlton", "Red", new Integer(1), Boolean.FALSE},
- {"Dave", "Kloba", "Yellow", new Integer(14), Boolean.FALSE},
- {"Peter", "Korn", "Purple", new Integer(12), Boolean.FALSE},
- {"Phil", "Milne", "Purple", new Integer(3), Boolean.FALSE},
- {"Dave", "Moore", "Green", new Integer(88), Boolean.FALSE},
- {"Hans", "Muller", "Maroon", new Integer(5), Boolean.FALSE},
- {"Rick", "Levenson", "Blue", new Integer(2), Boolean.FALSE},
- {"Tim", "Prinzing", "Blue", new Integer(22), Boolean.FALSE},
- {"Chester", "Rose", "Black", new Integer(0), Boolean.FALSE},
- {"Ray", "Ryan", "Gray", new Integer(77), Boolean.FALSE},
- {"Georges", "Saab", "Red", new Integer(4), Boolean.FALSE},
- {"Willie", "Walker", "Phthalo Blue", new Integer(4), Boolean.FALSE},
- {"Kathy", "Walrath", "Blue", new Integer(8), Boolean.FALSE},
- {"Arnaud", "Weber", "Green", new Integer(44), Boolean.FALSE}
+ { "Mark", "Andrews", "Red", new Integer(2), Boolean.TRUE },
+ { "Tom", "Ball", "Blue", new Integer(99), Boolean.FALSE },
+ { "Alan", "Chung", "Green", new Integer(838), Boolean.FALSE },
+ { "Jeff", "Dinkins", "Turquois", new Integer(8), Boolean.TRUE },
+ { "Amy", "Fowler", "Yellow", new Integer(3), Boolean.FALSE },
+ { "Brian", "Gerhold", "Green", new Integer(0), Boolean.FALSE },
+ { "James", "Gosling", "Pink", new Integer(21), Boolean.FALSE },
+ { "David", "Karlton", "Red", new Integer(1), Boolean.FALSE },
+ { "Dave", "Kloba", "Yellow", new Integer(14), Boolean.FALSE },
+ { "Peter", "Korn", "Purple", new Integer(12), Boolean.FALSE },
+ { "Phil", "Milne", "Purple", new Integer(3), Boolean.FALSE },
+ { "Dave", "Moore", "Green", new Integer(88), Boolean.FALSE },
+ { "Hans", "Muller", "Maroon", new Integer(5), Boolean.FALSE },
+ { "Rick", "Levenson", "Blue", new Integer(2), Boolean.FALSE },
+ { "Tim", "Prinzing", "Blue", new Integer(22), Boolean.FALSE },
+ { "Chester", "Rose", "Black", new Integer(0), Boolean.FALSE },
+ { "Ray", "Ryan", "Gray", new Integer(77), Boolean.FALSE },
+ { "Georges", "Saab", "Red", new Integer(4), Boolean.FALSE },
+ { "Willie", "Walker", "Phthalo Blue", new Integer(4), Boolean.FALSE },
+ { "Kathy", "Walrath", "Blue", new Integer(8), Boolean.FALSE },
+ { "Arnaud", "Weber", "Green", new Integer(44), Boolean.FALSE }
};
// Create a model of the data.
+ @SuppressWarnings("serial")
TableModel dataModel = new AbstractTableModel() {
// These methods always need to be implemented.
- public int getColumnCount() { return names.length; }
- public int getRowCount() { return data.length;}
- public Object getValueAt(int row, int col) {return data[row][col];}
+
+ public int getColumnCount() {
+ return names.length;
+ }
+
+ public int getRowCount() {
+ return data.length;
+ }
+
+ public Object getValueAt(int row, int col) {
+ return data[row][col];
+ }
// The default implementations of these methods in
// AbstractTableModel would work, but we can refine them.
- public String getColumnName(int column) {return names[column];}
- public Class getColumnClass(int c) {return getValueAt(0, c).getClass();}
- public boolean isCellEditable(int row, int col) {return true;}
+ @Override
+ public String getColumnName(int column) {
+ return names[column];
+ }
+
+ @Override
+ public Class getColumnClass(int c) {
+ return getValueAt(0, c).getClass();
+ }
+
+ @Override
+ public boolean isCellEditable(int row, int col) {
+ return true;
+ }
+
+ @Override
public void setValueAt(Object aValue, int row, int column) {
System.out.println("Setting value to: " + aValue);
data[row][column] = aValue;
}
- };
+ };
// Create the table
JTable tableView = new JTable(dataModel);
- // Turn off auto-resizing so that we can set column sizes programmatically.
- // In this mode, all columns will get their preferred widths, as set blow.
+ // Turn off auto-resizing so that we can set column sizes
+ // programmatically. In this mode, all columns will get their preferred
+ // widths, as set blow.
tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// Create a combo box to show that you can use one in a table.
@@ -123,15 +152,18 @@
colorColumn.setCellEditor(new DefaultCellEditor(comboBox));
// Set a pink background and tooltip for the Color column renderer.
- DefaultTableCellRenderer colorColumnRenderer = new DefaultTableCellRenderer();
+ DefaultTableCellRenderer colorColumnRenderer =
+ new DefaultTableCellRenderer();
colorColumnRenderer.setBackground(Color.pink);
colorColumnRenderer.setToolTipText("Click for combo box");
colorColumn.setCellRenderer(colorColumnRenderer);
// Set a tooltip for the header of the colors column.
TableCellRenderer headerRenderer = colorColumn.getHeaderRenderer();
- if (headerRenderer instanceof DefaultTableCellRenderer)
- ((DefaultTableCellRenderer)headerRenderer).setToolTipText("Hi Mom!");
+ if (headerRenderer instanceof DefaultTableCellRenderer) {
+ ((DefaultTableCellRenderer) headerRenderer).setToolTipText(
+ "Hi Mom!");
+ }
// Set the width of the "Vegetarian" column.
TableColumn vegetarianColumn = tableView.getColumn("Vegetarian");
@@ -139,9 +171,14 @@
// Show the values in the "Favorite Number" column in different colors.
TableColumn numbersColumn = tableView.getColumn("Favorite Number");
- DefaultTableCellRenderer numberColumnRenderer = new DefaultTableCellRenderer() {
+ @SuppressWarnings("serial")
+ DefaultTableCellRenderer numberColumnRenderer
+ = new DefaultTableCellRenderer() {
+
+ @Override
public void setValue(Object value) {
- int cellValue = (value instanceof Number) ? ((Number)value).intValue() : 0;
+ int cellValue = (value instanceof Number) ? ((Number) value).
+ intValue() : 0;
setForeground((cellValue > 30) ? Color.black : Color.red);
setText((value == null) ? "" : value.toString());
}
@@ -160,6 +197,19 @@
}
public static void main(String[] args) {
+ // Trying to set Nimbus look and feel
+ try {
+ for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
+ if ("Nimbus".equals(info.getName())) {
+ UIManager.setLookAndFeel(info.getClassName());
+ break;
+ }
+ }
+ } catch (Exception ex) {
+ Logger.getLogger(TableExample4.class.getName()).log(Level.SEVERE,
+ "Failed to apply Nimbus look and feel", ex);
+ }
+
new TableExample4();
}
}
--- a/jdk/src/share/demo/jfc/TableExample/TableMap.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/TableExample/TableMap.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,8 +29,6 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
/**
* In a chain of data manipulators some behaviour is common. TableMap
@@ -41,32 +39,34 @@
* a TableMap which has not been subclassed into a chain of table filters
* should have no effect.
*
- * @author Philip Milne */
-
+ * @author Philip Milne
+ */
import javax.swing.table.*;
import javax.swing.event.TableModelListener;
import javax.swing.event.TableModelEvent;
-public class TableMap extends AbstractTableModel implements TableModelListener
-{
+
+@SuppressWarnings("serial")
+public class TableMap extends AbstractTableModel implements TableModelListener {
+
protected TableModel model;
- public TableModel getModel() {
+ public TableModel getModel() {
return model;
}
- public void setModel(TableModel model) {
+ public void setModel(TableModel model) {
this.model = model;
model.addTableModelListener(this);
}
// By default, Implement TableModel by forwarding all messages
// to the model.
-
public Object getValueAt(int aRow, int aColumn) {
return model.getValueAt(aRow, aColumn);
}
+ @Override
public void setValueAt(Object aValue, int aRow, int aColumn) {
model.setValueAt(aValue, aRow, aColumn);
}
@@ -79,16 +79,19 @@
return (model == null) ? 0 : model.getColumnCount();
}
+ @Override
public String getColumnName(int aColumn) {
return model.getColumnName(aColumn);
}
+ @Override
public Class getColumnClass(int aColumn) {
return model.getColumnClass(aColumn);
}
+ @Override
public boolean isCellEditable(int row, int column) {
- return model.isCellEditable(row, column);
+ return model.isCellEditable(row, column);
}
//
// Implementation of the TableModelListener interface,
--- a/jdk/src/share/demo/jfc/TableExample/TableSorter.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/jfc/TableExample/TableSorter.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -29,8 +29,19 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-/*
- */
+
+import javax.swing.table.TableModel;
+import javax.swing.event.TableModelEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.event.InputEvent;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import javax.swing.JTable;
+import javax.swing.table.JTableHeader;
+import javax.swing.table.TableColumnModel;
+
/**
* A sorter for TableModels. The sorter has a model (conforming to TableModel)
@@ -48,46 +59,29 @@
*
* @author Philip Milne
*/
-
-import java.util.*;
-
-import javax.swing.table.TableModel;
-import javax.swing.event.TableModelEvent;
-
-// Imports for picking up mouse events from the JTable.
+@SuppressWarnings("serial")
+public final class TableSorter extends TableMap {
-import java.awt.event.MouseAdapter;
-import java.awt.event.MouseEvent;
-import java.awt.event.InputEvent;
-import javax.swing.JTable;
-import javax.swing.table.JTableHeader;
-import javax.swing.table.TableColumn;
-import javax.swing.table.TableColumnModel;
-
-public class TableSorter extends TableMap
-{
- int indexes[];
- Vector sortingColumns = new Vector();
- boolean ascending = true;
+ int indexes[];
+ List<Integer> sortingColumns = new ArrayList<Integer>();
+ boolean ascending = true;
int compares;
- public TableSorter()
- {
+ public TableSorter() {
indexes = new int[0]; // For consistency.
}
- public TableSorter(TableModel model)
- {
+ public TableSorter(TableModel model) {
setModel(model);
}
+ @Override
public void setModel(TableModel model) {
super.setModel(model);
reallocateIndexes();
}
- public int compareRowsByColumn(int row1, int row2, int column)
- {
+ public int compareRowsByColumn(int row1, int row2, int column) {
Class type = model.getColumnClass(column);
TableModel data = model;
@@ -99,104 +93,100 @@
// If both values are null return 0
if (o1 == null && o2 == null) {
return 0;
- }
- else if (o1 == null) { // Define null less than everything.
+ } else if (o1 == null) { // Define null less than everything.
return -1;
- }
- else if (o2 == null) {
+ } else if (o2 == null) {
return 1;
}
-/* We copy all returned values from the getValue call in case
-an optimised model is reusing one object to return many values.
-The Number subclasses in the JDK are immutable and so will not be used in
-this way but other subclasses of Number might want to do this to save
-space and avoid unnecessary heap allocation.
-*/
- if (type.getSuperclass() == java.lang.Number.class)
- {
- Number n1 = (Number)data.getValueAt(row1, column);
- double d1 = n1.doubleValue();
- Number n2 = (Number)data.getValueAt(row2, column);
- double d2 = n2.doubleValue();
+ /* We copy all returned values from the getValue call in case
+ an optimised model is reusing one object to return many values.
+ The Number subclasses in the JDK are immutable and so will not be used
+ in this way but other subclasses of Number might want to do this to save
+ space and avoid unnecessary heap allocation.
+ */
+ if (type.getSuperclass() == java.lang.Number.class) {
+ Number n1 = (Number) data.getValueAt(row1, column);
+ double d1 = n1.doubleValue();
+ Number n2 = (Number) data.getValueAt(row2, column);
+ double d2 = n2.doubleValue();
+
+ if (d1 < d2) {
+ return -1;
+ } else if (d1 > d2) {
+ return 1;
+ } else {
+ return 0;
+ }
+ } else if (type == java.util.Date.class) {
+ Date d1 = (Date) data.getValueAt(row1, column);
+ long n1 = d1.getTime();
+ Date d2 = (Date) data.getValueAt(row2, column);
+ long n2 = d2.getTime();
- if (d1 < d2)
- return -1;
- else if (d1 > d2)
- return 1;
- else
- return 0;
+ if (n1 < n2) {
+ return -1;
+ } else if (n1 > n2) {
+ return 1;
+ } else {
+ return 0;
}
- else if (type == java.util.Date.class)
- {
- Date d1 = (Date)data.getValueAt(row1, column);
- long n1 = d1.getTime();
- Date d2 = (Date)data.getValueAt(row2, column);
- long n2 = d2.getTime();
+ } else if (type == String.class) {
+ String s1 = (String) data.getValueAt(row1, column);
+ String s2 = (String) data.getValueAt(row2, column);
+ int result = s1.compareTo(s2);
- if (n1 < n2)
- return -1;
- else if (n1 > n2)
- return 1;
- else return 0;
+ if (result < 0) {
+ return -1;
+ } else if (result > 0) {
+ return 1;
+ } else {
+ return 0;
}
- else if (type == String.class)
+ } else if (type == Boolean.class) {
+ Boolean bool1 = (Boolean) data.getValueAt(row1, column);
+ boolean b1 = bool1.booleanValue();
+ Boolean bool2 = (Boolean) data.getValueAt(row2, column);
+ boolean b2 = bool2.booleanValue();
+
+ if (b1 == b2) {
+ return 0;
+ } else if (b1) // Define false < true
{
- String s1 = (String)data.getValueAt(row1, column);
- String s2 = (String)data.getValueAt(row2, column);
- int result = s1.compareTo(s2);
-
- if (result < 0)
- return -1;
- else if (result > 0)
- return 1;
- else return 0;
+ return 1;
+ } else {
+ return -1;
}
- else if (type == Boolean.class)
- {
- Boolean bool1 = (Boolean)data.getValueAt(row1, column);
- boolean b1 = bool1.booleanValue();
- Boolean bool2 = (Boolean)data.getValueAt(row2, column);
- boolean b2 = bool2.booleanValue();
+ } else {
+ Object v1 = data.getValueAt(row1, column);
+ String s1 = v1.toString();
+ Object v2 = data.getValueAt(row2, column);
+ String s2 = v2.toString();
+ int result = s1.compareTo(s2);
- if (b1 == b2)
- return 0;
- else if (b1) // Define false < true
- return 1;
- else
- return -1;
+ if (result < 0) {
+ return -1;
+ } else if (result > 0) {
+ return 1;
+ } else {
+ return 0;
}
- else
- {
- Object v1 = data.getValueAt(row1, column);
- String s1 = v1.toString();
- Object v2 = data.getValueAt(row2, column);
- String s2 = v2.toString();
- int result = s1.compareTo(s2);
-
- if (result < 0)
- return -1;
- else if (result > 0)
- return 1;
- else return 0;
- }
+ }
}
- public int compare(int row1, int row2)
- {
+ public int compare(int row1, int row2) {
compares++;
- for(int level = 0; level < sortingColumns.size(); level++)
- {
- Integer column = (Integer)sortingColumns.elementAt(level);
- int result = compareRowsByColumn(row1, row2, column.intValue());
- if (result != 0)
- return ascending ? result : -result;
+ for (int level = 0; level < sortingColumns.size(); level++) {
+ Integer column = sortingColumns.get(level);
+ int result = compareRowsByColumn(row1, row2, column.intValue());
+ if (result != 0) {
+ return ascending ? result : -result;
}
+ }
return 0;
}
- public void reallocateIndexes()
- {
+ public void reallocateIndexes() {
int rowCount = model.getRowCount();
// Set up a new array of indexes with the right number of elements
@@ -204,39 +194,38 @@
indexes = new int[rowCount];
// Initialise with the identity mapping.
- for(int row = 0; row < rowCount; row++)
+ for (int row = 0; row < rowCount; row++) {
indexes[row] = row;
+ }
}
- public void tableChanged(TableModelEvent e)
- {
+ @Override
+ public void tableChanged(TableModelEvent e) {
System.out.println("Sorter: tableChanged");
reallocateIndexes();
super.tableChanged(e);
}
- public void checkModel()
- {
+ public void checkModel() {
if (indexes.length != model.getRowCount()) {
System.err.println("Sorter not informed of a change in model.");
}
}
- public void sort(Object sender)
- {
+ public void sort(Object sender) {
checkModel();
compares = 0;
// n2sort();
// qsort(0, indexes.length-1);
- shuttlesort((int[])indexes.clone(), indexes, 0, indexes.length);
- System.out.println("Compares: "+compares);
+ shuttlesort(indexes.clone(), indexes, 0, indexes.length);
+ System.out.println("Compares: " + compares);
}
public void n2sort() {
- for(int i = 0; i < getRowCount(); i++) {
- for(int j = i+1; j < getRowCount(); j++) {
+ for (int i = 0; i < getRowCount(); i++) {
+ for (int j = i + 1; j < getRowCount(); j++) {
if (compare(indexes[i], indexes[j]) == -1) {
swap(i, j);
}
@@ -255,7 +244,7 @@
if (high - low < 2) {
return;
}
- int middle = (low + high)/2;
+ int middle = (low + high) / 2;
shuttlesort(to, from, low, middle);
shuttlesort(to, from, middle, high);
@@ -277,20 +266,17 @@
find out how the performance drops to Nlog(N) as the initial
order diminishes - it may drop very quickly. */
- if (high - low >= 4 && compare(from[middle-1], from[middle]) <= 0) {
- for (int i = low; i < high; i++) {
- to[i] = from[i];
- }
+ if (high - low >= 4 && compare(from[middle - 1], from[middle]) <= 0) {
+ System.arraycopy(from, low, to, low, high - low);
return;
}
// A normal merge.
- for(int i = low; i < high; i++) {
+ for (int i = low; i < high; i++) {
if (q >= high || (p < middle && compare(from[p], from[q]) <= 0)) {
to[i] = from[p++];
- }
- else {
+ } else {
to[i] = from[q++];
}
}
@@ -304,15 +290,14 @@
// The mapping only affects the contents of the data rows.
// Pass all requests to these rows through the mapping array: "indexes".
-
- public Object getValueAt(int aRow, int aColumn)
- {
+ @Override
+ public Object getValueAt(int aRow, int aColumn) {
checkModel();
return model.getValueAt(indexes[aRow], aColumn);
}
- public void setValueAt(Object aValue, int aRow, int aColumn)
- {
+ @Override
+ public void setValueAt(Object aValue, int aRow, int aColumn) {
checkModel();
model.setValueAt(aValue, indexes[aRow], aColumn);
}
@@ -323,8 +308,8 @@
public void sortByColumn(int column, boolean ascending) {
this.ascending = ascending;
- sortingColumns.removeAllElements();
- sortingColumns.addElement(new Integer(column));
+ sortingColumns.clear();
+ sortingColumns.add(column);
sort(this);
super.tableChanged(new TableModelEvent(this));
}
@@ -337,22 +322,21 @@
final JTable tableView = table;
tableView.setColumnSelectionAllowed(false);
MouseAdapter listMouseListener = new MouseAdapter() {
+
+ @Override
public void mouseClicked(MouseEvent e) {
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = tableView.convertColumnIndexToModel(viewColumn);
- if(e.getClickCount() == 1 && column != -1) {
+ if (e.getClickCount() == 1 && column != -1) {
System.out.println("Sorting ...");
- int shiftPressed = e.getModifiers()&InputEvent.SHIFT_MASK;
+ int shiftPressed = e.getModifiers() & InputEvent.SHIFT_MASK;
boolean ascending = (shiftPressed == 0);
sorter.sortByColumn(column, ascending);
}
- }
- };
+ }
+ };
JTableHeader th = tableView.getTableHeader();
th.addMouseListener(listMouseListener);
}
-
-
-
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/jfc/TransparentRuler/README.txt Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,14 @@
+
+To run the Ruler demo:
+
+ java -jar Ruler.jar
+
+These instructions assume that this installation's version of the java
+command is in your path. If it isn't, then you should either
+specify the complete path to the java command or update your
+PATH environment variable as described in the installation
+instructions for the Java(TM) SE Development Kit.
+
+KNOWN ISSUES:
+Context menu is clipped with the window shape. The issues are:
+CR 7027486 JPopupMenu doesn't take window shape into account
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/jfc/TransparentRuler/transparentruler/Ruler.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,234 @@
+/*
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+package transparentruler;
+
+
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsDevice.WindowTranslucency;
+import java.awt.GraphicsEnvironment;
+import java.awt.event.ActionEvent;
+import java.awt.event.ComponentAdapter;
+import java.awt.event.ComponentEvent;
+import java.awt.event.KeyAdapter;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.geom.Path2D.Float;
+import java.lang.reflect.InvocationTargetException;
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.JFrame;
+import javax.swing.JMenuItem;
+import javax.swing.JPanel;
+import javax.swing.JPopupMenu;
+import javax.swing.SwingUtilities;
+import javax.swing.WindowConstants;
+
+
+/**
+ * This sample demonstrates shaped and translucent window feature.
+ * @author Alexander Kouznetsov
+ */
+@SuppressWarnings("serial")
+public class Ruler extends JFrame {
+
+ private static final Color BACKGROUND = Color.RED;
+ private static final Color FOREGROUND = Color.WHITE;
+ private static final int OPACITY = 180;
+ private static final int W = 70;
+ private static final int F_HEIGHT = 400;
+ private static final int F_WIDTH = (int) (F_HEIGHT * 1.618 + 0.5);
+
+ private static void checkTranslucencyMode(WindowTranslucency arg) {
+ GraphicsEnvironment ge =
+ GraphicsEnvironment.getLocalGraphicsEnvironment();
+ GraphicsDevice gd = ge.getDefaultScreenDevice();
+ if (!gd.isWindowTranslucencySupported(arg)) {
+ System.err.println("'" + arg
+ + "' translucency mode isn't supported.");
+ System.exit(-1);
+ }
+ }
+ private final ComponentAdapter componentListener = new ComponentAdapter() {
+
+ /**
+ * Applies the shape to window. It is recommended to apply shape in
+ * componentResized() method
+ */
+ @Override
+ public void componentResized(ComponentEvent e) {
+ int h = getHeight();
+ int w = getWidth();
+ float a = (float) Math.hypot(h, w);
+ Float path = new java.awt.geom.Path2D.Float();
+ path.moveTo(0, 0);
+ path.lineTo(w, 0);
+ path.lineTo(0, h);
+ path.closePath();
+ path.moveTo(W, W);
+ path.lineTo(W, h - W * (a + h) / w);
+ path.lineTo(w - W * (a + w) / h, W);
+ path.closePath();
+ setShape(path);
+ }
+ };
+ private final Action exitAction = new AbstractAction("Exit") {
+
+ {
+ putValue(Action.MNEMONIC_KEY, KeyEvent.VK_X);
+ }
+
+ public void actionPerformed(ActionEvent e) {
+ System.exit(0);
+ }
+ };
+ private final JPopupMenu jPopupMenu = new JPopupMenu();
+
+ {
+ jPopupMenu.add(new JMenuItem(exitAction));
+ }
+ /**
+ * Implements mouse-related behavior: window dragging and popup menu
+ * invocation
+ */
+ private final MouseAdapter mouseListener = new MouseAdapter() {
+
+ int x, y;
+
+ @Override
+ public void mousePressed(MouseEvent e) {
+ if (e.getButton() == MouseEvent.BUTTON1) {
+ x = e.getX();
+ y = e.getY();
+ }
+ }
+
+ @Override
+ public void mouseDragged(MouseEvent e) {
+ if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) {
+ setLocation(e.getXOnScreen() - x, e.getYOnScreen() - y);
+ }
+ }
+
+ @Override
+ public void mouseReleased(MouseEvent e) {
+ if (e.isPopupTrigger()) {
+ jPopupMenu.show(getContentPane(), e.getX(), e.getY());
+ }
+ }
+ };
+ /**
+ * Implements keyboard navigation. Arrows move by 5 pixels, Ctrl + arrows
+ * move by 50 pixels, Alt + arrows move by 1 pixel.
+ * Esc exits the application.
+ */
+ private final KeyAdapter keyboardListener = new KeyAdapter() {
+
+ @Override
+ public void keyPressed(KeyEvent e) {
+ int step = e.isControlDown() ? 50 : e.isAltDown() ? 1 : 5;
+ switch (e.getKeyCode()) {
+ case KeyEvent.VK_LEFT:
+ setLocation(getX() - step, getY());
+ break;
+ case KeyEvent.VK_RIGHT:
+ setLocation(getX() + step, getY());
+ break;
+ case KeyEvent.VK_UP:
+ setLocation(getX(), getY() - step);
+ break;
+ case KeyEvent.VK_DOWN:
+ setLocation(getX(), getY() + step);
+ break;
+ case KeyEvent.VK_ESCAPE:
+ exitAction.actionPerformed(null);
+ }
+ }
+ };
+
+ public Ruler() {
+ setUndecorated(true);
+
+ // Enables perpixel translucency
+ setBackground(new Color(BACKGROUND.getRed(), BACKGROUND.getGreen(),
+ BACKGROUND.getBlue(), OPACITY));
+
+ addMouseListener(mouseListener);
+ addMouseMotionListener(mouseListener);
+ addComponentListener(componentListener);
+ addKeyListener(keyboardListener);
+ setContentPane(new JPanel() {
+
+ @Override
+ protected void paintComponent(Graphics g) {
+ Graphics gg = g.create();
+ int w = getWidth();
+ int h = getHeight();
+ int hh = gg.getFontMetrics().getAscent();
+ gg.setColor(FOREGROUND);
+ for (int x = 0; x < w * (h - 8) / h - 5; x += 5) {
+ boolean hi = x % 50 == 0;
+ gg.drawLine(x + 5, 0, x + 5,
+ hi ? 20 : (x % 25 == 0 ? 13 : 8));
+ if (hi) {
+ String number = Integer.toString(x);
+ int ww = gg.getFontMetrics().stringWidth(number);
+ gg.drawString(number, x + 5 - ww / 2, 20 + hh);
+ }
+ }
+ gg.dispose();
+ }
+ });
+ setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+ setSize(F_WIDTH, F_HEIGHT);
+ setLocationByPlatform(true);
+ }
+
+ /**
+ * @param args the command line arguments are ignored
+ */
+ public static void main(String[] args) throws InterruptedException, InvocationTargetException {
+
+ SwingUtilities.invokeAndWait(new Runnable() {
+
+ public void run() {
+ checkTranslucencyMode(WindowTranslucency.PERPIXEL_TRANSLUCENT);
+ checkTranslucencyMode(WindowTranslucency.PERPIXEL_TRANSPARENT);
+
+ Ruler ruler = new Ruler();
+ ruler.setVisible(true);
+ }
+ });
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/nbproject/jfc/TransparentRuler/build.properties Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,22 @@
+main.dir=${basedir}/../../../jfc/TransparentRuler
+
+src.dir=${main.dir}/src
+
+build.dir=build
+classes.dir=${build.dir}/classes
+jar=${main.dir}/TransparentRuler.jar
+javadoc.dir=${build.dir}/javadoc
+
+build.sysclasspath=ignore
+# E.g.: cp=lib/x.jar:lib/y.jar
+cp=
+extra.run.cp=
+
+main.class=transparentruler.Ruler
+
+run.cp=${cp}:${classes.dir}:${extra.run.cp}
+
+debug=true
+deprecation=false
+
+nbjdk.home=${basedir}/../../../..
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/nbproject/jfc/TransparentRuler/build.xml Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,91 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+ Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ - Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ - Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ - Neither the name of Oracle nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+-->
+
+<project name="TransparentRuler" basedir="." default="jar">
+
+ <import file="nbproject/jdk.xml"/>
+
+ <target name="-prop-init">
+ <property file="user.build.properties"/>
+ <property file="build.properties"/>
+ </target>
+
+ <target name="-init" depends="-prop-init,-jdk-init"/>
+
+ <target name="compile" depends="-init" description="Compile main sources.">
+ <mkdir dir="${classes.dir}"/>
+ <javac srcdir="${src.dir}" destdir="${classes.dir}" debug="${debug}" deprecation="${deprecation}">
+ <classpath path="${cp}"/>
+ </javac>
+ <copy todir="${classes.dir}">
+ <fileset dir="${src.dir}"/>
+ </copy>
+ </target>
+
+ <target name="jar" depends="compile" description="Build JAR file for main sources.">
+ <jar jarfile="${jar}" compress="true">
+ <manifest>
+ <attribute name="Main-Class" value="${main.class}"/>
+ </manifest>
+ <fileset dir="${classes.dir}"/>
+ </jar>
+ </target>
+
+ <target name="run" depends="compile" description="Run application.">
+ <fail unless="main.class">Must set property 'main.class' (e.g. in build.properties)</fail>
+ <java classname="${main.class}" fork="true" failonerror="true">
+ <classpath path="${run.cp}"/>
+ </java>
+ </target>
+
+ <target name="javadoc" depends="-init" description="Build Javadoc.">
+ <mkdir dir="${javadoc.dir}"/>
+ <javadoc destdir="${javadoc.dir}">
+ <classpath path="${cp}"/>
+ <sourcepath>
+ <pathelement location="${src.dir}"/>
+ </sourcepath>
+ <fileset dir="${src.dir}"/>
+ </javadoc>
+ </target>
+
+ <target name="clean" depends="-init" description="Clean build products.">
+ <delete dir="${build.dir}"/>
+ <delete file="${jar}"/>
+ </target>
+
+ <target name="profile">
+ <ant antfile="nbproject/netbeans-targets.xml" target="profile"/>
+ </target>
+
+</project>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/file-targets.xml Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+ Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ - Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ - Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ - Neither the name of Oracle nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+-->
+
+<project basedir=".." name="TransparentRuler/file">
+
+ <import file="../build.xml"/>
+
+ <target name="compile-selected" depends="-init">
+ <fail unless="includes">Must set property 'includes'</fail>
+ <mkdir dir="${classes.dir}"/>
+ <javac srcdir="${src.dir}" destdir="${classes.dir}" debug="${debug}" deprecation="${deprecation}" includes="${includes}">
+ <classpath path="${cp}"/>
+ </javac>
+ </target>
+
+</project>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/jdk.xml Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,98 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+ Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ - Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ - Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ - Neither the name of Oracle nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+-->
+
+<project name="jdk" basedir=".">
+
+ <target name="-jdk-preinit">
+ <condition property=".exe" value=".exe">
+ <os family="windows"/>
+ </condition>
+ <property name=".exe" value=""/>
+ <property name="nbjdk.javac" value="${nbjdk.home}/bin/javac${.exe}"/>
+ <property name="nbjdk.java" value="${nbjdk.home}/bin/java${.exe}"/>
+ <property name="nbjdk.javadoc" value="${nbjdk.home}/bin/javadoc${.exe}"/>
+ <property name="nbjdk.appletviewer" value="${nbjdk.home}/bin/appletviewer${.exe}"/>
+ <property name="nbjdk.bootclasspath" value="${nbjdk.home}/jre/lib/rt.jar"/>
+ </target>
+
+ <target name="-jdk-presetdef-basic" depends="-jdk-preinit" unless="nbjdk.presetdef.basic.done">
+ <macrodef name="javac-presetdef">
+ <attribute name="javacval"/>
+ <sequential>
+ <presetdef name="javac">
+ <javac fork="yes" executable="@{javacval}"/>
+ </presetdef>
+ </sequential>
+ </macrodef>
+ <javac-presetdef javacval="${nbjdk.javac}"/>
+ <macrodef name="java-presetdef">
+ <attribute name="javaval"/>
+ <sequential>
+ <presetdef name="java">
+ <java fork="yes" jvm="@{javaval}"/>
+ </presetdef>
+ </sequential>
+ </macrodef>
+ <java-presetdef javaval="${nbjdk.java}"/>
+ <macrodef name="javadoc-presetdef">
+ <attribute name="javadocval"/>
+ <sequential>
+ <presetdef name="javadoc">
+ <javadoc executable="@{javadocval}"/>
+ </presetdef>
+ </sequential>
+ </macrodef>
+ <javadoc-presetdef javadocval="${nbjdk.javadoc}"/>
+ <property name="nbjdk.presetdef.basic.done" value="true"/>
+ </target>
+
+ <target name="-jdk-presetdef-nbjpdastart" depends="-jdk-preinit" unless="nbjdk.presetdef.nbjpdastart.done">
+ <macrodef name="nbjpdastart-presetdef">
+ <attribute name="bootcpval"/>
+ <sequential>
+ <presetdef name="nbjpdastart">
+ <nbjpdastart>
+ <bootclasspath>
+ <path path="@{bootcpval}"/>
+ </bootclasspath>
+ </nbjpdastart>
+ </presetdef>
+ </sequential>
+ </macrodef>
+ <nbjpdastart-presetdef bootcpval="${nbjdk.bootclasspath}"/>
+ <property name="nbjdk.presetdef.nbjpdastart.done" value="true"/>
+ </target>
+
+ <target name="-jdk-init" depends="-jdk-preinit,-jdk-presetdef-basic"/>
+
+</project>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/netbeans-targets.xml Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,81 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+ Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ - Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ - Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ - Neither the name of Oracle nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+-->
+
+<project basedir=".." name="TransparentRuler/NB">
+
+ <import file="../build.xml"/>
+
+ <target name="debug" depends="compile,-jdk-presetdef-nbjpdastart">
+ <nbjpdastart addressproperty="jpda.address" name="TransparentRuler" transport="dt_socket">
+ <classpath path="${run.cp}"/>
+ </nbjpdastart>
+ <java classname="${main.class}" failonerror="true" fork="true">
+ <classpath path="${run.cp}"/>
+ <jvmarg value="-Xdebug"/>
+ <jvmarg value="-Xnoagent"/>
+ <jvmarg value="-Djava.compiler=none"/>
+ <jvmarg value="-Xrunjdwp:transport=dt_socket,address=${jpda.address}"/>
+ </java>
+ </target>
+
+ <target name="debug-fix" depends="-init">
+ <javac srcdir="${src.dir}" destdir="${classes.dir}" debug="true" deprecation="${deprecation}">
+ <classpath path="${cp}"/>
+ <include name="${class}.java"/>
+ </javac>
+ <nbjpdareload>
+ <fileset dir="${classes.dir}">
+ <include name="${class}.class"/>
+ </fileset>
+ </nbjpdareload>
+ </target>
+
+ <target name="show-javadoc" depends="javadoc">
+ <nbbrowse file="${javadoc.dir}/index.html"/>
+ </target>
+
+ <target name="profile" depends="compile">
+ <nbprofiledirect>
+ <classpath path="${run.cp}"/>
+ </nbprofiledirect>
+ <property environment="env"/>
+ <java classname="${main.class}" fork="true" failonerror="true" dir="${profiler.session.working.dir}" jvm="${profiler.info.jvm}">
+ <classpath path="${run.cp}"/>
+ <jvmarg value="${profiler.info.jvmargs.agent}"/>
+ <jvmarg line="${profiler.info.jvmargs}"/>
+ <env key="LD_LIBRARY_PATH" path="${profiler.info.agentpath}:${env.LD_LIBRARY_PATH}"/>
+ <env key="Path" path="${profiler.info.agentpath}:${env.Path}"/>
+ </java>
+ </target>
+
+</project>
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/nbproject/jfc/TransparentRuler/nbproject/project.xml Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,173 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+ Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ - Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ - Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ - Neither the name of Oracle nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+-->
+
+<project xmlns="http://www.netbeans.org/ns/project/1">
+ <type>org.netbeans.modules.ant.freeform</type>
+ <configuration>
+ <general-data xmlns="http://www.netbeans.org/ns/freeform-project/1">
+ <name>TransparentRuler</name>
+ <properties>
+ <property-file>user.build.properties</property-file>
+ <property-file>build.properties</property-file>
+ <property name="nbjdk.bootclasspath">${nbjdk.home}/jre/lib/rt.jar</property>
+ </properties>
+ <folders>
+ <source-folder>
+ <label>JDK Demo</label>
+ <location>${main.dir}</location>
+ </source-folder>
+ <source-folder>
+ <label>Sources</label>
+ <type>java</type>
+ <location>${src.dir}</location>
+ </source-folder>
+ <build-folder>
+ <location>${build.dir}</location>
+ </build-folder>
+ </folders>
+ <ide-actions>
+ <action name="build">
+ <target>jar</target>
+ </action>
+ <action name="clean">
+ <target>clean</target>
+ </action>
+ <action name="rebuild">
+ <target>clean</target>
+ <target>jar</target>
+ </action>
+ <action name="run">
+ <target>run</target>
+ </action>
+ <action name="javadoc">
+ <script>nbproject/netbeans-targets.xml</script>
+ <target>show-javadoc</target>
+ </action>
+ <action name="debug">
+ <script>nbproject/netbeans-targets.xml</script>
+ <target>debug</target>
+ </action>
+ <action name="compile.single">
+ <script>nbproject/file-targets.xml</script>
+ <target>compile-selected</target>
+ <context>
+ <property>includes</property>
+ <folder>${src.dir}</folder>
+ <pattern>\.java$</pattern>
+ <format>relative-path</format>
+ <arity>
+ <separated-files>,</separated-files>
+ </arity>
+ </context>
+ </action>
+ <action name="run.single">
+ <target>run</target>
+ <context>
+ <property>main.class</property>
+ <folder>${src.dir}</folder>
+ <pattern>\.java$</pattern>
+ <format>java-name</format>
+ <arity>
+ <one-file-only/>
+ </arity>
+ </context>
+ </action>
+ <action name="debug.single">
+ <script>nbproject/netbeans-targets.xml</script>
+ <target>debug</target>
+ <context>
+ <property>main.class</property>
+ <folder>${src.dir}</folder>
+ <pattern>\.java$</pattern>
+ <format>java-name</format>
+ <arity>
+ <one-file-only/>
+ </arity>
+ </context>
+ </action>
+ <action name="debug.fix">
+ <script>nbproject/netbeans-targets.xml</script>
+ <target>debug-fix</target>
+ <context>
+ <property>class</property>
+ <folder>${src.dir}</folder>
+ <pattern>\.java$</pattern>
+ <format>relative-path-noext</format>
+ <arity>
+ <one-file-only/>
+ </arity>
+ </context>
+ </action>
+ </ide-actions>
+ <export>
+ <type>jar</type>
+ <location>${jar}</location>
+ <build-target>jar</build-target>
+ <clean-target>clean</clean-target>
+ </export>
+ <view>
+ <items>
+ <source-folder style="packages">
+ <label>Sources</label>
+ <location>${src.dir}</location>
+ </source-folder>
+ <source-file>
+ <location>${main.dir}/README.txt</location>
+ </source-file>
+ </items>
+ <context-menu>
+ <ide-action name="build"/>
+ <ide-action name="rebuild"/>
+ <ide-action name="clean"/>
+ <ide-action name="javadoc"/>
+ <separator/>
+ <ide-action name="run"/>
+ <ide-action name="debug"/>
+ </context-menu>
+ </view>
+ <subprojects/>
+ </general-data>
+ <java-data xmlns="http://www.netbeans.org/ns/freeform-project-java/2">
+ <compilation-unit>
+ <package-root>${src.dir}</package-root>
+ <classpath mode="compile">${cp}</classpath>
+ <classpath mode="execute">${run.cp}</classpath>
+ <classpath mode="boot">${nbjdk.bootclasspath}</classpath>
+ <built-to>${classes.dir}</built-to>
+ <built-to>${jar}</built-to>
+ <javadoc-built-to>${javadoc.dir}</javadoc-built-to>
+ <source-level>1.5</source-level>
+ </compilation-unit>
+ </java-data>
+ </configuration>
+</project>
--- a/jdk/src/share/demo/nbproject/project.xml Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/nbproject/project.xml Sun Apr 10 10:23:28 2011 -0700
@@ -50,6 +50,7 @@
<project>nbproject/jfc/Stylepad</project>
<project>nbproject/jfc/SwingApplet</project>
<project>nbproject/jfc/TableExample</project>
+ <project>nbproject/jfc/TransparentRuler</project>
<project>nbproject/scripting/jconsole-plugin</project>
<project>nbproject/management/FullThreadDump</project>
<project>nbproject/management/JTop</project>
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystemProvider.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystemProvider.java Sun Apr 10 10:23:28 2011 -0700
@@ -99,7 +99,7 @@
synchronized(filesystems) {
Path realPath = null;
if (ensureFile(path)) {
- realPath = path.toRealPath(true);
+ realPath = path.toRealPath();
if (filesystems.containsKey(realPath))
throw new FileSystemAlreadyExistsException();
}
@@ -154,7 +154,7 @@
synchronized (filesystems) {
ZipFileSystem zipfs = null;
try {
- zipfs = filesystems.get(uriToPath(uri).toRealPath(true));
+ zipfs = filesystems.get(uriToPath(uri).toRealPath());
} catch (IOException x) {
// ignore the ioe from toRealPath(), return FSNFE
}
@@ -310,7 +310,7 @@
//////////////////////////////////////////////////////////////
void removeFileSystem(Path zfpath, ZipFileSystem zfs) throws IOException {
synchronized (filesystems) {
- zfpath = zfpath.toRealPath(true);
+ zfpath = zfpath.toRealPath();
if (filesystems.get(zfpath) == zfs)
filesystems.remove(zfpath);
}
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java Sun Apr 10 10:23:28 2011 -0700
@@ -150,7 +150,7 @@
}
@Override
- public ZipPath toRealPath(boolean resolveLinks) throws IOException {
+ public ZipPath toRealPath(LinkOption... options) throws IOException {
ZipPath realPath = new ZipPath(zfs, getResolvedPath()).toAbsolutePath();
realPath.checkAccess();
return realPath;
--- a/jdk/src/share/lib/logging.properties Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/lib/logging.properties Sun Apr 10 10:23:28 2011 -0700
@@ -43,6 +43,11 @@
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
+# Example to customize the SimpleFormatter output format
+# to print one-line log message like this:
+# <level>: <log message> [<date/time>]
+#
+# java.util.logging.SimpleFormatter.format=%4$s: %5$s [%1$tc]%n
############################################################
# Facility specific properties.
--- a/jdk/src/share/native/java/util/zip/Deflater.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/java/util/zip/Deflater.c Sun Apr 10 10:23:28 2011 -0700
@@ -129,34 +129,28 @@
if ((*env)->GetBooleanField(env, this, setParamsID)) {
int level = (*env)->GetIntField(env, this, levelID);
int strategy = (*env)->GetIntField(env, this, strategyID);
-
- in_buf = (jbyte *) malloc(this_len);
- if (in_buf == 0) {
+ in_buf = (*env)->GetPrimitiveArrayCritical(env, this_buf, 0);
+ if (in_buf == NULL) {
// Throw OOME only when length is not zero
if (this_len != 0)
JNU_ThrowOutOfMemoryError(env, 0);
return 0;
}
- (*env)->GetByteArrayRegion(env, this_buf, this_off, this_len, in_buf);
- out_buf = (jbyte *) malloc(len);
- if (out_buf == 0) {
- free(in_buf);
+ out_buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
+ if (out_buf == NULL) {
+ (*env)->ReleasePrimitiveArrayCritical(env, this_buf, in_buf, 0);
if (len != 0)
JNU_ThrowOutOfMemoryError(env, 0);
return 0;
}
- strm->next_in = (Bytef *) in_buf;
- strm->next_out = (Bytef *) out_buf;
+ strm->next_in = (Bytef *) (in_buf + this_off);
+ strm->next_out = (Bytef *) (out_buf + off);
strm->avail_in = this_len;
strm->avail_out = len;
res = deflateParams(strm, level, strategy);
-
- if (res == Z_OK) {
- (*env)->SetByteArrayRegion(env, b, off, len - strm->avail_out, out_buf);
- }
- free(out_buf);
- free(in_buf);
+ (*env)->ReleasePrimitiveArrayCritical(env, b, out_buf, 0);
+ (*env)->ReleasePrimitiveArrayCritical(env, this_buf, in_buf, 0);
switch (res) {
case Z_OK:
@@ -174,33 +168,28 @@
}
} else {
jboolean finish = (*env)->GetBooleanField(env, this, finishID);
- in_buf = (jbyte *) malloc(this_len);
- if (in_buf == 0) {
+ in_buf = (*env)->GetPrimitiveArrayCritical(env, this_buf, 0);
+ if (in_buf == NULL) {
if (this_len != 0)
JNU_ThrowOutOfMemoryError(env, 0);
return 0;
}
- (*env)->GetByteArrayRegion(env, this_buf, this_off, this_len, in_buf);
-
- out_buf = (jbyte *) malloc(len);
- if (out_buf == 0) {
- free(in_buf);
+ out_buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
+ if (out_buf == NULL) {
+ (*env)->ReleasePrimitiveArrayCritical(env, this_buf, in_buf, 0);
if (len != 0)
JNU_ThrowOutOfMemoryError(env, 0);
+
return 0;
}
- strm->next_in = (Bytef *) in_buf;
- strm->next_out = (Bytef *) out_buf;
+ strm->next_in = (Bytef *) (in_buf + this_off);
+ strm->next_out = (Bytef *) (out_buf + off);
strm->avail_in = this_len;
strm->avail_out = len;
res = deflate(strm, finish ? Z_FINISH : flush);
-
- if (res == Z_STREAM_END || res == Z_OK) {
- (*env)->SetByteArrayRegion(env, b, off, len - strm->avail_out, out_buf);
- }
- free(out_buf);
- free(in_buf);
+ (*env)->ReleasePrimitiveArrayCritical(env, b, out_buf, 0);
+ (*env)->ReleasePrimitiveArrayCritical(env, this_buf, in_buf, 0);
switch (res) {
case Z_STREAM_END:
--- a/jdk/src/share/native/java/util/zip/Inflater.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/java/util/zip/Inflater.c Sun Apr 10 10:23:28 2011 -0700
@@ -38,8 +38,6 @@
#include "zlib.h"
#include "java_util_zip_Inflater.h"
-#define MIN2(x, y) ((x) < (y) ? (x) : (y))
-
#define ThrowDataFormatException(env, msg) \
JNU_ThrowByName(env, "java/util/zip/DataFormatException", msg)
@@ -111,71 +109,50 @@
jarray b, jint off, jint len)
{
z_stream *strm = jlong_to_ptr(addr);
-
jarray this_buf = (jarray)(*env)->GetObjectField(env, this, bufID);
jint this_off = (*env)->GetIntField(env, this, offID);
jint this_len = (*env)->GetIntField(env, this, lenID);
+
jbyte *in_buf;
jbyte *out_buf;
int ret;
- /*
- * Avoid excess copying.
- * zlib stream usually has a few bytes of overhead for header info
- * (depends on the underlying data)
- *
- * (a) 5 bytes per 16KB
- * (b) 6 bytes for entire stream
- * (c) 4 bytes for gzip header
- * (d) 2 bytes for crc
- *
- * Use 20 bytes as the "safe cutoff" number.
- */
- jint in_len = MIN2(this_len, len + 20);
- jint consumed;
- in_buf = (jbyte *) malloc(in_len);
- if (in_buf == 0) {
- if (in_len != 0)
+ in_buf = (*env)->GetPrimitiveArrayCritical(env, this_buf, 0);
+ if (in_buf == NULL) {
+ if (this_len != 0)
JNU_ThrowOutOfMemoryError(env, 0);
return 0;
}
- (*env)->GetByteArrayRegion(env, this_buf, this_off, in_len, in_buf);
-
- out_buf = (jbyte *) malloc(len);
- if (out_buf == 0) {
- free(in_buf);
+ out_buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
+ if (out_buf == NULL) {
+ (*env)->ReleasePrimitiveArrayCritical(env, this_buf, in_buf, 0);
if (len != 0)
JNU_ThrowOutOfMemoryError(env, 0);
return 0;
}
-
- strm->next_in = (Bytef *) in_buf;
- strm->next_out = (Bytef *) out_buf;
- strm->avail_in = in_len;
+ strm->next_in = (Bytef *) (in_buf + this_off);
+ strm->next_out = (Bytef *) (out_buf + off);
+ strm->avail_in = this_len;
strm->avail_out = len;
ret = inflate(strm, Z_PARTIAL_FLUSH);
-
- if (ret == Z_STREAM_END || ret == Z_OK) {
- (*env)->SetByteArrayRegion(env, b, off, len - strm->avail_out, out_buf);
- }
- free(out_buf);
- free(in_buf);
+ (*env)->ReleasePrimitiveArrayCritical(env, b, out_buf, 0);
+ (*env)->ReleasePrimitiveArrayCritical(env, this_buf, in_buf, 0);
switch (ret) {
case Z_STREAM_END:
(*env)->SetBooleanField(env, this, finishedID, JNI_TRUE);
/* fall through */
case Z_OK:
- consumed = in_len - strm->avail_in;
- (*env)->SetIntField(env, this, offID, this_off + consumed);
- (*env)->SetIntField(env, this, lenID, this_len - consumed);
+ this_off += this_len - strm->avail_in;
+ (*env)->SetIntField(env, this, offID, this_off);
+ (*env)->SetIntField(env, this, lenID, strm->avail_in);
return len - strm->avail_out;
case Z_NEED_DICT:
(*env)->SetBooleanField(env, this, needDictID, JNI_TRUE);
/* Might have consumed some input here! */
- consumed = in_len - strm->avail_in;
- (*env)->SetIntField(env, this, offID, this_off + consumed);
- (*env)->SetIntField(env, this, lenID, this_len - consumed);
+ this_off += this_len - strm->avail_in;
+ (*env)->SetIntField(env, this, offID, this_off);
+ (*env)->SetIntField(env, this, lenID, strm->avail_in);
return 0;
case Z_BUF_ERROR:
return 0;
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageAffine.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageAffine.c Sun Apr 10 10:23:28 2011 -0700
@@ -210,6 +210,8 @@
t_ind = 4;
else if (type == MLIB_DOUBLE)
t_ind = 5;
+ else
+ return MLIB_FAILURE; /* unknown image type */
if (colormap != NULL && filter != MLIB_NEAREST) {
if (t_ind != 0 && t_ind != 1)
@@ -318,6 +320,10 @@
}
break;
+
+ default:
+ /* nothing to do for other edge types. */
+ break;
}
if (param_e->buff_malloc != NULL)
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageAffineEdge.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageAffineEdge.c Sun Apr 10 10:23:28 2011 -0700
@@ -616,6 +616,9 @@
MLIB_PROCESS_EDGES_ZERO(mlib_d64);
break;
}
+ default:
+ /* Image type MLIB_BIT is not used in java, so we can ignore it. */
+ break;
}
}
@@ -643,6 +646,9 @@
case MLIB_DOUBLE:
MLIB_PROCESS_EDGES(MLIB_EDGE_NEAREST_LINE, mlib_d64);
break;
+ default:
+ /* Image type MLIB_BIT is not used in java, so we can ignore it. */
+ break;
}
}
@@ -673,8 +679,11 @@
if (ltype == MLIB_BYTE) {
buff = mlib_malloc(channels * max_xsize);
}
- else {
+ else if (ltype == MLIB_SHORT) {
buff = mlib_malloc(channels * max_xsize * sizeof(mlib_s16));
+ } else {
+ /* Unsupported type of lookup table. Report a failure */
+ return MLIB_FAILURE;
}
if (buff == NULL)
@@ -691,6 +700,9 @@
srcStride >>= 1;
MLIB_PROCESS_EDGES(MLIB_EDGE_INDEX_u8i, mlib_s16);
break;
+ default:
+ /* Incompatible image type. Ignore it for now. */
+ break;
}
break;
@@ -705,9 +717,18 @@
srcStride >>= 1;
MLIB_PROCESS_EDGES(MLIB_EDGE_INDEX_s16i, mlib_s16);
break;
+ default:
+ /* Incompatible image type. Ignore it for now. */
+ break;
}
break;
+ default:
+ /* Unsupported type of lookup table.
+ * Can not be here due to check on line 685,
+ * so just ignore it.
+ */
+ break;
}
mlib_free(buff);
@@ -744,6 +765,10 @@
srcStride >>= 3;
MLIB_PROCESS_EDGES(MLIB_EDGE_BL, mlib_d64);
break;
+
+ default:
+ /* Image type MLIB_BIT is not supported, ignore it. */
+ break;
}
return MLIB_SUCCESS;
@@ -803,8 +828,11 @@
if (ltype == MLIB_BYTE) {
buff = mlib_malloc(channels * max_xsize);
}
- else {
+ else if (ltype == MLIB_SHORT) {
buff = mlib_malloc(channels * max_xsize * sizeof(mlib_s16));
+ } else {
+ /* Unsupported type of lookup table. */
+ return MLIB_FAILURE;
}
if (buff == NULL)
@@ -821,6 +849,9 @@
srcStride >>= 1;
MLIB_PROCESS_EDGES(MLIB_EDGE_INDEX_u8i, mlib_s16);
break;
+ default:
+ /* Ignore incomatible image type. */
+ break;
}
break;
@@ -835,9 +866,19 @@
srcStride >>= 1;
MLIB_PROCESS_EDGES(MLIB_EDGE_INDEX_s16i, mlib_s16);
break;
+ default:
+ /* Ignore incomatible image type. */
+ break;
}
break;
+
+ default:
+ /* Unsupported type of lookup table.
+ * Can not be here due to check on line 836,
+ * so just ignore it.
+ */
+ break;
}
mlib_free(buff);
@@ -895,6 +936,10 @@
}
break;
+
+ default:
+ /* Ignore unsupported image type MLIB_BIT */
+ break;
}
return MLIB_SUCCESS;
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageColorTrue2Index.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageColorTrue2Index.c Sun Apr 10 10:23:28 2011 -0700
@@ -2623,9 +2623,10 @@
return MLIB_FAILURE;
}
}
+ default:
+ /* Unsupported type of destination image */
+ return MLIB_FAILURE;
}
-
- break;
}
case MLIB_SHORT:
@@ -2678,18 +2679,15 @@
return MLIB_FAILURE;
}
}
+ default:
+ /* Unsupported type of destination image */
+ return MLIB_FAILURE;
}
-
- break;
}
default:
return MLIB_FAILURE;
}
-
- /* we need to return something to make Microsoft VC happy.
- Return FAILURE because on success we likely to return earlier. */
- return MLIB_FAILURE;
}
/***************************************************************/
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageConvMxN.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageConvMxN.c Sun Apr 10 10:23:28 2011 -0700
@@ -211,6 +211,13 @@
case MLIB_DOUBLE:
ret = mlib_convMxNnw_d64(dst_i, src_i, kernel, m, n, dm, dn, cmask);
break;
+
+ default:
+ /* For some reasons, there is no convolution routine for type MLIB_BIT.
+ * For now, we silently ignore it (because this image type is not used by java),
+ * but probably we have to report an error.
+ */
+ break;
}
}
@@ -221,6 +228,11 @@
case MLIB_EDGE_DST_COPY_SRC:
mlib_ImageConvCopyEdge(dst_e, src_e, dx_l, dx_r, dy_t, dy_b, cmask);
break;
+ default:
+ /* Other edge conditions do not need additional handling.
+ * Note also that they are not exposed in public Java API
+ */
+ break;
}
}
else { /* MLIB_EDGE_SRC_EXTEND */
@@ -279,6 +291,12 @@
case MLIB_DOUBLE:
mlib_convMxNext_d64(dst_e, src_e, kernel, m, n, dx_l, dx_r, dy_t, dy_b, cmask);
break;
+ default:
+ /* For some reasons, there is no convolution routine for type MLIB_BIT.
+ * For now, we silently ignore it (because this image type is not used by java),
+ * but probably we have to report an error.
+ */
+ break;
}
}
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_16ext.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_16ext.c Sun Apr 10 10:23:28 2011 -0700
@@ -1869,8 +1869,8 @@
/***************************************************************/
mlib_status CONV_FUNC_MxN
{
- DTYPE *adr_src, *sl, *sp;
- DTYPE *adr_dst, *dl, *dp;
+ DTYPE *adr_src, *sl, *sp = NULL;
+ DTYPE *adr_dst, *dl, *dp = NULL;
FTYPE buff[BUFF_SIZE], *buffs_arr[2*(MAX_N + 1)];
FTYPE **buffs = buffs_arr, *buffd;
FTYPE akernel[256], *k = akernel, fscale = DSCALE;
@@ -2332,8 +2332,8 @@
mlib_status CONV_FUNC_MxN_I
{
- DTYPE *adr_src, *sl, *sp;
- DTYPE *adr_dst, *dl, *dp;
+ DTYPE *adr_src, *sl, *sp = NULL;
+ DTYPE *adr_dst, *dl, *dp = NULL;
mlib_s32 buff[BUFF_SIZE], *buffs_arr[2*(MAX_N + 1)];
mlib_s32 *pbuff = buff;
mlib_s32 **buffs = buffs_arr, *buffd;
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_16nw.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_16nw.c Sun Apr 10 10:23:28 2011 -0700
@@ -148,8 +148,8 @@
/***************************************************************/
#define DEF_VARS(type) \
- type *adr_src, *sl, *sp; \
- type *adr_dst, *dl, *dp; \
+ type *adr_src, *sl, *sp = NULL; \
+ type *adr_dst, *dl, *dp = NULL; \
FTYPE *pbuff = buff; \
mlib_s32 wid, hgt, sll, dll; \
mlib_s32 nchannel, chan1; \
@@ -2060,8 +2060,8 @@
mlib_s32 d0, d1, shift1, shift2;
mlib_s32 k0, k1, k2, k3, k4, k5, k6;
mlib_s32 p0, p1, p2, p3, p4, p5, p6, p7;
- DTYPE *adr_src, *sl, *sp;
- DTYPE *adr_dst, *dl, *dp;
+ DTYPE *adr_src, *sl, *sp = NULL;
+ DTYPE *adr_dst, *dl, *dp = NULL;
mlib_s32 wid, hgt, sll, dll;
mlib_s32 nchannel, chan1;
mlib_s32 i, j, c;
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_32nw.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_32nw.c Sun Apr 10 10:23:28 2011 -0700
@@ -78,7 +78,7 @@
/***************************************************************/
#define DEF_VARS_MxN(type) \
GET_SRC_DST_PARAMETERS(type); \
- type *sl, *sp, *dl, *dp; \
+ type *sl, *sp = NULL, *dl, *dp = NULL; \
mlib_d64 *pbuff = buff; \
mlib_s32 i, j, c
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_8ext.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_8ext.c Sun Apr 10 10:23:28 2011 -0700
@@ -1869,8 +1869,8 @@
/***************************************************************/
mlib_status CONV_FUNC_MxN
{
- DTYPE *adr_src, *sl, *sp;
- DTYPE *adr_dst, *dl, *dp;
+ DTYPE *adr_src, *sl, *sp = NULL;
+ DTYPE *adr_dst, *dl, *dp = NULL;
FTYPE buff[BUFF_SIZE], *buffs_arr[2*(MAX_N + 1)];
FTYPE **buffs = buffs_arr, *buffd;
FTYPE akernel[256], *k = akernel, fscale = DSCALE;
@@ -2332,8 +2332,8 @@
mlib_status CONV_FUNC_MxN_I
{
- DTYPE *adr_src, *sl, *sp;
- DTYPE *adr_dst, *dl, *dp;
+ DTYPE *adr_src, *sl, *sp = NULL;
+ DTYPE *adr_dst, *dl, *dp = NULL;
mlib_s32 buff[BUFF_SIZE], *buffs_arr[2*(MAX_N + 1)];
mlib_s32 *pbuff = buff;
mlib_s32 **buffs = buffs_arr, *buffd;
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_8nw.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_8nw.c Sun Apr 10 10:23:28 2011 -0700
@@ -149,8 +149,8 @@
/***************************************************************/
#define DEF_VARS(type) \
- type *adr_src, *sl, *sp; \
- type *adr_dst, *dl, *dp; \
+ type *adr_src, *sl, *sp = NULL; \
+ type *adr_dst, *dl, *dp = NULL; \
FTYPE *pbuff = buff; \
mlib_s32 wid, hgt, sll, dll; \
mlib_s32 nchannel, chan1; \
@@ -2061,8 +2061,8 @@
mlib_s32 d0, d1, shift1, shift2;
mlib_s32 k0, k1, k2, k3, k4, k5, k6;
mlib_s32 p0, p1, p2, p3, p4, p5, p6, p7;
- DTYPE *adr_src, *sl, *sp;
- DTYPE *adr_dst, *dl, *dp;
+ DTYPE *adr_src, *sl, *sp = NULL;
+ DTYPE *adr_dst, *dl, *dp = NULL;
mlib_s32 wid, hgt, sll, dll;
mlib_s32 nchannel, chan1;
mlib_s32 i, j, c;
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_D64nw.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_D64nw.c Sun Apr 10 10:23:28 2011 -0700
@@ -71,8 +71,8 @@
#define DEF_VARS(type) \
GET_SRC_DST_PARAMETERS(type); \
type *sl; \
- type *dl, *dp; \
- mlib_s32 i, j, c
+ type *dl, *dp = NULL; \
+ mlib_s32 i = 0, j, c
/***************************************************************/
#undef KSIZE
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_F32nw.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_F32nw.c Sun Apr 10 10:23:28 2011 -0700
@@ -71,7 +71,7 @@
#define DEF_VARS(type) \
GET_SRC_DST_PARAMETERS(type); \
type *sl; \
- type *dl, *dp; \
+ type *dl, *dp = NULL; \
mlib_s32 i, j, c
/***************************************************************/
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_u16ext.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_u16ext.c Sun Apr 10 10:23:28 2011 -0700
@@ -1869,8 +1869,8 @@
/***************************************************************/
mlib_status CONV_FUNC_MxN
{
- DTYPE *adr_src, *sl, *sp;
- DTYPE *adr_dst, *dl, *dp;
+ DTYPE *adr_src, *sl, *sp = NULL;
+ DTYPE *adr_dst, *dl, *dp = NULL;
FTYPE buff[BUFF_SIZE], *buffs_arr[2*(MAX_N + 1)];
FTYPE **buffs = buffs_arr, *buffd;
FTYPE akernel[256], *k = akernel, fscale = DSCALE;
@@ -2332,8 +2332,8 @@
mlib_status CONV_FUNC_MxN_I
{
- DTYPE *adr_src, *sl, *sp;
- DTYPE *adr_dst, *dl, *dp;
+ DTYPE *adr_src, *sl, *sp = NULL;
+ DTYPE *adr_dst, *dl, *dp = NULL;
mlib_s32 buff[BUFF_SIZE], *buffs_arr[2*(MAX_N + 1)];
mlib_s32 *pbuff = buff;
mlib_s32 **buffs = buffs_arr, *buffd;
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_u16nw.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageConv_u16nw.c Sun Apr 10 10:23:28 2011 -0700
@@ -148,8 +148,8 @@
/***************************************************************/
#define DEF_VARS(type) \
- type *adr_src, *sl, *sp; \
- type *adr_dst, *dl, *dp; \
+ type *adr_src, *sl, *sp = NULL; \
+ type *adr_dst, *dl, *dp = NULL; \
FTYPE *pbuff = buff; \
mlib_s32 wid, hgt, sll, dll; \
mlib_s32 nchannel, chan1; \
@@ -2060,8 +2060,8 @@
mlib_s32 d0, d1, shift1, shift2;
mlib_s32 k0, k1, k2, k3, k4, k5, k6;
mlib_s32 p0, p1, p2, p3, p4, p5, p6, p7;
- DTYPE *adr_src, *sl, *sp;
- DTYPE *adr_dst, *dl, *dp;
+ DTYPE *adr_src, *sl, *sp = NULL;
+ DTYPE *adr_dst, *dl, *dp = NULL;
mlib_s32 wid, hgt, sll, dll;
mlib_s32 nchannel, chan1;
mlib_s32 i, j, c;
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageCopy_Bit.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageCopy_Bit.c Sun Apr 10 10:23:28 2011 -0700
@@ -204,9 +204,9 @@
mlib_u64 *dp; /* 8-byte aligned start points in dst */
mlib_u64 *sp; /* 8-byte aligned start point in src */
mlib_s32 j; /* offset of address in dst */
- mlib_u64 lmask0 = 0xFFFFFFFFFFFFFFFF;
+ mlib_u64 lmask0 = 0xFFFFFFFFFFFFFFFFULL;
mlib_u64 dmask;
- mlib_u64 lsrc, lsrc0, lsrc1, ldst;
+ mlib_u64 lsrc, lsrc0, lsrc1 = 0ULL, ldst;
mlib_s32 ls_offset, ld_offset, shift;
if (size <= 0) return;
@@ -427,9 +427,9 @@
mlib_u64 *dp; /* 8-byte aligned start points in dst */
mlib_u64 *sp; /* 8-byte aligned start point in src */
mlib_s32 j; /* offset of address in dst */
- mlib_u64 lmask0 = 0xFFFFFFFFFFFFFFFF;
+ mlib_u64 lmask0 = 0xFFFFFFFFFFFFFFFFULL;
mlib_u64 dmask;
- mlib_u64 lsrc, lsrc0, lsrc1, ldst;
+ mlib_u64 lsrc, lsrc0, lsrc1 = 0ULL, ldst;
mlib_s32 ls_offset, ld_offset, shift;
if (size <= 0) return;
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageCreate.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageCreate.c Sun Apr 10 10:23:28 2011 -0700
@@ -334,7 +334,7 @@
mlib_s32 width; /* for parent image */
mlib_s32 height; /* for parent image */
mlib_s32 stride;
- mlib_s32 bitoffset;
+ mlib_s32 bitoffset = 0;
void *data;
/* sanity check */
@@ -423,7 +423,7 @@
mlib_s32 channels = src -> channels;
mlib_s32 stride = src -> stride;
mlib_u8 *data = src -> data;
- mlib_s32 bitoffset;
+ mlib_s32 bitoffset = 0;
data += y * stride;
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/solaris/bin/arm/jvm.cfg Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,38 @@
+# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+# List of JVMs that can be used as an option to java, javac, etc.
+# Order is important -- first in this list is the default JVM.
+# NOTE that this both this file and its format are UNSUPPORTED and
+# WILL GO AWAY in a future release.
+#
+# You may also select a JVM in an arbitrary location with the
+# "-XXaltjvm=<jvm_dir>" option, but that too is unsupported
+# and may not be available in a future release.
+#
+-client KNOWN
+-server KNOWN
+-hotspot ERROR
+-classic WARN
+-native ERROR
+-green ERROR
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/solaris/bin/ppc/jvm.cfg Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,38 @@
+# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+# List of JVMs that can be used as an option to java, javac, etc.
+# Order is important -- first in this list is the default JVM.
+# NOTE that this both this file and its format are UNSUPPORTED and
+# WILL GO AWAY in a future release.
+#
+# You may also select a JVM in an arbitrary location with the
+# "-XXaltjvm=<jvm_dir>" option, but that too is unsupported
+# and may not be available in a future release.
+#
+-client KNOWN
+-server KNOWN
+-hotspot ERROR
+-classic WARN
+-native ERROR
+-green ERROR
--- a/jdk/src/solaris/classes/sun/awt/X11/XRobotPeer.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XRobotPeer.java Sun Apr 10 10:23:28 2011 -0700
@@ -48,7 +48,7 @@
}
public void dispose() {
- // does nothing
+ _dispose();
}
public void mouseMove(int x, int y) {
@@ -88,6 +88,7 @@
}
private static native synchronized void setup(int numberOfButtons, int[] buttonDownMasks);
+ private static native synchronized void _dispose();
private static native synchronized void mouseMoveImpl(X11GraphicsConfig xgc, int x, int y);
private static native synchronized void mousePressImpl(int buttons);
--- a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -135,6 +135,12 @@
noisyAwtHandler = AccessController.doPrivileged(new GetBooleanAction("sun.awt.noisyerrorhandler"));
}
+ /*
+ * Return (potentially) platform specific display timeout for the
+ * tray icon
+ */
+ static native long getTrayIconDisplayTimeout();
+
//---- ERROR HANDLER CODE ----//
/*
@@ -1222,8 +1228,8 @@
public PrintJob getPrintJob(final Frame frame, final String doctitle,
final Properties props) {
- if (GraphicsEnvironment.isHeadless()) {
- throw new IllegalArgumentException();
+ if (frame == null) {
+ throw new NullPointerException("frame must not be null");
}
PrintJob2D printJob = new PrintJob2D(frame, doctitle, props);
@@ -1236,11 +1242,10 @@
public PrintJob getPrintJob(final Frame frame, final String doctitle,
final JobAttributes jobAttributes,
- final PageAttributes pageAttributes) {
-
-
- if (GraphicsEnvironment.isHeadless()) {
- throw new IllegalArgumentException();
+ final PageAttributes pageAttributes)
+ {
+ if (frame == null) {
+ throw new NullPointerException("frame must not be null");
}
PrintJob2D printJob = new PrintJob2D(frame, doctitle,
--- a/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -230,7 +230,7 @@
// Wait till the EmbeddedFrame is reparented
long start = System.currentTimeMillis();
- final long PERIOD = 2000L;
+ final long PERIOD = XToolkit.getTrayIconDisplayTimeout();
XToolkit.awtLock();
try {
while (!isTrayIconDisplayed) {
--- a/jdk/src/solaris/classes/sun/java2d/xr/XRPMBlitLoops.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/solaris/classes/sun/java2d/xr/XRPMBlitLoops.java Sun Apr 10 10:23:28 2011 -0700
@@ -143,7 +143,8 @@
Blit swToSurfaceBlit = Blit.getFromCache(src.getSurfaceType(), CompositeType.SrcNoEa, vImgSurfaceType);
XRSurfaceData vImgSurface = (XRSurfaceData) vImg.getDestSurface();
- swToSurfaceBlit.Blit(src, vImgSurface, null, null, sx, sy, 0, 0, w, h);
+ swToSurfaceBlit.Blit(src, vImgSurface, AlphaComposite.Src, null,
+ sx, sy, 0, 0, w, h);
return vImgSurface;
}
--- a/jdk/src/solaris/classes/sun/nio/fs/LinuxFileSystemProvider.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/solaris/classes/sun/nio/fs/LinuxFileSystemProvider.java Sun Apr 10 10:23:28 2011 -0700
@@ -56,11 +56,11 @@
{
if (type == DosFileAttributeView.class) {
return (V) new LinuxDosFileAttributeView(UnixPath.toUnixPath(obj),
- followLinks(options));
+ Util.followLinks(options));
}
if (type == UserDefinedFileAttributeView.class) {
return (V) new LinuxUserDefinedFileAttributeView(UnixPath.toUnixPath(obj),
- followLinks(options));
+ Util.followLinks(options));
}
return super.getFileAttributeView(obj, type, options);
}
@@ -72,11 +72,11 @@
{
if (name.equals("dos")) {
return new LinuxDosFileAttributeView(UnixPath.toUnixPath(obj),
- followLinks(options));
+ Util.followLinks(options));
}
if (name.equals("user")) {
return new LinuxUserDefinedFileAttributeView(UnixPath.toUnixPath(obj),
- followLinks(options));
+ Util.followLinks(options));
}
return super.getFileAttributeView(obj, name, options);
}
--- a/jdk/src/solaris/classes/sun/nio/fs/SolarisFileSystemProvider.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/solaris/classes/sun/nio/fs/SolarisFileSystemProvider.java Sun Apr 10 10:23:28 2011 -0700
@@ -57,11 +57,11 @@
{
if (type == AclFileAttributeView.class) {
return (V) new SolarisAclFileAttributeView(UnixPath.toUnixPath(obj),
- followLinks(options));
+ Util.followLinks(options));
}
if (type == UserDefinedFileAttributeView.class) {
return(V) new SolarisUserDefinedFileAttributeView(UnixPath.toUnixPath(obj),
- followLinks(options));
+ Util.followLinks(options));
}
return super.getFileAttributeView(obj, type, options);
}
@@ -73,10 +73,10 @@
{
if (name.equals("acl"))
return new SolarisAclFileAttributeView(UnixPath.toUnixPath(obj),
- followLinks(options));
+ Util.followLinks(options));
if (name.equals("user"))
return new SolarisUserDefinedFileAttributeView(UnixPath.toUnixPath(obj),
- followLinks(options));
+ Util.followLinks(options));
return super.getFileAttributeView(obj, name, options);
}
}
--- a/jdk/src/solaris/classes/sun/nio/fs/UnixFileSystemProvider.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/solaris/classes/sun/nio/fs/UnixFileSystemProvider.java Sun Apr 10 10:23:28 2011 -0700
@@ -105,20 +105,6 @@
return (UnixPath)obj;
}
- boolean followLinks(LinkOption... options) {
- boolean followLinks = true;
- for (LinkOption option: options) {
- if (option == LinkOption.NOFOLLOW_LINKS) {
- followLinks = false;
- continue;
- }
- if (option == null)
- throw new NullPointerException();
- throw new AssertionError("Should not get here");
- }
- return followLinks;
- }
-
@Override
@SuppressWarnings("unchecked")
public <V extends FileAttributeView> V getFileAttributeView(Path obj,
@@ -126,7 +112,7 @@
LinkOption... options)
{
UnixPath file = UnixPath.toUnixPath(obj);
- boolean followLinks = followLinks(options);
+ boolean followLinks = Util.followLinks(options);
if (type == BasicFileAttributeView.class)
return (V) UnixFileAttributeViews.createBasicView(file, followLinks);
if (type == PosixFileAttributeView.class)
@@ -163,7 +149,7 @@
LinkOption... options)
{
UnixPath file = UnixPath.toUnixPath(obj);
- boolean followLinks = followLinks(options);
+ boolean followLinks = Util.followLinks(options);
if (name.equals("basic"))
return UnixFileAttributeViews.createBasicView(file, followLinks);
if (name.equals("posix"))
--- a/jdk/src/solaris/classes/sun/nio/fs/UnixPath.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/solaris/classes/sun/nio/fs/UnixPath.java Sun Apr 10 10:23:28 2011 -0700
@@ -819,13 +819,13 @@
}
@Override
- public Path toRealPath(boolean resolveLinks) throws IOException {
+ public Path toRealPath(LinkOption... options) throws IOException {
checkRead();
UnixPath absolute = toAbsolutePath();
- // if resolveLinks is true then use realpath
- if (resolveLinks) {
+ // if resolving links then use realpath
+ if (Util.followLinks(options)) {
try {
byte[] rp = realpath(absolute);
return new UnixPath(getFileSystem(), rp);
@@ -834,7 +834,7 @@
}
}
- // if resolveLinks is false then eliminate "." and also ".."
+ // if not resolving links then eliminate "." and also ".."
// where the previous element is not a link.
UnixPath result = fs.rootDirectory();
for (int i=0; i<absolute.getNameCount(); i++) {
--- a/jdk/src/solaris/classes/sun/nio/fs/UnixSecureDirectoryStream.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/solaris/classes/sun/nio/fs/UnixSecureDirectoryStream.java Sun Apr 10 10:23:28 2011 -0700
@@ -81,20 +81,6 @@
return (UnixPath)obj;
}
- private boolean followLinks(LinkOption... options) {
- boolean followLinks = true;
- for (LinkOption option: options) {
- if (option == LinkOption.NOFOLLOW_LINKS) {
- followLinks = false;
- continue;
- }
- if (option == null)
- throw new NullPointerException();
- throw new AssertionError("Should not get here");
- }
- return followLinks;
- }
-
/**
* Opens sub-directory in this directory
*/
@@ -105,7 +91,7 @@
{
UnixPath file = getName(obj);
UnixPath child = ds.directory().resolve(file);
- boolean followLinks = followLinks(options);
+ boolean followLinks = Util.followLinks(options);
// permission check using name resolved against original path of directory
SecurityManager sm = System.getSecurityManager();
@@ -316,7 +302,7 @@
LinkOption... options)
{
UnixPath file = getName(obj);
- boolean followLinks = followLinks(options);
+ boolean followLinks = Util.followLinks(options);
return getFileAttributeViewImpl(file, type, followLinks);
}
--- a/jdk/src/solaris/native/java/lang/java_props_md.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/solaris/native/java/lang/java_props_md.c Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -55,6 +55,11 @@
#endif
#endif
+#ifdef JAVASE_EMBEDDED
+#include <dlfcn.h>
+#include <sys/stat.h>
+#endif
+
/* Take an array of string pairs (map of key->value) and a string (key).
* Examine each pair in the map to see if the first string (key) matches the
* string. If so, store the second string of the pair (value) in the value and
@@ -304,6 +309,36 @@
return 1;
}
+#ifdef JAVASE_EMBEDDED
+/* Determine the default embedded toolkit based on whether lib/xawt/
+ * exists in the JRE. This can still be overridden by -Dawt.toolkit=XXX
+ */
+static char* getEmbeddedToolkit() {
+ Dl_info dlinfo;
+ char buf[MAXPATHLEN];
+ int32_t len;
+ char *p;
+ struct stat statbuf;
+
+ /* Get address of this library and the directory containing it. */
+ dladdr((void *)getEmbeddedToolkit, &dlinfo);
+ realpath((char *)dlinfo.dli_fname, buf);
+ len = strlen(buf);
+ p = strrchr(buf, '/');
+ /* Default AWT Toolkit on Linux and Solaris is XAWT. */
+ strncpy(p, "/xawt/", MAXPATHLEN-len-1);
+ /* Check if it exists */
+ if (stat(buf, &statbuf) == -1 && errno == ENOENT) {
+ /* No - this is a reduced-headless-jre so use special HToolkit */
+ return "sun.awt.HToolkit";
+ }
+ else {
+ /* Yes - this is a headful JRE so fallback to SE defaults */
+ return NULL;
+ }
+}
+#endif
+
/* This function gets called very early, before VM_CALLS are setup.
* Do not use any of the VM_CALLS entries!!!
*/
@@ -328,7 +363,12 @@
/* Java 2D properties */
sprops.graphics_env = "sun.awt.X11GraphicsEnvironment";
- sprops.awt_toolkit = NULL;
+
+#ifdef JAVASE_EMBEDDED
+ sprops.awt_toolkit = getEmbeddedToolkit();
+ if (sprops.awt_toolkit == NULL) // default as below
+#endif
+ sprops.awt_toolkit = "sun.awt.X11.XToolkit";
/* This is used only for debugging of font problems. */
v = getenv("JAVA2D_FONTPATH");
--- a/jdk/src/solaris/native/sun/awt/awt_Robot.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/solaris/native/sun/awt/awt_Robot.c Sun Apr 10 10:23:28 2011 -0700
@@ -48,12 +48,28 @@
#ifdef __linux__
#include <sys/socket.h>
#endif
+#include <dlfcn.h>
extern struct X11GraphicsConfigIDs x11GraphicsConfigIDs;
static jint * masks;
static jint num_buttons;
+static unsigned int s_robotInstanceCounter = 0;
+
+static void* xcompositeLibHandle = NULL;
+static Bool xcompositeExtAvailable = False;
+static Bool xcompositeExtTested = False;
+
+typedef Status (*T_XCompositeQueryVersion)(Display *dpy, int *major_versionp, int *minor_versionp);
+typedef Window (*T_XCompositeGetOverlayWindow)(Display *dpy, Window window);
+typedef void (*T_XCompositeReleaseOverlayWindow)(Display *dpy, Window window);
+
+static T_XCompositeQueryVersion XCompositeQueryVersion = NULL;
+static T_XCompositeGetOverlayWindow XCompositeGetOverlayWindow = NULL;
+static T_XCompositeReleaseOverlayWindow XCompositeReleaseOverlayWindow = NULL;
+
+
static int32_t isXTestAvailable() {
int32_t major_opcode, first_event, first_error;
int32_t event_basep, error_basep, majorp, minorp;
@@ -194,8 +210,80 @@
}
AWT_UNLOCK();
+
+ s_robotInstanceCounter++;
+}
+
+JNIEXPORT void JNICALL
+Java_sun_awt_X11_XRobotPeer__1dispose (JNIEnv * env, jclass cls)
+{
+ if (--s_robotInstanceCounter) {
+ return;
+ }
+
+ // This is the last instance of the XRobotPeer being released
+
+ if (xcompositeExtTested && xcompositeExtAvailable && xcompositeLibHandle) {
+ // The lib is loaded in IsXCompositeAvailable(). Unload under AWT_LOCK
+ // so that the shutdown function of the lib behaves correctly.
+ AWT_LOCK();
+ dlclose(xcompositeLibHandle);
+ AWT_UNLOCK();
+ }
+
+ xcompositeExtTested = False;
+ xcompositeExtAvailable = False;
+ xcompositeLibHandle = NULL;
}
+/*
+ * Returns True only if XCOMPOSITE is of version 0.3 or higher.
+ * The functions that we need are available since that version.
+ *
+ * Must be invoked under AWT_LOCK.
+ *
+ * Leaves the library loaded if the version is correct.
+ */
+static Bool IsXCompositeAvailable()
+{
+ if (!xcompositeExtTested) {
+ int opcode, eventb, errorb;
+
+ if (XQueryExtension(awt_display, "Composite", &opcode, &eventb, &errorb)) {
+ xcompositeLibHandle = dlopen("libXcomposite.so.1", RTLD_LAZY | RTLD_GLOBAL);
+#ifndef __linux__ /* SOLARIS */
+ if (xcompositeLibHandle == NULL) {
+ xcompositeLibHandle = dlopen("/usr/sfw/lib/libXcomposite.so.1",
+ RTLD_LAZY | RTLD_GLOBAL);
+ }
+#endif
+
+ if (xcompositeLibHandle) {
+ int major, minor;
+ XCompositeQueryVersion = (T_XCompositeQueryVersion)dlsym(xcompositeLibHandle, "XCompositeQueryVersion");
+
+ if (XCompositeQueryVersion && XCompositeQueryVersion(awt_display, &major, &minor)) {
+ if (major >= 0 && minor >= 3) {
+ XCompositeGetOverlayWindow = (T_XCompositeGetOverlayWindow)dlsym(xcompositeLibHandle, "XCompositeGetOverlayWindow");
+ XCompositeReleaseOverlayWindow = (T_XCompositeReleaseOverlayWindow)dlsym(xcompositeLibHandle, "XCompositeReleaseOverlayWindow");
+
+ if (XCompositeGetOverlayWindow && XCompositeReleaseOverlayWindow) {
+ xcompositeExtAvailable = True;
+ }
+ }
+ }
+
+ if (!xcompositeExtAvailable) {
+ dlclose(xcompositeLibHandle);
+ } /* else the lib is unloaded in _dispose() */
+ }
+ }
+
+ xcompositeExtTested = True;
+ }
+
+ return xcompositeExtAvailable;
+}
JNIEXPORT void JNICALL
Java_sun_awt_X11_XRobotPeer_getRGBPixelsImpl( JNIEnv *env,
@@ -211,7 +299,7 @@
jint *ary; /* Array of jints for sending pixel values back
* to parent process.
*/
- Window rootWindow;
+ Window window;
AwtGraphicsConfigDataPtr adata;
DTRACE_PRINTLN6("RobotPeer: getRGBPixelsImpl(%lx, %d, %d, %d, %d, %x)", xgc, x, y, width, height, pixelArray);
@@ -228,14 +316,24 @@
adata = (AwtGraphicsConfigDataPtr) JNU_GetLongFieldAsPtr(env, xgc, x11GraphicsConfigIDs.aData);
DASSERT(adata != NULL);
- rootWindow = XRootWindow(awt_display, adata->awt_visInfo.screen);
- image = getWindowImage(awt_display, rootWindow, x, y, width, height);
+ window = XRootWindow(awt_display, adata->awt_visInfo.screen);
+
+ if (IsXCompositeAvailable()) {
+ // Use 'composite overlay window' instead of the root window.
+ // See 6903034 for details.
+ window = XCompositeGetOverlayWindow(awt_display, window);
+ }
+
+ image = getWindowImage(awt_display, window, x, y, width, height);
/* Array to use to crunch around the pixel values */
ary = (jint *) malloc(width * height * sizeof (jint));
if (ary == NULL) {
JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError");
XDestroyImage(image);
+ if (IsXCompositeAvailable()) {
+ XCompositeReleaseOverlayWindow(awt_display, window);
+ }
AWT_UNLOCK();
return;
}
@@ -256,6 +354,9 @@
free(ary);
XDestroyImage(image);
+ if (IsXCompositeAvailable()) {
+ XCompositeReleaseOverlayWindow(awt_display, window);
+ }
AWT_UNLOCK();
}
--- a/jdk/src/solaris/native/sun/awt/jawt.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/solaris/native/sun/awt/jawt.c Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -33,6 +33,10 @@
*/
JNIEXPORT jboolean JNICALL JAWT_GetAWT(JNIEnv* env, JAWT* awt)
{
+#if defined(JAVASE_EMBEDDED) && defined(HEADLESS)
+ /* there are no AWT libs available at all */
+ return JNI_FALSE;
+#else
if (awt == NULL) {
return JNI_FALSE;
}
@@ -51,4 +55,5 @@
}
return JNI_TRUE;
+#endif
}
--- a/jdk/src/solaris/native/sun/java2d/x11/XRBackendNative.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/solaris/native/sun/java2d/x11/XRBackendNative.c Sun Apr 10 10:23:28 2011 -0700
@@ -644,7 +644,7 @@
for (i=0; i < glyphCnt; i++) {
GlyphInfo *jginfo = (GlyphInfo *) jlong_to_ptr(glyphInfoPtrs[i]);
- gid[i] = (Glyph) (0xffffffff & ((unsigned int) jginfo->cellInfo));
+ gid[i] = (Glyph) (0x0ffffffffL & ((unsigned long)(jginfo->cellInfo)));
xginfo[i].x = (-jginfo->topLeftX);
xginfo[i].y = (-jginfo->topLeftY);
xginfo[i].width = jginfo->width;
@@ -666,16 +666,56 @@
JNIEXPORT void JNICALL
Java_sun_java2d_xr_XRBackendNative_XRFreeGlyphsNative
(JNIEnv *env, jclass cls, jint glyphSet, jintArray gidArray, jint glyphCnt) {
- jint *gids;
- int i;
- if ((gids = (jint *) (*env)->GetPrimitiveArrayCritical(env, gidArray, NULL)) == NULL) {
+ /* The glyph ids are 32 bit but may be stored in a 64 bit long on
+ * a 64 bit architecture. So optimise the 32 bit case to avoid
+ * extra stack or heap allocations by directly referencing the
+ * underlying Java array and only allocate on 64 bit.
+ */
+ if (sizeof(jint) == sizeof(Glyph)) {
+ jint *gids =
+ (*env)->GetPrimitiveArrayCritical(env, gidArray, NULL);
+ if (gids == NULL) {
+ return;
+ } else {
+ XRenderFreeGlyphs(awt_display,
+ (GlyphSet)glyphSet, (Glyph *)gids, glyphCnt);
+ (*env)->ReleasePrimitiveArrayCritical(env, gidArray,
+ gids, JNI_ABORT);
+ }
return;
- }
+ } else {
+ Glyph stack_ids[64];
+ Glyph *gids = NULL;
+ jint* jgids = NULL;
+ int i;
- XRenderFreeGlyphs (awt_display, (GlyphSet) glyphSet, (Glyph *) gids, glyphCnt);
-
- (*env)->ReleasePrimitiveArrayCritical(env, gidArray, gids, JNI_ABORT);
+ if (glyphCnt <= 64) {
+ gids = stack_ids;
+ } else {
+ gids = (Glyph *)malloc(sizeof(Glyph) * glyphCnt);
+ if (gids == NULL) {
+ return;
+ }
+ }
+ jgids = (*env)->GetPrimitiveArrayCritical(env, gidArray, NULL);
+ if (jgids == NULL) {
+ if (gids != stack_ids) {
+ free(gids);
+ }
+ return;
+ }
+ for (i=0; i < glyphCnt; i++) {
+ gids[i] = jgids[i];
+ }
+ XRenderFreeGlyphs(awt_display,
+ (GlyphSet) glyphSet, gids, glyphCnt);
+ (*env)->ReleasePrimitiveArrayCritical(env, gidArray,
+ jgids, JNI_ABORT);
+ if (gids != stack_ids) {
+ free(gids);
+ }
+ }
}
JNIEXPORT jint JNICALL
@@ -692,9 +732,9 @@
jint *ids;
jint *elts;
XGlyphElt32 *xelts;
- Glyph *xids;
+ unsigned int *xids;
XGlyphElt32 selts[24];
- Glyph sids[256];
+ unsigned int sids[256];
int charCnt = 0;
if (eltCnt <= 24) {
@@ -709,7 +749,7 @@
if (glyphCnt <= 256) {
xids = &sids[0];
} else {
- xids = (Glyph *) malloc(sizeof(Glyph) * glyphCnt);
+ xids = (unsigned int*)malloc(sizeof(unsigned int) * glyphCnt);
if (xids == NULL) {
if (xelts != &selts[0]) {
free(xelts);
@@ -742,7 +782,7 @@
}
for (i=0; i < glyphCnt; i++) {
- xids[i] = (Glyph) ids[i];
+ xids[i] = ids[i];
}
for (i=0; i < eltCnt; i++) {
@@ -750,7 +790,7 @@
xelts[i].xOff = elts[i*4 + 1];
xelts[i].yOff = elts[i*4 + 2];
xelts[i].glyphset = (GlyphSet) elts[i*4 + 3];
- xelts[i].chars = (unsigned int *) &xids[charCnt];
+ xelts[i].chars = &xids[charCnt];
charCnt += xelts[i].nchars;
}
--- a/jdk/src/solaris/native/sun/xawt/XToolkit.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/solaris/native/sun/xawt/XToolkit.c Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -112,6 +112,21 @@
/*
* Class: sun_awt_X11_XToolkit
+ * Method: getTrayIconDisplayTimeout
+ * Signature: ()J
+ */
+JNIEXPORT jlong JNICALL Java_sun_awt_X11_XToolkit_getTrayIconDisplayTimeout
+ (JNIEnv *env, jclass clazz)
+{
+#ifndef JAVASE_EMBEDDED
+ return (jlong) 2000;
+#else
+ return (jlong) 10000;
+#endif
+}
+
+/*
+ * Class: sun_awt_X11_XToolkit
* Method: getDefaultXColormap
* Signature: ()J
*/
@@ -340,15 +355,34 @@
#define AWT_READPIPE (awt_pipe_fds[0])
#define AWT_WRITEPIPE (awt_pipe_fds[1])
-#define DEF_AWT_MAX_POLL_TIMEOUT ((uint32_t)500) /* milliseconds */
+#ifdef JAVASE_EMBEDDED
+ #define DEF_AWT_MAX_POLL_TIMEOUT ((uint32_t)4000000000) /* milliseconds */
+#else
+ #define DEF_AWT_MAX_POLL_TIMEOUT ((uint32_t)500) /* milliseconds */
+#endif
+
#define DEF_AWT_FLUSH_TIMEOUT ((uint32_t)100) /* milliseconds */
#define AWT_MIN_POLL_TIMEOUT ((uint32_t)0) /* milliseconds */
#define TIMEOUT_TIMEDOUT 0
#define TIMEOUT_EVENTS 1
+/* awt_poll_alg - AWT Poll Events Aging Algorithms */
+#define AWT_POLL_FALSE 1
+#define AWT_POLL_AGING_SLOW 2
+#define AWT_POLL_AGING_FAST 3
+
+#define AWT_POLL_THRESHOLD 1000 // msec, Block if delay is larger
+#define AWT_POLL_BLOCK -1 // cause poll() block
+
// Static fields
+#ifdef JAVASE_EMBEDDED
+ static int awt_poll_alg = AWT_POLL_AGING_FAST;
+#else
+ static int awt_poll_alg = AWT_POLL_AGING_SLOW;
+#endif
+
static uint32_t AWT_FLUSH_TIMEOUT = DEF_AWT_FLUSH_TIMEOUT; /* milliseconds */
static uint32_t AWT_MAX_POLL_TIMEOUT = DEF_AWT_MAX_POLL_TIMEOUT; /* milliseconds */
static pthread_t awt_MainThread = 0;
@@ -417,6 +451,7 @@
*/
static void readEnv() {
char * value;
+ int tmp_poll_alg;
static Boolean env_read = False;
if (env_read) return;
@@ -451,6 +486,23 @@
if (static_poll_timeout != 0) {
curPollTimeout = static_poll_timeout;
}
+
+ // non-blocking poll()
+ value = getenv("_AWT_POLL_ALG");
+ if (value != NULL) {
+ tmp_poll_alg = atoi(value);
+ switch(tmp_poll_alg) {
+ case AWT_POLL_FALSE:
+ case AWT_POLL_AGING_SLOW:
+ case AWT_POLL_AGING_FAST:
+ awt_poll_alg = tmp_poll_alg;
+ break;
+ default:
+ PRINT("Unknown value of _AWT_POLL_ALG, assuming Slow Aging Algorithm by default");
+ awt_poll_alg = AWT_POLL_AGING_SLOW;
+ break;
+ }
+ }
}
/**
@@ -478,14 +530,29 @@
if (static_poll_timeout != 0) return;
// Update it otherwise
- if (timeout_control == TIMEOUT_TIMEDOUT) {
- /* add 1/4 (plus 1, in case the division truncates to 0) */
- curPollTimeout += ((curPollTimeout>>2) + 1);
- curPollTimeout = min(AWT_MAX_POLL_TIMEOUT, curPollTimeout);
- } else if (timeout_control == TIMEOUT_EVENTS) {
- /* subtract 1/4 (plus 1, in case the division truncates to 0) */
- curPollTimeout -= ((curPollTimeout>>2) + 1);
- curPollTimeout = max(AWT_MIN_POLL_TIMEOUT, curPollTimeout);
+
+ switch(awt_poll_alg) {
+ case AWT_POLL_AGING_SLOW:
+ if (timeout_control == TIMEOUT_TIMEDOUT) {
+ /* add 1/4 (plus 1, in case the division truncates to 0) */
+ curPollTimeout += ((curPollTimeout>>2) + 1);
+ curPollTimeout = min(AWT_MAX_POLL_TIMEOUT, curPollTimeout);
+ } else if (timeout_control == TIMEOUT_EVENTS) {
+ /* subtract 1/4 (plus 1, in case the division truncates to 0) */
+ curPollTimeout -= ((curPollTimeout>>2) + 1);
+ curPollTimeout = max(AWT_MIN_POLL_TIMEOUT, curPollTimeout);
+ }
+ break;
+ case AWT_POLL_AGING_FAST:
+ if (timeout_control == TIMEOUT_TIMEDOUT) {
+ curPollTimeout += ((curPollTimeout>>2) + 1);
+ curPollTimeout = min(AWT_MAX_POLL_TIMEOUT, curPollTimeout);
+ if((int)curPollTimeout > AWT_POLL_THRESHOLD || (int)curPollTimeout == AWT_POLL_BLOCK)
+ curPollTimeout = AWT_POLL_BLOCK;
+ } else if (timeout_control == TIMEOUT_EVENTS) {
+ curPollTimeout = max(AWT_MIN_POLL_TIMEOUT, 1);
+ }
+ break;
}
}
@@ -497,16 +564,37 @@
*/
static uint32_t get_poll_timeout(jlong nextTaskTime)
{
+ uint32_t ret_timeout;
+ uint32_t timeout;
+ uint32_t taskTimeout;
+ uint32_t flushTimeout;
+
jlong curTime = awtJNI_TimeMillis();
- uint32_t timeout = curPollTimeout;
- uint32_t taskTimeout = (nextTaskTime == -1) ? AWT_MAX_POLL_TIMEOUT : (uint32_t)max(0, (int32_t)(nextTaskTime - curTime));
- uint32_t flushTimeout = (awt_next_flush_time > 0) ? (uint32_t)max(0, (int32_t)(awt_next_flush_time - curTime)) : AWT_MAX_POLL_TIMEOUT;
+ timeout = curPollTimeout;
+ switch(awt_poll_alg) {
+ case AWT_POLL_AGING_SLOW:
+ case AWT_POLL_AGING_FAST:
+ taskTimeout = (nextTaskTime == -1) ? AWT_MAX_POLL_TIMEOUT : (uint32_t)max(0, (int32_t)(nextTaskTime - curTime));
+ flushTimeout = (awt_next_flush_time > 0) ? (uint32_t)max(0, (int32_t)(awt_next_flush_time - curTime)) : AWT_MAX_POLL_TIMEOUT;
+
+ PRINT2("to: %d, ft: %d, to: %d, tt: %d, mil: %d\n", taskTimeout, flushTimeout, timeout, (int)nextTaskTime, (int)curTime);
- PRINT2("to: %d, ft: %d, to: %d, tt: %d, mil: %d\n", taskTimeout, flushTimeout, timeout, (int)nextTaskTime, (int)curTime);
+ // Adjust timeout to flush_time and task_time
+ ret_timeout = min(flushTimeout, min(taskTimeout, timeout));
+ if((int)curPollTimeout == AWT_POLL_BLOCK)
+ ret_timeout = AWT_POLL_BLOCK;
+ break;
- // Adjust timeout to flush_time and task_time
- return min(flushTimeout, min(taskTimeout, timeout));
-} /* awt_get_poll_timeout() */
+ case AWT_POLL_FALSE:
+ ret_timeout = (nextTaskTime > curTime) ?
+ (nextTaskTime - curTime) :
+ ((nextTaskTime == -1) ? -1 : 0);
+ break;
+ }
+
+ return ret_timeout;
+
+} /* get_poll_timeout() */
/*
* Waits for X/Xt events to appear on the pipe. Returns only when
@@ -598,6 +686,8 @@
if (result == 0) {
/* poll() timed out -- update timeout value */
update_poll_timeout(TIMEOUT_TIMEDOUT);
+ PRINT2("%s(): TIMEOUT_TIMEDOUT curPollTimeout = %d \n",
+ performPoll, curPollTimeout);
}
if (pollFds[1].revents) {
int count;
@@ -606,10 +696,14 @@
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);
}
if (pollFds[0].revents) {
// Events in X pipe
update_poll_timeout(TIMEOUT_EVENTS);
+ PRINT2("%s(): TIMEOUT_EVENTS curPollTimeout = %ld \n",
+ performPoll, curPollTimeout);
}
return;
--- a/jdk/src/windows/classes/sun/awt/Win32GraphicsEnvironment.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/classes/sun/awt/Win32GraphicsEnvironment.java Sun Apr 10 10:23:28 2011 -0700
@@ -39,12 +39,8 @@
import java.util.StringTokenizer;
import sun.awt.DisplayChangedListener;
import sun.awt.SunDisplayChanger;
-import sun.awt.windows.WFontConfiguration;
import sun.awt.windows.WPrinterJob;
import sun.awt.windows.WToolkit;
-import sun.font.FontManager;
-import sun.font.FontManagerFactory;
-import sun.font.SunFontManager;
import sun.java2d.SunGraphicsEnvironment;
import sun.java2d.SurfaceManagerFactory;
import sun.java2d.WindowsSurfaceManagerFactory;
@@ -231,20 +227,6 @@
return device;
}
- // Implements SunGraphicsEnvironment.createFontConfiguration.
- protected FontConfiguration createFontConfiguration() {
- FontConfiguration fc = new WFontConfiguration(SunFontManager.getInstance());
- fc.init();
- return fc;
- }
-
- public FontConfiguration createFontConfiguration(boolean preferLocaleFonts,
- boolean preferPropFonts) {
-
- return new WFontConfiguration(SunFontManager.getInstance(),
- preferLocaleFonts,preferPropFonts);
- }
-
public boolean isDisplayLocal() {
return true;
}
--- a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java Sun Apr 10 10:23:28 2011 -0700
@@ -630,10 +630,10 @@
public PrintJob getPrintJob(Frame frame, String doctitle,
JobAttributes jobAttributes,
- PageAttributes pageAttributes) {
-
- if (GraphicsEnvironment.isHeadless()) {
- throw new IllegalArgumentException();
+ PageAttributes pageAttributes)
+ {
+ if (frame == null) {
+ throw new NullPointerException("frame must not be null");
}
PrintJob2D printJob = new PrintJob2D(frame, doctitle,
--- a/jdk/src/windows/classes/sun/awt/windows/fontconfig.properties Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/fontconfig.properties Sun Apr 10 10:23:28 2011 -0700
@@ -102,28 +102,28 @@
monospaced.plain.alphabetic=Courier New
monospaced.plain.chinese-ms950=MingLiU
monospaced.plain.chinese-ms950-extb=MingLiU-ExtB
-monospaced.plain.hebrew=David
+monospaced.plain.hebrew=Courier New
monospaced.plain.japanese=MS Gothic
monospaced.plain.korean=GulimChe
monospaced.bold.alphabetic=Courier New Bold
monospaced.bold.chinese-ms950=PMingLiU
monospaced.bold.chinese-ms950-extb=PMingLiU-ExtB
-monospaced.bold.hebrew=David Bold
+monospaced.bold.hebrew=Courier New Bold
monospaced.bold.japanese=MS Gothic
monospaced.bold.korean=GulimChe
monospaced.italic.alphabetic=Courier New Italic
monospaced.italic.chinese-ms950=PMingLiU
monospaced.italic.chinese-ms950-extb=PMingLiU-ExtB
-monospaced.italic.hebrew=David
+monospaced.italic.hebrew=Courier New
monospaced.italic.japanese=MS Gothic
monospaced.italic.korean=GulimChe
monospaced.bolditalic.alphabetic=Courier New Bold Italic
monospaced.bolditalic.chinese-ms950=PMingLiU
monospaced.bolditalic.chinese-ms950-extb=PMingLiU-ExtB
-monospaced.bolditalic.hebrew=David Bold
+monospaced.bolditalic.hebrew=Courier New Bold
monospaced.bolditalic.japanese=MS Gothic
monospaced.bolditalic.korean=GulimChe
--- a/jdk/src/windows/classes/sun/nio/fs/WindowsFileSystemProvider.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/classes/sun/nio/fs/WindowsFileSystemProvider.java Sun Apr 10 10:23:28 2011 -0700
@@ -150,20 +150,6 @@
}
}
- private boolean followLinks(LinkOption... options) {
- boolean followLinks = true;
- for (LinkOption option: options) {
- if (option == LinkOption.NOFOLLOW_LINKS) {
- followLinks = false;
- continue;
- }
- if (option == null)
- throw new NullPointerException();
- throw new AssertionError("Should not get here");
- }
- return followLinks;
- }
-
@Override
@SuppressWarnings("unchecked")
public <V extends FileAttributeView> V
@@ -172,7 +158,7 @@
WindowsPath file = WindowsPath.toWindowsPath(obj);
if (view == null)
throw new NullPointerException();
- boolean followLinks = followLinks(options);
+ boolean followLinks = Util.followLinks(options);
if (view == BasicFileAttributeView.class)
return (V) WindowsFileAttributeViews.createBasicView(file, followLinks);
if (view == DosFileAttributeView.class)
@@ -209,7 +195,7 @@
@Override
public DynamicFileAttributeView getFileAttributeView(Path obj, String name, LinkOption... options) {
WindowsPath file = WindowsPath.toWindowsPath(obj);
- boolean followLinks = followLinks(options);
+ boolean followLinks = Util.followLinks(options);
if (name.equals("basic"))
return WindowsFileAttributeViews.createBasicView(file, followLinks);
if (name.equals("dos"))
--- a/jdk/src/windows/classes/sun/nio/fs/WindowsPath.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/classes/sun/nio/fs/WindowsPath.java Sun Apr 10 10:23:28 2011 -0700
@@ -831,9 +831,9 @@
}
@Override
- public WindowsPath toRealPath(boolean resolveLinks) throws IOException {
+ public WindowsPath toRealPath(LinkOption... options) throws IOException {
checkRead();
- String rp = WindowsLinkSupport.getRealPath(this, resolveLinks);
+ String rp = WindowsLinkSupport.getRealPath(this, Util.followLinks(options));
return createFromNormalizedPath(getFileSystem(), rp);
}
--- a/jdk/src/windows/native/com/sun/management/OperatingSystem_md.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/com/sun/management/OperatingSystem_md.c Sun Apr 10 10:23:28 2011 -0700
@@ -30,6 +30,7 @@
#include "management.h"
#include "com_sun_management_OperatingSystem.h"
+#include <psapi.h>
#include <errno.h>
#include <stdlib.h>
@@ -53,41 +54,12 @@
return result;
}
-// From psapi.h
-typedef struct _PROCESS_MEMORY_COUNTERS {
- DWORD cb;
- DWORD PageFaultCount;
- SIZE_T PeakWorkingSetSize;
- SIZE_T WorkingSetSize;
- SIZE_T QuotaPeakPagedPoolUsage;
- SIZE_T QuotaPagedPoolUsage;
- SIZE_T QuotaPeakNonPagedPoolUsage;
- SIZE_T QuotaNonPagedPoolUsage;
- SIZE_T PagefileUsage;
- SIZE_T PeakPagefileUsage;
-} PROCESS_MEMORY_COUNTERS;
-
-static HINSTANCE hInstPsapi = NULL;
-typedef BOOL (WINAPI *LPFNGETPROCESSMEMORYINFO)(HANDLE, PROCESS_MEMORY_COUNTERS*, DWORD);
-
-static jboolean is_nt = JNI_FALSE;
static HANDLE main_process;
JNIEXPORT void JNICALL
Java_com_sun_management_OperatingSystem_initialize
(JNIEnv *env, jclass cls)
{
- OSVERSIONINFO oi;
- oi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
- GetVersionEx(&oi);
- switch(oi.dwPlatformId) {
- case VER_PLATFORM_WIN32_WINDOWS: is_nt = JNI_FALSE; break;
- case VER_PLATFORM_WIN32_NT: is_nt = JNI_TRUE; break;
- default:
- throw_internal_error(env, "Unsupported Platform");
- return;
- }
-
main_process = GetCurrentProcess();
}
@@ -95,31 +67,12 @@
Java_com_sun_management_OperatingSystem_getCommittedVirtualMemorySize0
(JNIEnv *env, jobject mbean)
{
-
- /*
- * In bytes. NT/2000/XP only - using GetProcessMemoryInfo from psapi.dll
- */
- static LPFNGETPROCESSMEMORYINFO lpfnGetProcessMemoryInfo = NULL;
- static volatile jboolean psapi_inited = JNI_FALSE;
PROCESS_MEMORY_COUNTERS pmc;
-
- if (!is_nt) return -1;
-
- if (!psapi_inited) {
- psapi_inited = JNI_TRUE;
- if ((hInstPsapi = LoadLibrary("PSAPI.DLL")) == NULL) return -1;
- if ((lpfnGetProcessMemoryInfo = (LPFNGETPROCESSMEMORYINFO)
- GetProcAddress( hInstPsapi, "GetProcessMemoryInfo")) == NULL) {
- FreeLibrary(hInstPsapi);
- return -1;
- }
+ if (GetProcessMemoryInfo(main_process, &pmc, sizeof(PROCESS_MEMORY_COUNTERS)) == 0) {
+ return (jlong)-1L;
+ } else {
+ return (jlong) pmc.PagefileUsage;
}
-
- if (lpfnGetProcessMemoryInfo == NULL) return -1;
-
- lpfnGetProcessMemoryInfo(main_process, &pmc,
- sizeof(PROCESS_MEMORY_COUNTERS));
- return (jlong) pmc.PagefileUsage;
}
JNIEXPORT jlong JNICALL
@@ -148,20 +101,15 @@
FILETIME process_creation_time, process_exit_time,
process_user_time, process_kernel_time;
- // Windows NT only
- if (is_nt) {
- // Using static variables declared above
- // Units are 100-ns intervals. Convert to ns.
- GetProcessTimes(main_process, &process_creation_time,
- &process_exit_time,
- &process_kernel_time, &process_user_time);
- return (jlong_from(process_user_time.dwHighDateTime,
- process_user_time.dwLowDateTime) +
- jlong_from(process_kernel_time.dwHighDateTime,
- process_kernel_time.dwLowDateTime)) * 100;
- } else {
- return -1;
- }
+ // Using static variables declared above
+ // Units are 100-ns intervals. Convert to ns.
+ GetProcessTimes(main_process, &process_creation_time,
+ &process_exit_time,
+ &process_kernel_time, &process_user_time);
+ return (jlong_from(process_user_time.dwHighDateTime,
+ process_user_time.dwLowDateTime) +
+ jlong_from(process_kernel_time.dwHighDateTime,
+ process_kernel_time.dwLowDateTime)) * 100;
}
JNIEXPORT jlong JNICALL
--- a/jdk/src/windows/native/java/io/WinNTFileSystem_md.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/java/io/WinNTFileSystem_md.c Sun Apr 10 10:23:28 2011 -0700
@@ -23,9 +23,9 @@
* questions.
*/
-/* Access APIs for Win2K and above */
+/* Access APIs for WinXP and above */
#ifndef _WIN32_WINNT
-#define _WIN32_WINNT 0x0500
+#define _WIN32_WINNT 0x0501
#endif
#include <assert.h>
@@ -60,13 +60,17 @@
JNIEXPORT void JNICALL
Java_java_io_WinNTFileSystem_initIDs(JNIEnv *env, jclass cls)
{
- HANDLE handle;
+ HMODULE handle;
jclass fileClass = (*env)->FindClass(env, "java/io/File");
if (!fileClass) return;
ids.path =
(*env)->GetFieldID(env, fileClass, "path", "Ljava/lang/String;");
- handle = LoadLibrary("kernel32");
- if (handle != NULL) {
+
+ // GetFinalPathNameByHandle requires Windows Vista or newer
+ if (GetModuleHandleExW((GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
+ GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT),
+ (LPCWSTR)&CreateFileW, &handle) != 0)
+ {
GetFinalPathNameByHandle_func = (GetFinalPathNameByHandleProc)
GetProcAddress(handle, "GetFinalPathNameByHandleW");
}
@@ -824,8 +828,6 @@
return ret;
}
-typedef BOOL (WINAPI* GetVolumePathNameProc) (LPCWSTR, LPWSTR, DWORD);
-
JNIEXPORT jlong JNICALL
Java_java_io_WinNTFileSystem_getSpace0(JNIEnv *env, jobject this,
jobject file, jint t)
@@ -834,14 +836,7 @@
jlong rv = 0L;
WCHAR *pathbuf = fileToNTPath(env, file, ids.path);
- HMODULE h = LoadLibrary("kernel32");
- GetVolumePathNameProc getVolumePathNameW = NULL;
- if (h) {
- getVolumePathNameW
- = (GetVolumePathNameProc)GetProcAddress(h, "GetVolumePathNameW");
- }
-
- if (getVolumePathNameW(pathbuf, volname, MAX_PATH_LENGTH)) {
+ if (GetVolumePathNameW(pathbuf, volname, MAX_PATH_LENGTH)) {
ULARGE_INTEGER totalSpace, freeSpace, usableSpace;
if (GetDiskFreeSpaceExW(volname, &usableSpace, &totalSpace, &freeSpace)) {
switch(t) {
@@ -860,9 +855,6 @@
}
}
- if (h) {
- FreeLibrary(h);
- }
free(pathbuf);
return rv;
}
--- a/jdk/src/windows/native/java/lang/java_props_md.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/java/lang/java_props_md.c Sun Apr 10 10:23:28 2011 -0700
@@ -196,42 +196,23 @@
/*
* Code to figure out the user's home directory using shell32.dll
*/
-typedef HRESULT (WINAPI *GetSpecialFolderType)(HWND, int, LPITEMIDLIST *);
-typedef BOOL (WINAPI *GetPathFromIDListType)(LPCITEMIDLIST, LPSTR);
-
WCHAR*
getHomeFromShell32()
{
- HMODULE lib = LoadLibraryW(L"SHELL32.DLL");
- GetSpecialFolderType do_get_folder;
- GetPathFromIDListType do_get_path;
HRESULT rc;
LPITEMIDLIST item_list = 0;
WCHAR *p;
WCHAR path[MAX_PATH+1];
int size = MAX_PATH+1;
- if (lib == 0) {
- // We can't load the library !!??
- return NULL;
- }
-
- do_get_folder = (GetSpecialFolderType)GetProcAddress(lib, "SHGetSpecialFolderLocation");
- do_get_path = (GetPathFromIDListType)GetProcAddress(lib, "SHGetPathFromIDListW");
-
- if (do_get_folder == 0 || do_get_path == 0) {
- // the library doesn't hold the right functions !!??
- return NULL;
- }
-
- rc = (*do_get_folder)(NULL, CSIDL_DESKTOPDIRECTORY, &item_list);
+ rc = SHGetSpecialFolderLocation(NULL, CSIDL_DESKTOPDIRECTORY, &item_list);
if (!SUCCEEDED(rc)) {
// we can't find the shell folder.
return NULL;
}
path[0] = 0;
- (*do_get_path)(item_list, (LPSTR)path);
+ SHGetPathFromIDListW(item_list, (LPWSTR)path);
/* Get the parent of Desktop directory */
p = wcsrchr(path, L'\\');
@@ -253,17 +234,7 @@
static boolean
haveMMX(void)
{
- boolean mmx = 0;
- HMODULE lib = LoadLibrary("KERNEL32");
- if (lib != NULL) {
- BOOL (WINAPI *isProcessorFeaturePresent)(DWORD) =
- (BOOL (WINAPI *)(DWORD))
- GetProcAddress(lib, "IsProcessorFeaturePresent");
- if (isProcessorFeaturePresent != NULL)
- mmx = isProcessorFeaturePresent(PF_MMX_INSTRUCTIONS_AVAILABLE);
- FreeLibrary(lib);
- }
- return mmx;
+ return IsProcessorFeaturePresent(PF_MMX_INSTRUCTIONS_AVAILABLE);
}
static const char *
@@ -532,10 +503,19 @@
if (uname != NULL && wcslen(uname) > 0) {
sprops.user_name = _wcsdup(uname);
} else {
- WCHAR buf[100];
- int buflen = sizeof(buf);
- sprops.user_name =
- GetUserNameW(buf, &buflen) ? _wcsdup(buf) : L"unknown";
+ DWORD buflen = 0;
+ if (GetUserNameW(NULL, &buflen) == 0 &&
+ GetLastError() == ERROR_INSUFFICIENT_BUFFER)
+ {
+ uname = (WCHAR*)malloc(buflen * sizeof(WCHAR));
+ if (uname != NULL && GetUserNameW(uname, &buflen) == 0) {
+ free(uname);
+ uname = NULL;
+ }
+ } else {
+ uname = NULL;
+ }
+ sprops.user_name = (uname != NULL) ? uname : L"unknown";
}
}
@@ -633,8 +613,8 @@
/* Current directory */
{
WCHAR buf[MAX_PATH];
- GetCurrentDirectoryW(sizeof(buf), buf);
- sprops.user_dir = _wcsdup(buf);
+ if (GetCurrentDirectoryW(sizeof(buf)/sizeof(WCHAR), buf) != 0)
+ sprops.user_dir = _wcsdup(buf);
}
sprops.file_separator = "\\";
--- a/jdk/src/windows/native/java/net/Inet6AddressImpl.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/java/net/Inet6AddressImpl.c Sun Apr 10 10:23:28 2011 -0700
@@ -90,6 +90,7 @@
jobjectArray ret = 0;
int retLen = 0;
jboolean preferIPv6Address;
+ static jfieldID ia_preferIPv6AddressID;
int error=0;
struct addrinfo hints, *res, *resNew = NULL;
@@ -116,166 +117,163 @@
hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE);
CHECK_NULL_RETURN(hostname, NULL);
- if (NET_addrtransAvailable()) {
- static jfieldID ia_preferIPv6AddressID;
- if (ia_preferIPv6AddressID == NULL) {
- jclass c = (*env)->FindClass(env,"java/net/InetAddress");
- if (c) {
- ia_preferIPv6AddressID =
- (*env)->GetStaticFieldID(env, c, "preferIPv6Address", "Z");
- }
- if (ia_preferIPv6AddressID == NULL) {
- JNU_ReleaseStringPlatformChars(env, host, hostname);
- return NULL;
- }
+ if (ia_preferIPv6AddressID == NULL) {
+ jclass c = (*env)->FindClass(env,"java/net/InetAddress");
+ if (c) {
+ ia_preferIPv6AddressID =
+ (*env)->GetStaticFieldID(env, c, "preferIPv6Address", "Z");
}
- /* get the address preference */
- preferIPv6Address
- = (*env)->GetStaticBooleanField(env, ia_class, ia_preferIPv6AddressID);
-
- /* Try once, with our static buffer. */
- memset(&hints, 0, sizeof(hints));
- hints.ai_flags = AI_CANONNAME;
- hints.ai_family = AF_UNSPEC;
-
- error = (*getaddrinfo_ptr)(hostname, NULL, &hints, &res);
-
- if (error) {
- /* report error */
- JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException",
- (char *)hostname);
+ if (ia_preferIPv6AddressID == NULL) {
JNU_ReleaseStringPlatformChars(env, host, hostname);
return NULL;
- } else {
- int i = 0;
- int inetCount = 0, inet6Count = 0, inetIndex, inet6Index;
- struct addrinfo *itr, *last, *iterator = res;
- while (iterator != NULL) {
- int skip = 0;
- itr = resNew;
- while (itr != NULL) {
- if (iterator->ai_family == itr->ai_family &&
- iterator->ai_addrlen == itr->ai_addrlen) {
- if (itr->ai_family == AF_INET) { /* AF_INET */
- struct sockaddr_in *addr1, *addr2;
- addr1 = (struct sockaddr_in *)iterator->ai_addr;
- addr2 = (struct sockaddr_in *)itr->ai_addr;
- if (addr1->sin_addr.s_addr ==
- addr2->sin_addr.s_addr) {
- skip = 1;
- break;
- }
- } else {
- int t;
- struct sockaddr_in6 *addr1, *addr2;
- addr1 = (struct sockaddr_in6 *)iterator->ai_addr;
- addr2 = (struct sockaddr_in6 *)itr->ai_addr;
+ }
+ }
+ /* get the address preference */
+ preferIPv6Address
+ = (*env)->GetStaticBooleanField(env, ia_class, ia_preferIPv6AddressID);
+
+ /* Try once, with our static buffer. */
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_flags = AI_CANONNAME;
+ hints.ai_family = AF_UNSPEC;
+
+ error = getaddrinfo(hostname, NULL, &hints, &res);
- for (t = 0; t < 16; t++) {
- if (addr1->sin6_addr.s6_addr[t] !=
- addr2->sin6_addr.s6_addr[t]) {
- break;
- }
- }
- if (t < 16) {
- itr = itr->ai_next;
- continue;
- } else {
- skip = 1;
+ if (error) {
+ /* report error */
+ JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException",
+ (char *)hostname);
+ JNU_ReleaseStringPlatformChars(env, host, hostname);
+ return NULL;
+ } else {
+ int i = 0;
+ int inetCount = 0, inet6Count = 0, inetIndex, inet6Index;
+ struct addrinfo *itr, *last, *iterator = res;
+ while (iterator != NULL) {
+ int skip = 0;
+ itr = resNew;
+ while (itr != NULL) {
+ if (iterator->ai_family == itr->ai_family &&
+ iterator->ai_addrlen == itr->ai_addrlen) {
+ if (itr->ai_family == AF_INET) { /* AF_INET */
+ struct sockaddr_in *addr1, *addr2;
+ addr1 = (struct sockaddr_in *)iterator->ai_addr;
+ addr2 = (struct sockaddr_in *)itr->ai_addr;
+ if (addr1->sin_addr.s_addr ==
+ addr2->sin_addr.s_addr) {
+ skip = 1;
+ break;
+ }
+ } else {
+ int t;
+ struct sockaddr_in6 *addr1, *addr2;
+ addr1 = (struct sockaddr_in6 *)iterator->ai_addr;
+ addr2 = (struct sockaddr_in6 *)itr->ai_addr;
+
+ for (t = 0; t < 16; t++) {
+ if (addr1->sin6_addr.s6_addr[t] !=
+ addr2->sin6_addr.s6_addr[t]) {
break;
}
}
- } else if (iterator->ai_family != AF_INET &&
- iterator->ai_family != AF_INET6) {
- /* we can't handle other family types */
- skip = 1;
- break;
- }
- itr = itr->ai_next;
- }
-
- if (!skip) {
- struct addrinfo *next
- = (struct addrinfo*) malloc(sizeof(struct addrinfo));
- if (!next) {
- JNU_ThrowOutOfMemoryError(env, "heap allocation failed");
- ret = NULL;
- goto cleanupAndReturn;
+ if (t < 16) {
+ itr = itr->ai_next;
+ continue;
+ } else {
+ skip = 1;
+ break;
+ }
}
- memcpy(next, iterator, sizeof(struct addrinfo));
- next->ai_next = NULL;
- if (resNew == NULL) {
- resNew = next;
- } else {
- last->ai_next = next;
- }
- last = next;
- i++;
- if (iterator->ai_family == AF_INET) {
- inetCount ++;
- } else if (iterator->ai_family == AF_INET6) {
- inet6Count ++;
- }
+ } else if (iterator->ai_family != AF_INET &&
+ iterator->ai_family != AF_INET6) {
+ /* we can't handle other family types */
+ skip = 1;
+ break;
}
- iterator = iterator->ai_next;
- }
- retLen = i;
- iterator = resNew;
- i = 0;
- ret = (*env)->NewObjectArray(env, retLen, ni_iacls, NULL);
-
- if (IS_NULL(ret)) {
- /* we may have memory to free at the end of this */
- goto cleanupAndReturn;
+ itr = itr->ai_next;
}
- if (preferIPv6Address) {
- inetIndex = inet6Count;
- inet6Index = 0;
- } else {
- inetIndex = 0;
- inet6Index = inetCount;
- }
-
- while (iterator != NULL) {
- if (iterator->ai_family == AF_INET) {
- jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
- if (IS_NULL(iaObj)) {
+ if (!skip) {
+ struct addrinfo *next
+ = (struct addrinfo*) malloc(sizeof(struct addrinfo));
+ if (!next) {
+ JNU_ThrowOutOfMemoryError(env, "heap allocation failed");
ret = NULL;
goto cleanupAndReturn;
- }
- (*env)->SetIntField(env, iaObj, ni_iaaddressID,
- ntohl(((struct sockaddr_in*)iterator->ai_addr)->sin_addr.s_addr));
- (*env)->SetObjectField(env, iaObj, ni_iahostID, host);
- (*env)->SetObjectArrayElement(env, ret, inetIndex, iaObj);
- inetIndex ++;
+ }
+ memcpy(next, iterator, sizeof(struct addrinfo));
+ next->ai_next = NULL;
+ if (resNew == NULL) {
+ resNew = next;
+ } else {
+ last->ai_next = next;
+ }
+ last = next;
+ i++;
+ if (iterator->ai_family == AF_INET) {
+ inetCount ++;
} else if (iterator->ai_family == AF_INET6) {
- jint scope = 0;
- jbyteArray ipaddress;
- jobject iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
- if (IS_NULL(iaObj)) {
- ret = NULL;
- goto cleanupAndReturn;
- }
- ipaddress = (*env)->NewByteArray(env, 16);
- if (IS_NULL(ipaddress)) {
- ret = NULL;
- goto cleanupAndReturn;
- }
- (*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
- (jbyte *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));
- scope = ((struct sockaddr_in6*)iterator->ai_addr)->sin6_scope_id;
- if (scope != 0) { /* zero is default value, no need to set */
- (*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
- (*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
- }
- (*env)->SetObjectField(env, iaObj, ni_ia6ipaddressID, ipaddress);
- (*env)->SetObjectField(env, iaObj, ni_iahostID, host);
- (*env)->SetObjectArrayElement(env, ret, inet6Index, iaObj);
- inet6Index ++;
+ inet6Count ++;
}
- iterator = iterator->ai_next;
}
+ iterator = iterator->ai_next;
+ }
+ retLen = i;
+ iterator = resNew;
+ i = 0;
+ ret = (*env)->NewObjectArray(env, retLen, ni_iacls, NULL);
+
+ if (IS_NULL(ret)) {
+ /* we may have memory to free at the end of this */
+ goto cleanupAndReturn;
+ }
+
+ if (preferIPv6Address) {
+ inetIndex = inet6Count;
+ inet6Index = 0;
+ } else {
+ inetIndex = 0;
+ inet6Index = inetCount;
+ }
+
+ while (iterator != NULL) {
+ if (iterator->ai_family == AF_INET) {
+ jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
+ if (IS_NULL(iaObj)) {
+ ret = NULL;
+ goto cleanupAndReturn;
+ }
+ (*env)->SetIntField(env, iaObj, ni_iaaddressID,
+ ntohl(((struct sockaddr_in*)iterator->ai_addr)->sin_addr.s_addr));
+ (*env)->SetObjectField(env, iaObj, ni_iahostID, host);
+ (*env)->SetObjectArrayElement(env, ret, inetIndex, iaObj);
+ inetIndex ++;
+ } else if (iterator->ai_family == AF_INET6) {
+ jint scope = 0;
+ jbyteArray ipaddress;
+ jobject iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
+ if (IS_NULL(iaObj)) {
+ ret = NULL;
+ goto cleanupAndReturn;
+ }
+ ipaddress = (*env)->NewByteArray(env, 16);
+ if (IS_NULL(ipaddress)) {
+ ret = NULL;
+ goto cleanupAndReturn;
+ }
+ (*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
+ (jbyte *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));
+ scope = ((struct sockaddr_in6*)iterator->ai_addr)->sin6_scope_id;
+ if (scope != 0) { /* zero is default value, no need to set */
+ (*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
+ (*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
+ }
+ (*env)->SetObjectField(env, iaObj, ni_ia6ipaddressID, ipaddress);
+ (*env)->SetObjectField(env, iaObj, ni_iahostID, host);
+ (*env)->SetObjectArrayElement(env, ret, inet6Index, iaObj);
+ inet6Index ++;
+ }
+ iterator = iterator->ai_next;
}
}
@@ -291,8 +289,7 @@
JNU_ReleaseStringPlatformChars(env, host, hostname);
}
- if (NET_addrtransAvailable())
- (*freeaddrinfo_ptr)(res);
+ freeaddrinfo(res);
return ret;
}
@@ -312,44 +309,41 @@
int len = 0;
jbyte caddr[16];
- if (NET_addrtransAvailable()) {
- struct sockaddr_in him4;
- struct sockaddr_in6 him6;
- struct sockaddr *sa;
+ struct sockaddr_in him4;
+ struct sockaddr_in6 him6;
+ struct sockaddr *sa;
+ /*
+ * For IPv4 addresses construct a sockaddr_in structure.
+ */
+ if ((*env)->GetArrayLength(env, addrArray) == 4) {
+ jint addr;
+ (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
+ addr = ((caddr[0]<<24) & 0xff000000);
+ addr |= ((caddr[1] <<16) & 0xff0000);
+ addr |= ((caddr[2] <<8) & 0xff00);
+ addr |= (caddr[3] & 0xff);
+ memset((char *) &him4, 0, sizeof(him4));
+ him4.sin_addr.s_addr = (uint32_t) htonl(addr);
+ him4.sin_family = AF_INET;
+ sa = (struct sockaddr *) &him4;
+ len = sizeof(him4);
+ } else {
/*
- * For IPv4 addresses construct a sockaddr_in structure.
+ * For IPv6 address construct a sockaddr_in6 structure.
*/
- if ((*env)->GetArrayLength(env, addrArray) == 4) {
- jint addr;
- (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
- addr = ((caddr[0]<<24) & 0xff000000);
- addr |= ((caddr[1] <<16) & 0xff0000);
- addr |= ((caddr[2] <<8) & 0xff00);
- addr |= (caddr[3] & 0xff);
- memset((char *) &him4, 0, sizeof(him4));
- him4.sin_addr.s_addr = (uint32_t) htonl(addr);
- him4.sin_family = AF_INET;
- sa = (struct sockaddr *) &him4;
- len = sizeof(him4);
- } else {
- /*
- * For IPv6 address construct a sockaddr_in6 structure.
- */
- (*env)->GetByteArrayRegion(env, addrArray, 0, 16, caddr);
- memset((char *) &him6, 0, sizeof(him6));
- memcpy((void *)&(him6.sin6_addr), caddr, sizeof(struct in6_addr) );
- him6.sin6_family = AF_INET6;
- sa = (struct sockaddr *) &him6 ;
- len = sizeof(him6) ;
- }
+ (*env)->GetByteArrayRegion(env, addrArray, 0, 16, caddr);
+ memset((char *) &him6, 0, sizeof(him6));
+ memcpy((void *)&(him6.sin6_addr), caddr, sizeof(struct in6_addr) );
+ him6.sin6_family = AF_INET6;
+ sa = (struct sockaddr *) &him6 ;
+ len = sizeof(him6) ;
+ }
- error = (*getnameinfo_ptr)(sa, len, host, NI_MAXHOST, NULL, 0,
- NI_NAMEREQD);
+ error = getnameinfo(sa, len, host, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
- if (!error) {
- ret = (*env)->NewStringUTF(env, host);
- }
+ if (!error) {
+ ret = (*env)->NewStringUTF(env, host);
}
if (ret == NULL) {
--- a/jdk/src/windows/native/java/net/NetworkInterface.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/java/net/NetworkInterface.c Sun Apr 10 10:23:28 2011 -0700
@@ -53,36 +53,6 @@
* order and this ensures consistent device number across invocations.
*/
-
-/* IP helper library routines */
-int (PASCAL FAR *GetIpAddrTable_fn)();
-int (PASCAL FAR *GetIfTable_fn)();
-int (PASCAL FAR *GetFriendlyIfIndex_fn)();
-int (PASCAL FAR *GetAdaptersAddresses_fn)();
-int (PASCAL FAR *GetAdaptersInfo_fn)();
-int (PASCAL FAR *GetNumberOfInterfaces_fn)();
-
-/* Enumeration routines */
-typedef int (*EnumerateNetInterfaces)(JNIEnv *, netif **);
-typedef int(*EnumerateNetAddresses)(JNIEnv *, netif *, netaddr **);
-
-static EnumerateNetInterfaces enumInterfaces_fn;
-static EnumerateNetAddresses enumAddresses_fn;
-
-/* Windows 9x routines are external (not needed on 64-bit) */
-#ifndef _WIN64
-extern int enumInterfaces_win9x(JNIEnv *, netif **);
-extern int enumAddresses_win9x(JNIEnv *, netif *, netaddr **);
-extern int init_win9x(void);
-#endif
-
-
-/* Windows 95/98/ME running */
-static jboolean isW9x;
-
-/* Windows version supports */
-static jboolean os_supports_ipv6;
-
/* various JNI ids */
jclass ni_class; /* NetworkInterface */
@@ -154,10 +124,10 @@
*/
size = sizeof(MIB_IFTABLE);
tableP = (MIB_IFTABLE *)malloc(size);
- count = (*GetIfTable_fn)(tableP, &size, TRUE);
+ count = GetIfTable(tableP, &size, TRUE);
if (count == ERROR_INSUFFICIENT_BUFFER || count == ERROR_BUFFER_OVERFLOW) {
tableP = (MIB_IFTABLE *)realloc(tableP, size);
- count = (*GetIfTable_fn)(tableP, &size, TRUE);
+ count = GetIfTable(tableP, &size, TRUE);
}
if (count != NO_ERROR) {
@@ -172,7 +142,7 @@
/*
* Warning the real index is obtained by GetFriendlyIfIndex()
*/
- ifindex = (*GetFriendlyIfIndex_fn)(ifrowP->dwIndex);
+ ifindex = GetFriendlyIfIndex(ifrowP->dwIndex);
if (ifindex == index) {
/*
* Create a copy of the entry so that we can free the table.
@@ -199,7 +169,7 @@
* occurs then netifPP be returned as list of netif structures or NULL
* if no interfaces are found.
*/
-int enumInterfaces_win(JNIEnv *env, netif **netifPP)
+int enumInterfaces(JNIEnv *env, netif **netifPP)
{
MIB_IFTABLE *tableP;
MIB_IFROW *ifrowP;
@@ -215,32 +185,16 @@
*/
size = sizeof(MIB_IFTABLE);
tableP = (MIB_IFTABLE *)malloc(size);
- ret = (*GetIfTable_fn)(tableP, &size, TRUE);
+ ret = GetIfTable(tableP, &size, TRUE);
if (ret == ERROR_INSUFFICIENT_BUFFER || ret == ERROR_BUFFER_OVERFLOW) {
tableP = (MIB_IFTABLE *)realloc(tableP, size);
- ret = (*GetIfTable_fn)(tableP, &size, TRUE);
+ ret = GetIfTable(tableP, &size, TRUE);
}
if (ret != NO_ERROR) {
if (tableP != NULL)
free(tableP);
-#ifndef _WIN64
- if (isW9x && ret == ERROR_NOT_SUPPORTED) {
- /*
- * If ERROR_NOT_SUPPORTED is returned on Windows 98 it means that
- * IE5.0 has been installed. In this case we revert to the Windows 95
- * approach and avoid using the IP Helper Library.
- * See: http://support.microsoft.com/support/kb/articles/q234/5/73.asp
- */
- enumInterfaces_fn = enumInterfaces_win9x;
- enumAddresses_fn = enumAddresses_win9x;
- init_win9x();
-
- return (*enumInterfaces_fn)(env, netifPP);
- }
-#endif
-
JNU_ThrowByName(env, "java/lang/Error",
"IP Helper Library GetIfTable function failed");
@@ -328,7 +282,7 @@
curr->displayName[ifrowP->dwDescrLen] = '\0';
curr->dwIndex = ifrowP->dwIndex;
curr->ifType = ifrowP->dwType;
- curr->index = (*GetFriendlyIfIndex_fn)(ifrowP->dwIndex);
+ curr->index = GetFriendlyIfIndex(ifrowP->dwIndex);
/*
* Put the interface at tail of list as GetIfTable(,,TRUE) is
@@ -384,10 +338,10 @@
size = sizeof(MIB_IPADDRTABLE);
tableP = (MIB_IPADDRTABLE *)malloc(size);
- ret = (*GetIpAddrTable_fn)(&tableP, &size, FALSE);
+ ret = GetIpAddrTable(tableP, &size, FALSE);
if (ret == ERROR_INSUFFICIENT_BUFFER || ret == ERROR_BUFFER_OVERFLOW) {
tableP = (MIB_IPADDRTABLE *)realloc(tableP, size);
- ret = (*GetIpAddrTable_fn)(tableP, &size, FALSE);
+ ret = GetIpAddrTable(tableP, &size, FALSE);
}
if (ret != NO_ERROR) {
if (tableP) {
@@ -477,71 +431,6 @@
JNIEXPORT void JNICALL
Java_java_net_NetworkInterface_init(JNIEnv *env, jclass cls)
{
- OSVERSIONINFO ver;
- HANDLE h;
-
- /*
- * First check if this is a Windows 9x machine.
- */
- ver.dwOSVersionInfoSize = sizeof(ver);
- GetVersionEx(&ver);
- if (ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && ver.dwMajorVersion == 4) {
- isW9x = JNI_TRUE;
- }
-
- /*
- * Try to load the IP Helper Library and obtain the entry points we
- * require. This will succeed on 98, NT SP4+, 2000 & XP. It will
- * fail on Windows 95 (if IE hasn't been updated) and old versions
- * of NT (IP helper library only appeared at SP4). If it fails on
- * Windows 9x we will use the registry approach, otherwise if it
- * fails we throw an Error indicating that we have an incompatible
- * IP helper library.
- */
- h = LoadLibrary("iphlpapi.dll");
- if (h != NULL) {
- GetIpAddrTable_fn =
- (int (PASCAL FAR *)())GetProcAddress(h, "GetIpAddrTable");
- GetIfTable_fn =
- (int (PASCAL FAR *)())GetProcAddress(h, "GetIfTable");
- GetFriendlyIfIndex_fn =
- (int (PASCAL FAR *)())GetProcAddress(h, "GetFriendlyIfIndex");
- GetNumberOfInterfaces_fn =
- (int (PASCAL FAR *)())GetProcAddress(h, "GetNumberOfInterfaces");
- GetAdaptersAddresses_fn =
- (int (PASCAL FAR *)())GetProcAddress(h, "GetAdaptersAddresses");
- GetAdaptersInfo_fn =
- (int (PASCAL FAR *)())GetProcAddress(h, "GetAdaptersInfo");
- }
-
- /* IPv6 is supported on Windows versions if the following APIs avail */
-
- os_supports_ipv6 = (GetAdaptersAddresses_fn != NULL) &&
- (GetNumberOfInterfaces_fn != NULL) &&
- (GetAdaptersInfo_fn != NULL);
-
- if (GetIpAddrTable_fn == NULL ||
- GetIfTable_fn == NULL ||
- GetFriendlyIfIndex_fn == NULL) {
-
-#ifndef _WIN64
- if (isW9x) {
- /* Use Windows 9x registry approach which requires initialization */
- enumInterfaces_fn = enumInterfaces_win9x;
- enumAddresses_fn = enumAddresses_win9x;
- init_win9x();
- } else
-#endif
- {
- JNU_ThrowByName(env, "java/lang/Error",
- "Incompatible IP helper library (iphlpapi.dll)");
- return;
- }
- } else {
- enumInterfaces_fn = enumInterfaces_win;
- enumAddresses_fn = enumAddresses_win;
- }
-
/*
* Get the various JNI ids that we require
*/
@@ -581,7 +470,8 @@
* populate the InetAddress array based on the IP addresses for this
* interface.
*/
-jobject createNetworkInterface(JNIEnv *env, netif *ifs, int netaddrCount, netaddr *netaddrP)
+jobject createNetworkInterface
+ (JNIEnv *env, netif *ifs, int netaddrCount, netaddr *netaddrP)
{
jobject netifObj;
jobject name, displayName;
@@ -596,7 +486,8 @@
netifObj = (*env)->NewObject(env, ni_class, ni_ctor);
name = (*env)->NewStringUTF(env, ifs->name);
if (ifs->dNameIsUnicode) {
- displayName = (*env)->NewString(env, (PWCHAR)ifs->displayName, wcslen ((PWCHAR)ifs->displayName));
+ displayName = (*env)->NewString(env, (PWCHAR)ifs->displayName,
+ (jsize)wcslen ((PWCHAR)ifs->displayName));
} else {
displayName = (*env)->NewStringUTF(env, ifs->displayName);
}
@@ -612,7 +503,7 @@
* Note that 0 is a valid number of addresses.
*/
if (netaddrCount < 0) {
- netaddrCount = (*enumAddresses_fn)(env, ifs, &netaddrP);
+ netaddrCount = enumAddresses_win(env, ifs, &netaddrP);
if ((*env)->ExceptionOccurred(env)) {
free_netaddr(netaddrP);
return NULL;
@@ -725,12 +616,13 @@
const char *name_utf;
jobject netifObj = NULL;
- if (os_supports_ipv6 && ipv6_available()) {
+ // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
+ if (ipv6_available()) {
return Java_java_net_NetworkInterface_getByName0_XP (env, cls, name);
}
/* get the list of interfaces */
- if ((*enumInterfaces_fn)(env, &ifList) < 0) {
+ if (enumInterfaces(env, &ifList) < 0) {
return NULL;
}
@@ -771,12 +663,13 @@
netif *ifList, *curr;
jobject netifObj = NULL;
- if (os_supports_ipv6 && ipv6_available()) {
+ // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
+ if (ipv6_available()) {
return Java_java_net_NetworkInterface_getByIndex0_XP (env, cls, index);
}
/* get the list of interfaces */
- if ((*enumInterfaces_fn)(env, &ifList) < 0) {
+ if (enumInterfaces(env, &ifList) < 0) {
return NULL;
}
@@ -812,12 +705,13 @@
jint addr = (*env)->GetIntField(env, iaObj, ni_iaAddr);
jobject netifObj = NULL;
- if (os_supports_ipv6 && ipv6_available()) {
+ // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
+ if (ipv6_available()) {
return Java_java_net_NetworkInterface_getByInetAddress0_XP (env, cls, iaObj);
}
/* get the list of interfaces */
- if ((*enumInterfaces_fn)(env, &ifList) < 0) {
+ if (enumInterfaces(env, &ifList) < 0) {
return NULL;
}
@@ -832,7 +726,7 @@
netaddr *addrP;
/* enumerate the addresses on this interface */
- count = (*enumAddresses_fn)(env, curr, &addrList);
+ count = enumAddresses_win(env, curr, &addrList);
if (count < 0) {
free_netif(ifList);
return NULL;
@@ -881,14 +775,15 @@
jobjectArray netIFArr;
jint arr_index;
- if (os_supports_ipv6 && ipv6_available()) {
+ // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
+ if (ipv6_available()) {
return Java_java_net_NetworkInterface_getAll_XP (env, cls);
}
/*
* Get list of interfaces
*/
- count = (*enumInterfaces_fn)(env, &ifList);
+ count = enumInterfaces(env, &ifList);
if (count < 0) {
return NULL;
}
@@ -934,13 +829,16 @@
(JNIEnv *env, jclass cls, jstring name, jint index) {
jboolean ret = JNI_FALSE;
- if (os_supports_ipv6 && ipv6_available()) {
+ // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
+ if (ipv6_available()) {
return Java_java_net_NetworkInterface_isUp0_XP(env, cls, name, index);
} else {
MIB_IFROW *ifRowP;
ifRowP = getIF(index);
if (ifRowP != NULL) {
- ret = ifRowP->dwAdminStatus == 1 && (ifRowP->dwOperStatus == MIB_IF_OPER_STATUS_OPERATIONAL || ifRowP->dwOperStatus == MIB_IF_OPER_STATUS_CONNECTED);
+ ret = ifRowP->dwAdminStatus == 1 &&
+ (ifRowP->dwOperStatus == MIB_IF_OPER_STATUS_OPERATIONAL ||
+ ifRowP->dwOperStatus == MIB_IF_OPER_STATUS_CONNECTED);
free(ifRowP);
}
}
@@ -952,11 +850,13 @@
* Method: isP2P0
* Signature: (Ljava/lang/String;I)Z
*/
-JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isP2P0(JNIEnv *env, jclass cls, jstring name, jint index) {
+JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isP2P0
+ (JNIEnv *env, jclass cls, jstring name, jint index) {
MIB_IFROW *ifRowP;
jboolean ret = JNI_FALSE;
- if (os_supports_ipv6 && ipv6_available()) {
+ // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
+ if (ipv6_available()) {
return Java_java_net_NetworkInterface_isP2P0_XP(env, cls, name, index);
} else {
ifRowP = getIF(index);
@@ -983,7 +883,8 @@
MIB_IFROW *ifRowP;
jboolean ret = JNI_FALSE;
- if (os_supports_ipv6 && ipv6_available()) {
+ // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
+ if (ipv6_available()) {
return Java_java_net_NetworkInterface_isLoopback0_XP(env, cls, name, index);
} else {
ifRowP = getIF(index);
@@ -1003,22 +904,8 @@
*/
JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_supportsMulticast0
(JNIEnv *env, jclass cls, jstring name, jint index) {
- MIB_IFROW *ifRowP;
- jboolean ret = JNI_TRUE;
-
- // Let's try to use the newer API (XP & 2003 only)
- if (GetAdaptersAddresses_fn != NULL) {
- ret = Java_java_net_NetworkInterface_supportsMulticast0_XP(env, cls,
+ return Java_java_net_NetworkInterface_supportsMulticast0_XP(env, cls,
name, index);
- return ret;
- }
- ifRowP = getIF(index);
- if (ifRowP != NULL) {
- if (ifRowP->dwType == MIB_IF_TYPE_LOOPBACK)
- ret = JNI_FALSE;
- free(ifRowP);
- }
- return ret;
}
/*
@@ -1026,12 +913,14 @@
* Method: getMacAddr0
* Signature: ([bLjava/lang/String;I)[b
*/
-JNIEXPORT jbyteArray JNICALL Java_java_net_NetworkInterface_getMacAddr0(JNIEnv *env, jclass class, jbyteArray addrArray, jstring name, jint index) {
+JNIEXPORT jbyteArray JNICALL Java_java_net_NetworkInterface_getMacAddr0
+ (JNIEnv *env, jclass class, jbyteArray addrArray, jstring name, jint index) {
jbyteArray ret = NULL;
int len;
MIB_IFROW *ifRowP;
- if (os_supports_ipv6 && ipv6_available()) {
+ // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
+ if (ipv6_available()) {
return Java_java_net_NetworkInterface_getMacAddr0_XP(env, class, name, index);
} else {
ifRowP = getIF(index);
@@ -1058,11 +947,13 @@
* Method: getMTU0
* Signature: ([bLjava/lang/String;I)I
*/
-JNIEXPORT jint JNICALL Java_java_net_NetworkInterface_getMTU0(JNIEnv *env, jclass class, jstring name, jint index) {
+JNIEXPORT jint JNICALL Java_java_net_NetworkInterface_getMTU0
+ (JNIEnv *env, jclass class, jstring name, jint index) {
jint ret = -1;
MIB_IFROW *ifRowP;
- if (os_supports_ipv6 && ipv6_available()) {
+ // Retained for now to support IPv4 only stack, java.net.preferIPv4Stack
+ if (ipv6_available()) {
return Java_java_net_NetworkInterface_getMTU0_XP(env, class, name, index);
} else {
ifRowP = getIF(index);
--- a/jdk/src/windows/native/java/net/NetworkInterface.h Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/java/net/NetworkInterface.h Sun Apr 10 10:23:28 2011 -0700
@@ -87,338 +87,6 @@
extern jfieldID ni_ibbroadcastID; /* InterfaceAddress.broadcast */
extern jfieldID ni_ibmaskID; /* InterfaceAddress.maskLength */
-int enumInterfaces_win(JNIEnv *env, netif **netifPP);
-
-/* We have included iphlpapi.h which includes iptypes.h which has the definition
- * for MAX_ADAPTER_DESCRIPTION_LENGTH (along with the other definitions in this
- * ifndef block). Therefore if MAX_ADAPTER_DESCRIPTION_LENGTH is defined we can
- * be sure that the other definitions are also defined */
-#ifndef MAX_ADAPTER_DESCRIPTION_LENGTH
-
-/*
- * Following includes come from iptypes.h
- */
-
-#pragma warning(push)
-#pragma warning(disable:4201)
-
-#include <time.h>
-
-// Definitions and structures used by getnetworkparams and getadaptersinfo apis
-
-#define MAX_ADAPTER_DESCRIPTION_LENGTH 128 // arb.
-#define MAX_ADAPTER_NAME_LENGTH 256 // arb.
-#define MAX_ADAPTER_ADDRESS_LENGTH 8 // arb.
-#define DEFAULT_MINIMUM_ENTITIES 32 // arb.
-#define MAX_HOSTNAME_LEN 128 // arb.
-#define MAX_DOMAIN_NAME_LEN 128 // arb.
-#define MAX_SCOPE_ID_LEN 256 // arb.
-
-//
-// types
-//
-
-// Node Type
-
-#define BROADCAST_NODETYPE 1
-#define PEER_TO_PEER_NODETYPE 2
-#define MIXED_NODETYPE 4
-#define HYBRID_NODETYPE 8
-
-//
-// IP_ADDRESS_STRING - store an IP address as a dotted decimal string
-//
-
-typedef struct {
- char String[4 * 4];
-} IP_ADDRESS_STRING, *PIP_ADDRESS_STRING, IP_MASK_STRING, *PIP_MASK_STRING;
-
-//
-// IP_ADDR_STRING - store an IP address with its corresponding subnet mask,
-// both as dotted decimal strings
-//
-
-typedef struct _IP_ADDR_STRING {
- struct _IP_ADDR_STRING* Next;
- IP_ADDRESS_STRING IpAddress;
- IP_MASK_STRING IpMask;
- DWORD Context;
-} IP_ADDR_STRING, *PIP_ADDR_STRING;
-
-//
-// ADAPTER_INFO - per-adapter information. All IP addresses are stored as
-// strings
-//
-
-typedef struct _IP_ADAPTER_INFO {
- struct _IP_ADAPTER_INFO* Next;
- DWORD ComboIndex;
- char AdapterName[MAX_ADAPTER_NAME_LENGTH + 4];
- char Description[MAX_ADAPTER_DESCRIPTION_LENGTH + 4];
- UINT AddressLength;
- BYTE Address[MAX_ADAPTER_ADDRESS_LENGTH];
- DWORD Index;
- UINT Type;
- UINT DhcpEnabled;
- PIP_ADDR_STRING CurrentIpAddress;
- IP_ADDR_STRING IpAddressList;
- IP_ADDR_STRING GatewayList;
- IP_ADDR_STRING DhcpServer;
- BOOL HaveWins;
- IP_ADDR_STRING PrimaryWinsServer;
- IP_ADDR_STRING SecondaryWinsServer;
- time_t LeaseObtained;
- time_t LeaseExpires;
-} IP_ADAPTER_INFO, *PIP_ADAPTER_INFO;
-
-#ifdef _WINSOCK2API_
-
-//
-// The following types require Winsock2.
-//
-
-typedef enum {
- IpPrefixOriginOther = 0,
- IpPrefixOriginManual,
- IpPrefixOriginWellKnown,
- IpPrefixOriginDhcp,
- IpPrefixOriginRouterAdvertisement,
-} IP_PREFIX_ORIGIN;
-
-typedef enum {
- IpSuffixOriginOther = 0,
- IpSuffixOriginManual,
- IpSuffixOriginWellKnown,
- IpSuffixOriginDhcp,
- IpSuffixOriginLinkLayerAddress,
- IpSuffixOriginRandom,
-} IP_SUFFIX_ORIGIN;
-
-typedef enum {
- IpDadStateInvalid = 0,
- IpDadStateTentative,
- IpDadStateDuplicate,
- IpDadStateDeprecated,
- IpDadStatePreferred,
-} IP_DAD_STATE;
-
-typedef struct _IP_ADAPTER_UNICAST_ADDRESS {
- union {
- ULONGLONG Alignment;
- struct {
- ULONG Length;
- DWORD Flags;
- };
- };
- struct _IP_ADAPTER_UNICAST_ADDRESS *Next;
- SOCKET_ADDRESS Address;
-
- IP_PREFIX_ORIGIN PrefixOrigin;
- IP_SUFFIX_ORIGIN SuffixOrigin;
- IP_DAD_STATE DadState;
-
- ULONG ValidLifetime;
- ULONG PreferredLifetime;
- ULONG LeaseLifetime;
-} IP_ADAPTER_UNICAST_ADDRESS, *PIP_ADAPTER_UNICAST_ADDRESS;
-
-typedef struct _IP_ADAPTER_ANYCAST_ADDRESS {
- union {
- ULONGLONG Alignment;
- struct {
- ULONG Length;
- DWORD Flags;
- };
- };
- struct _IP_ADAPTER_ANYCAST_ADDRESS *Next;
- SOCKET_ADDRESS Address;
-} IP_ADAPTER_ANYCAST_ADDRESS, *PIP_ADAPTER_ANYCAST_ADDRESS;
-
-typedef struct _IP_ADAPTER_MULTICAST_ADDRESS {
- union {
- ULONGLONG Alignment;
- struct {
- ULONG Length;
- DWORD Flags;
- };
- };
- struct _IP_ADAPTER_MULTICAST_ADDRESS *Next;
- SOCKET_ADDRESS Address;
-} IP_ADAPTER_MULTICAST_ADDRESS, *PIP_ADAPTER_MULTICAST_ADDRESS;
-
-//
-// Per-address Flags
-//
-#define IP_ADAPTER_ADDRESS_DNS_ELIGIBLE 0x01
-#define IP_ADAPTER_ADDRESS_TRANSIENT 0x02
-
-typedef struct _IP_ADAPTER_DNS_SERVER_ADDRESS {
- union {
- ULONGLONG Alignment;
- struct {
- ULONG Length;
- DWORD Reserved;
- };
- };
- struct _IP_ADAPTER_DNS_SERVER_ADDRESS *Next;
- SOCKET_ADDRESS Address;
-} IP_ADAPTER_DNS_SERVER_ADDRESS, *PIP_ADAPTER_DNS_SERVER_ADDRESS;
-
-typedef struct _IP_ADAPTER_PREFIX {
- union {
- ULONGLONG Alignment;
- struct {
- ULONG Length;
- DWORD Flags;
- };
- };
- struct _IP_ADAPTER_PREFIX *Next;
- SOCKET_ADDRESS Address;
- ULONG PrefixLength;
-} IP_ADAPTER_PREFIX, *PIP_ADAPTER_PREFIX;
-
-//
-// Per-adapter Flags
-//
-#define IP_ADAPTER_DDNS_ENABLED 0x01
-#define IP_ADAPTER_REGISTER_ADAPTER_SUFFIX 0x02
-#define IP_ADAPTER_DHCP_ENABLED 0x04
-#define IP_ADAPTER_RECEIVE_ONLY 0x08
-#define IP_ADAPTER_NO_MULTICAST 0x10
-#define IP_ADAPTER_IPV6_OTHER_STATEFUL_CONFIG 0x20
-
-//
-// OperStatus values from RFC 2863
-//
-typedef enum {
- IfOperStatusUp = 1,
- IfOperStatusDown,
- IfOperStatusTesting,
- IfOperStatusUnknown,
- IfOperStatusDormant,
- IfOperStatusNotPresent,
- IfOperStatusLowerLayerDown
-} IF_OPER_STATUS;
-
-//
-// Scope levels from RFC 2373 used with ZoneIndices array.
-//
-typedef enum {
- ScopeLevelInterface = 1,
- ScopeLevelLink = 2,
- ScopeLevelSubnet = 3,
- ScopeLevelAdmin = 4,
- ScopeLevelSite = 5,
- ScopeLevelOrganization = 8,
- ScopeLevelGlobal = 14
-} SCOPE_LEVEL;
-
-typedef struct _IP_ADAPTER_ADDRESSES {
- union {
- ULONGLONG Alignment;
- struct {
- ULONG Length;
- DWORD IfIndex;
- };
- };
- struct _IP_ADAPTER_ADDRESSES *Next;
- PCHAR AdapterName;
- PIP_ADAPTER_UNICAST_ADDRESS FirstUnicastAddress;
- PIP_ADAPTER_ANYCAST_ADDRESS FirstAnycastAddress;
- PIP_ADAPTER_MULTICAST_ADDRESS FirstMulticastAddress;
- PIP_ADAPTER_DNS_SERVER_ADDRESS FirstDnsServerAddress;
- PWCHAR DnsSuffix;
- PWCHAR Description;
- PWCHAR FriendlyName;
- BYTE PhysicalAddress[MAX_ADAPTER_ADDRESS_LENGTH];
- DWORD PhysicalAddressLength;
- DWORD Flags;
- DWORD Mtu;
- DWORD IfType;
- IF_OPER_STATUS OperStatus;
- DWORD Ipv6IfIndex;
- DWORD ZoneIndices[16];
- PIP_ADAPTER_PREFIX FirstPrefix;
-} IP_ADAPTER_ADDRESSES, *PIP_ADAPTER_ADDRESSES;
-
-//
-// Flags used as argument to GetAdaptersAddresses().
-// "SKIP" flags are added when the default is to include the information.
-// "INCLUDE" flags are added when the default is to skip the information.
-//
-#define GAA_FLAG_SKIP_UNICAST 0x0001
-#define GAA_FLAG_SKIP_ANYCAST 0x0002
-#define GAA_FLAG_SKIP_MULTICAST 0x0004
-#define GAA_FLAG_SKIP_DNS_SERVER 0x0008
-#define GAA_FLAG_INCLUDE_PREFIX 0x0010
-#define GAA_FLAG_SKIP_FRIENDLY_NAME 0x0020
-
-#endif /* _WINSOCK2API_ */
-
-//
-// IP_PER_ADAPTER_INFO - per-adapter IP information such as DNS server list.
-//
-
-typedef struct _IP_PER_ADAPTER_INFO {
- UINT AutoconfigEnabled;
- UINT AutoconfigActive;
- PIP_ADDR_STRING CurrentDnsServer;
- IP_ADDR_STRING DnsServerList;
-} IP_PER_ADAPTER_INFO, *PIP_PER_ADAPTER_INFO;
-
-//
-// FIXED_INFO - the set of IP-related information which does not depend on DHCP
-//
-
-typedef struct {
- char HostName[MAX_HOSTNAME_LEN + 4] ;
- char DomainName[MAX_DOMAIN_NAME_LEN + 4];
- PIP_ADDR_STRING CurrentDnsServer;
- IP_ADDR_STRING DnsServerList;
- UINT NodeType;
- char ScopeId[MAX_SCOPE_ID_LEN + 4];
- UINT EnableRouting;
- UINT EnableProxy;
- UINT EnableDns;
-} FIXED_INFO, *PFIXED_INFO;
-
-#pragma warning(pop)
-
-#endif /*!MAX_ADAPTER_DESCRIPTION_LENGTH*/
-
-#ifndef IP_INTERFACE_NAME_INFO_DEFINED
-#define IP_INTERFACE_NAME_INFO_DEFINED
-
-typedef struct ip_interface_name_info {
- ULONG Index; // Interface Index
- ULONG MediaType; // Interface Types - see ipifcons.h
- UCHAR ConnectionType;
- UCHAR AccessType;
- GUID DeviceGuid; // Device GUID is the guid of the device
- // that IP exposes
- GUID InterfaceGuid; // Interface GUID, if not GUID_NULL is the
- // GUID for the interface mapped to the device.
-} IP_INTERFACE_NAME_INFO, *PIP_INTERFACE_NAME_INFO;
+int enumInterfaces(JNIEnv *env, netif **netifPP);
#endif
-
-
-/* from ipifcons.h */
-
-#ifndef IF_TYPE_PPP
-#define IF_TYPE_PPP 23
-#endif
-
-#ifndef IF_TYPE_SOFTWARE_LOOPBACK
-#define IF_TYPE_SOFTWARE_LOOPBACK 24
-#endif
-
-#ifndef IF_TYPE_SLIP
-#define IF_TYPE_SLIP 28
-#endif
-
-#ifndef IF_TYPE_TUNNEL
-#define IF_TYPE_TUNNEL 131
-#endif
-
-#endif
--- a/jdk/src/windows/native/java/net/NetworkInterface_win9x.c Thu Apr 07 15:21:10 2011 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1141 +0,0 @@
-/*
- * Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute 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.
- */
-
-#include <windows.h>
-#include <winsock2.h>
-#include <assert.h>
-
-#include "jni_util.h"
-
-#include "NetworkInterface.h"
-
-/*
- * Windows 9x specific routines to enumerate network interfaces and the
- * IP addresses bound to those interfaces.
- *
- * Windows 95 does not include IP helper library support by default.
- * Additionally Windows 98 can have its IP helper library support
- * trashed by certain IE installations. For these environments we
- * combine information from the registry with the list of IP addresses
- * obtained via SIO_GET_INTERFACE_LIST.
- */
-
-/*
- * Header files are missing these
- */
-#if !defined(SIO_GET_INTERFACE_LIST)
-#define SIO_GET_INTERFACE_LIST _IOR('t', 127, u_long)
-
-struct in_addr6 {
- u_char s6_addr[16];
-};
-
-struct sockaddr_in6 {
- short sin6_family;
- u_short sin6_port;
- u_long sin6_flowinfo;
- struct in_addr6 sin6_addr;
-};
-
-typedef union sockaddr_gen{
- struct sockaddr Address;
- struct sockaddr_in AddressIn;
- struct sockaddr_in6 AddressIn6;
-} sockaddr_gen;
-
-typedef struct _INTERFACE_INFO
-{
- u_long iiFlags;
- sockaddr_gen iiAddress;
- sockaddr_gen iiBroadcastAddress;
- sockaddr_gen iiNetmask;
-} INTERFACE_INFO;
-
-#define IFF_UP 0x00000001
-#endif
-
-
-#define MAX_STR_LEN 256
-
-
-/*
- * A network adapter (similiar to the netif structure except contains
- * Windows 9x specific fields).
- */
-typedef struct _adapter {
- char *name;
- char *displayName;
- int index;
- char *reg_key;
- int is_wan_driver;
- netaddr *addrs;
- struct _adapter *next;
-} adapter;
-
-
-/*
- * Cached adapter list.
- */
-static CRITICAL_SECTION cacheLock;
-static adapter *cachedAdapterList;
-
-/*
- * Initialize cache
- */
-void init_win9x() {
- InitializeCriticalSection(&cacheLock);
-}
-
-
-/*
- * Free adapter list and any addresses bound to the adpater.
- */
-static void free_adapters(adapter *adapterP) {
- adapter *curr = adapterP;
- while (curr != NULL) {
- if (curr->name != NULL)
- free(curr->name);
-
- if (curr->displayName != NULL)
- free(curr->displayName);
-
- if (curr->reg_key != NULL)
- free(curr->reg_key);
-
- if (curr->addrs != NULL)
- free_netaddr(curr->addrs);
-
- adapterP = adapterP->next;
- free(curr);
- curr = adapterP;
- }
-}
-
-
-/*
- * Returns the SIO_GET_INTERFACE_LIST output
- */
-static int getInterfaceList(JNIEnv *env, INTERFACE_INFO *infoP, DWORD dwSize) {
- SOCKET sock;
- DWORD ret;
-
- /* create a socket and do the ioctl */
- sock = socket(AF_INET, SOCK_DGRAM, 0);
- if (sock == INVALID_SOCKET) {
- JNU_ThrowByName(env, "java/lang/Error", "socket failed");
- return -1;
- }
- ret = WSAIoctl(sock, SIO_GET_INTERFACE_LIST, NULL, 0,
- infoP, dwSize, &dwSize, NULL, NULL);
- closesocket(sock);
- if (ret == SOCKET_ERROR) {
- JNU_ThrowByName(env, "java/lang/Error", "WSAIoctl failed");
- return -1;
- }
- return dwSize;
-}
-
-
-/*
- * Gross, ugly, and crude way of guessing if this is a WAN (dial-up) driver.
- * Returns 1 if it's the normal PPCMAC VxD, otherwise 0.
- */
-static int isWanDriver(char *driver) {
- LONG ret;
- HKEY hKey;
- DWORD dwLen;
- ULONG ulType;
- char key[MAX_STR_LEN];
- char vxd[MAX_STR_LEN];
-
- sprintf(key, "System\\CurrentControlSet\\Services\\Class\\%s", driver);
- ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, (PHKEY)&hKey);
- if (ret != ERROR_SUCCESS) {
- return 0;
- }
- dwLen = sizeof(vxd);
- ret = RegQueryValueEx(hKey, "DeviceVxDs", NULL, &ulType,
- (LPBYTE)vxd, &dwLen);
- RegCloseKey(hKey);
- if (ret != ERROR_SUCCESS) {
- return 0;
- }
- return (strcmp(vxd, "pppmac.vxd") == 0);
-}
-
-/*
- * Windows 9x routine to get the network adapters using the registry.
- * We enumerate HKEY_LOCAL_MACHINE\Enum and iterate through the tree
- * looking for devices of class "Net". As these devices may not have a
- * unique name we assign them a generated name.
- *
- * Returns a list of adapters without IP addresses (addrs member is NULL).
- */
-static int getAdapters(JNIEnv *env, adapter **adapterPP)
-{
- LONG ret;
- HKEY enumKey;
- DWORD dwLen;
- DWORD dwEnumKeys;
- DWORD enumIndex;
- ULONG ulType;
- int adapterCount = 0;
- adapter *adapterP = NULL;
- adapter *curr;
-
- /*
- * Start at HKEY_LOCAL_MACHINE\Enum
- */
- ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Enum", 0, KEY_READ, (PHKEY)&enumKey);
- if (ret != ERROR_SUCCESS) {
- return -1;
- }
- ret = RegQueryInfoKey(enumKey, NULL, NULL, NULL, &dwEnumKeys,
- NULL, NULL, NULL, NULL, NULL, NULL, NULL);
- if (ret != ERROR_SUCCESS) {
- RegCloseKey(enumKey);
- return -1;
- }
-
- /*
- * Iterate through the sub-keys (PCI, Root, ...)
- */
- for(enumIndex = 0; enumIndex<dwEnumKeys; enumIndex++) {
- TCHAR deviceType[MAX_STR_LEN];
- HKEY deviceKey;
- DWORD deviceIndex;
- DWORD dwDeviceKeys;
-
- dwLen = sizeof(deviceType);
- ret = RegEnumKeyEx(enumKey, enumIndex, deviceType, &dwLen, NULL, NULL, NULL, NULL);
- if (ret != ERROR_SUCCESS) {
- /* ignore this tree */
- continue;
- }
-
- ret = RegOpenKeyEx(enumKey, deviceType, 0, KEY_READ, (PHKEY)&deviceKey);
- if (ret != ERROR_SUCCESS) {
- /* ignore this tree */
- continue;
- }
- ret = RegQueryInfoKey(deviceKey, NULL, NULL, NULL, &dwDeviceKeys,
- NULL, NULL, NULL, NULL, NULL, NULL, NULL);
- if (ret != ERROR_SUCCESS) {
- /* ignore this tree */
- RegCloseKey(deviceKey);
- continue;
- }
-
- /*
- * Iterate through each of the sub-keys under PCI, Root, ...
- */
- for (deviceIndex=0; deviceIndex<dwDeviceKeys; deviceIndex++) {
- TCHAR name[MAX_STR_LEN];
- HKEY nameKey;
- DWORD nameIndex;
- DWORD dwNameKeys;
-
- dwLen = sizeof(name);
- ret = RegEnumKeyEx(deviceKey, deviceIndex, name, &dwLen, NULL, NULL, NULL, NULL);
-
- if (ret != ERROR_SUCCESS) {
- /* ignore this sub-tree */
- continue;
- }
-
- ret = RegOpenKeyEx(deviceKey, name, 0, KEY_READ, (PHKEY)&nameKey);
- if (ret != ERROR_SUCCESS) {
- /* ignore this sub-tree */
- continue;
- }
- ret = RegQueryInfoKey(nameKey, NULL, NULL, NULL, &dwNameKeys,
- NULL, NULL, NULL, NULL, NULL, NULL, NULL);
- if (ret != ERROR_SUCCESS) {
- RegCloseKey(nameKey);
- /* ignore this sub-tree */
- continue;
- }
-
- /*
- * Finally iterate through the Enum\Root\Net level keys
- */
- for (nameIndex=0; nameIndex<dwNameKeys; nameIndex++) {
- TCHAR dev[MAX_STR_LEN];
- TCHAR cls[MAX_STR_LEN];
- HKEY clsKey;
-
- dwLen = sizeof(dev);
- ret = RegEnumKeyEx(nameKey, nameIndex, dev, &dwLen, NULL, NULL, NULL, NULL);
- if (ret != ERROR_SUCCESS) {
- continue;
- }
-
- ret = RegOpenKeyEx(nameKey, dev, 0, KEY_READ, (PHKEY)&clsKey);
- if (ret == ERROR_SUCCESS) {
- dwLen = sizeof(cls);
- ret = RegQueryValueEx(clsKey, "Class", NULL, &ulType,
- (LPBYTE)cls, &dwLen);
-
- if (ret == ERROR_SUCCESS) {
- if (strcmp(cls, "Net") == 0) {
- TCHAR deviceDesc[MAX_STR_LEN];
-
- dwLen = sizeof(deviceDesc);
- ret = RegQueryValueEx(clsKey, "DeviceDesc", NULL, &ulType,
- (LPBYTE)deviceDesc, &dwLen);
-
- if (ret == ERROR_SUCCESS) {
- char key_name[MAX_STR_LEN];
- char ps_name[8];
- char driver[MAX_STR_LEN];
- int wan_device;
-
- /*
- * Generate a pseudo device name
- */
- sprintf(ps_name, "net%d", adapterCount);
-
- /*
- * Try to determine if this a WAN adapter. This is
- * useful when we try to eliminate WAN adapters from
- * the interface list when probing for DHCP info
- */
- dwLen = sizeof(driver);
- ret = RegQueryValueEx(clsKey, "Driver", NULL,
- &ulType, (LPBYTE)driver, &dwLen);
- if (ret == ERROR_SUCCESS) {
- wan_device = isWanDriver(driver);
- } else {
- wan_device = 0;
- }
-
- /*
- * We have found a Net device. In order to get the
- * static IP addresses we must note the key.
- */
- sprintf(key_name, "Enum\\%s\\%s\\%s", deviceType, name, dev);
-
- /*
- * Create the net adapter
- */
- curr = (adapter *)calloc(1, sizeof(adapter));
- if (curr != NULL) {
- curr->is_wan_driver = wan_device;
- curr->name = (char *)malloc(strlen(ps_name) + 1);
- if (curr->name) {
- curr->displayName = (char *)malloc(strlen(deviceDesc) + 1);
- if (curr->displayName) {
- curr->reg_key = (char *)malloc(strlen(key_name)+1);
- if (curr->reg_key == NULL) {
- free(curr->displayName);
- free(curr->name);
- free(curr);
- curr = NULL;
- }
- } else {
- free(curr->name);
- free(curr);
- curr = NULL;
- }
- } else {
- free(curr);
- curr = NULL;
- }
- }
-
- /* At OutOfMemory occurred */
- if (curr == NULL) {
- JNU_ThrowOutOfMemoryError(env, "heap allocation failure");
- free_adapters(adapterP);
- RegCloseKey(clsKey);
- RegCloseKey(nameKey);
- RegCloseKey(deviceKey);
- RegCloseKey(enumKey);
- return -1;
- }
-
- /* index starts at 1 (not 0) */
- curr->index = ++adapterCount;
-
- strcpy(curr->name, ps_name);
- strcpy(curr->displayName, deviceDesc);
- strcpy(curr->reg_key, key_name);
-
- /*
- * Put the adapter at the end of the list.
- */
- if (adapterP == NULL) {
- adapterP = curr;
- } else {
- adapter *tail = adapterP;
- while (tail->next != NULL) {
- tail = tail->next;
- }
- tail->next = curr;
- }
- }
- }
- }
- }
- RegCloseKey(clsKey);
- }
- RegCloseKey(nameKey);
- }
- RegCloseKey(deviceKey);
- }
- RegCloseKey(enumKey);
-
- /*
- * Insert an entry for the loopback interface
- */
- curr = (adapter *)calloc(1, sizeof(adapter));
- if (curr == NULL) {
- JNU_ThrowOutOfMemoryError(env, "heap allocation failure");
- free_adapters(adapterP);
- return -1;
- }
- curr->index = ++adapterCount;
- curr->name = _strdup("lo");
- curr->displayName = _strdup("TCP Loopback interface");
- curr->next = adapterP;
- *adapterPP = curr;
-
- return adapterCount;
-}
-
-/*
- * Windows 9x routine to obtain any static addresses for a specified
- * TCP/IP binding.
- *
- * We first open Enum\Network\${binding} and check that the driver
- * is TCP/IP. If so we pick up the driver and check for any IP addresses
- * in System\\CurrentControlSet\\Services\\Class\\${driver}
- *
- * Returns 0 if found, otherwise -1.
- */
-static int getStaticAddressEntry(char *binding, char *addresses) {
- LONG ret;
- HKEY hKey;
- char name[255];
- char desc[255];
- char driver[255];
- char ipaddr[255];
- DWORD dwName;
- ULONG ulType;
-
- /* assume nothing will be returned */
- strcpy(addresses, "");
-
- /*
- * Open the binding and check that it's TCP/IP
- */
- sprintf(name, "Enum\\Network\\%s", binding);
- ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, name, 0, KEY_READ, (PHKEY)&hKey);
- if (ret != ERROR_SUCCESS) {
- return -1;
- }
- dwName = sizeof(desc);
- ret = RegQueryValueEx(hKey, "DeviceDesc", NULL, &ulType,
- (LPBYTE)desc, &dwName);
- if (ret != ERROR_SUCCESS) {
- RegCloseKey(hKey);
- return -1;
- }
- if (strcmp(desc, "TCP/IP") != 0) {
- /* ignore non-TCP/IP bindings */
- RegCloseKey(hKey);
- return -1;
- }
-
- /*
- * Get the driver for this TCP/IP binding
- */
- dwName = sizeof(driver);
- ret = RegQueryValueEx(hKey, "Driver", NULL, &ulType,
- (LPBYTE)driver, &dwName);
- RegCloseKey(hKey);
- if (ret != ERROR_SUCCESS) {
- return -1;
- }
-
- /*
- * Finally check if there is an IPAddress value for this driver.
- */
- sprintf(name, "System\\CurrentControlSet\\Services\\Class\\%s", driver);
- ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, name, 0, KEY_READ, (PHKEY)&hKey);
- if (ret != ERROR_SUCCESS) {
- return -1;
- }
- dwName = sizeof(ipaddr);
- ret = RegQueryValueEx(hKey, "IPAddress", NULL, &ulType,
- (LPBYTE)ipaddr, &dwName);
- RegCloseKey(hKey);
- if (ret != ERROR_SUCCESS) {
- return -1;
- }
-
- /* Return the address(es) */
- strcpy( addresses, ipaddr );
- return 0;
-}
-
-/*
- * Windows 9x routine to enumerate the static IP addresses on a
- * particular interface using the registry.
- *
- * Returns a count of the number of addresses found.
- */
-static int getStaticAddresses(JNIEnv *env, char *reg_key, netaddr **netaddrPP)
-{
- LONG ret;
- HKEY enumKey, bindingKey;
- DWORD dwLen;
- ULONG ulType;
- char addresses[MAX_STR_LEN];
- unsigned long addr; /* IPv4 address */
- unsigned char byte;
- netaddr *netaddrP, *curr;
- int i, addrCount;
-
- /*
- * Open the HKEY_LOCAL_MACHINE\Enum\%s\%s\%s key
- */
- ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, reg_key, 0, KEY_READ,
- (PHKEY)&enumKey);
- if (ret != ERROR_SUCCESS) {
- /* interface has been removed */
- *netaddrPP = NULL;
- return 0;
- }
-
- /*
- * Iterate through each of the bindings to find any TCP/IP bindings
- * and any static address assoicated with the binding.
- */
- strcpy(addresses, "");
- addrCount = 0;
- netaddrP = NULL;
-
- ret = RegOpenKeyEx(enumKey, "Bindings", 0, KEY_READ, (PHKEY)&bindingKey);
- if (ret == ERROR_SUCCESS) {
- DWORD dwBindingKeys;
- DWORD dwBindingIndex;
-
- ret = RegQueryInfoKey(bindingKey, NULL, NULL, NULL, NULL, NULL, NULL, &dwBindingKeys,
- NULL, NULL, NULL, NULL);
- if (ret == ERROR_SUCCESS) {
- TCHAR binding[MAX_STR_LEN];
-
- dwBindingIndex=0;
- while (dwBindingIndex<dwBindingKeys) {
- dwLen = sizeof(binding);
- ret = RegEnumValue(bindingKey, dwBindingIndex, binding, &dwLen,
- NULL, &ulType, NULL, NULL);
- if (ret == ERROR_SUCCESS) {
- if (getStaticAddressEntry(binding, addresses) == 0) {
- /*
- * On Windows 9x IP addresses are strings. Multi-homed hosts have
- * the IP addresses seperated by commas.
- */
- addr = 0;
- byte = 0;
- i = 0;
- while ((DWORD)i < strlen(addresses)+1) {
- /* eof or seperator */
- if (addresses[i] == ',' || addresses[i] == 0) {
- if (addr != 0) {
- addr = (addr << 8) | byte;
-
- curr = (netaddr *)malloc(sizeof(netaddr));
- if (curr == NULL) {
- JNU_ThrowOutOfMemoryError(env, "heap allocation failure");
- free_netaddr(netaddrP);
- RegCloseKey(enumKey);
- return -1;
- }
- curr->addr.him4.sin_family = AF_INET;
- curr->addr.him4.sin_addr.s_addr = htonl(addr);
- curr->next = netaddrP;
-
- netaddrP = curr;
- addrCount++;
-
- /* reset the address for the next iteration */
- addr = 0;
- }
- byte = 0;
- } else {
- if (addresses[i] == '.') {
- addr = (addr << 8) | byte;
- byte = 0;
- } else {
- byte = (byte * 10) + (addresses[i] - '0');
- }
- }
- i++;
- }
- }
- }
- if (addrCount > 0) {
- break;
- }
- dwBindingIndex++;
- }
- }
- RegCloseKey(bindingKey);
- }
-
- /* close the registry */
- RegCloseKey(enumKey);
-
-
- /* return the list */
- *netaddrPP = netaddrP;
- return addrCount;
-}
-
-/*
- * Windows 9x routine to probe the registry for a DHCP allocated address.
- * This routine is only useful if we know that only one interface has its
- * address allocated using DHCP. Returns 0.0.0.0 if none or multiple
- * addresses found.0
- */
-static DWORD getDHCPAddress()
-{
- LONG ret;
- HKEY hKey;
- DWORD dwLen;
- ULONG ulType;
- char key[MAX_STR_LEN];
- int index;
- DWORD dhcp_addr = 0;
-
- index = 0;
- while (index < 99) {
- DWORD addr;
-
- sprintf(key, "SYSTEM\\CurrentControlSet\\Services\\VxD\\DHCP\\DhcpInfo%02d", index);
-
- ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, (PHKEY)&hKey);
- if (ret != ERROR_SUCCESS) {
- return dhcp_addr;
- }
-
- /*
- * On Windows 9x the DHCP address is in the DhcpIPAddress key. We
- * are assuming here that this is Windows Socket 2. If Windows
- * Sockets is the original 1.1 release then this doesn't work because
- * the IP address if in the DhcpInfo key (a blob with the first 4
- * bytes set to the IP address).
- */
- dwLen = sizeof(addr);
- ret = RegQueryValueEx(hKey, "DhcpIPAddress", NULL, &ulType,
- (LPBYTE)&addr, &dwLen);
- RegCloseKey(hKey);
-
- if (ret == ERROR_SUCCESS) {
- if (addr) {
- /* more than 1 DHCP address in registry */
- if (dhcp_addr) {
- return 0;
- }
- dhcp_addr = htonl(addr);
- }
- }
- index++;
- }
-
- /* if we get here it means we've examined 100 registry entries */
- return 0;
-}
-
-
-/*
- * Attempt to allocate the remaining addresses on addrList to the adpaters
- * on adapterList. Returns the number of address remaining.
- */
-int allocateRemaining(adapter *adapterList, int address_count, netaddr *addrList) {
- adapter *adapterP = adapterList;
- adapter *nobindingsP = NULL;
-
- /*
- * If all addresses have been assigned there's nothing to do.
- */
- if (address_count == 0) {
- return 0;
- }
-
- /*
- * Determine if there is only one adapter without an address
- */
- while (adapterP != NULL) {
- if (adapterP->addrs == NULL) {
- if (nobindingsP == NULL) {
- nobindingsP = adapterP;
- } else {
- nobindingsP = NULL;
- break;
- }
- }
- adapterP = adapterP->next;
- }
-
- /*
- * Found (only one)
- */
- if (nobindingsP) {
- nobindingsP->addrs = addrList;
- address_count = 0;
- }
-
- return address_count;
-}
-
-
-/*
- * 1. Network adapters are enumerated by traversing through the
- * HKEY_LOCAL_MACHINE\Enum tree and picking out class "Net" devices.
- *
- * 2. Address enumeration starts with the list of IP addresses returned
- * by SIO_GET_INTERFACE_LIST and then we "allocate" the addresses to
- * the network adapters enumerated in step 1. Allocation works as
- * follows :-
- *
- * i. Loopback address is assigned to the loopback interface. If there
- * is one network adapter then all other addresses must be bound
- * to that adapter.
- *
- * ii. Enumerate all static IP addresses using the registry. This allows
- * us to allocate all static IP address to the corresponding adapter.
- *
- * iii. After step ii. if there is one network adapter that has not been
- * allocated an IP address then we know that the remaining IP addresses
- * must be bound to this adapter.
- *
- * iv. If we get to this step it means we are dealing with a complex
- * configuration whereby multiple network adapters have their address
- * configured dynamically (eg: NIC using DHCP plus modem using PPP).
- * We employ a gross hack based on a crude determination done in step 1.
- * If there is a DHCP address configured and if one remaining
- * network adapter that is not a WAN adapter then the DHCP address
- * must be bound to it.
- */
-static adapter *loadConfig(JNIEnv *env) {
- adapter *adapterList;
- int adapter_count;
- INTERFACE_INFO interfaceInfo[8];
- DWORD dwSize;
- int address_count, i;
- netaddr *addrList;
-
- /*
- * Enumerate the network adapters
- */
- adapter_count = getAdapters(env, &adapterList);
- if (adapter_count < 0) {
- return NULL;
- }
- /* minimum of loopback interface */
- assert(adapter_count >= 1);
-
- /*
- * Enumerate all IP addresses as known to winsock
- */
- dwSize = getInterfaceList(env, interfaceInfo, sizeof(interfaceInfo));
- if (dwSize < 0) {
- free_adapters(adapterList);
- return NULL;
- }
- address_count = dwSize/sizeof(INTERFACE_INFO);
-
- /* minimum of loopback address */
- assert(address_count >= 1);
-
- /*
- * Create an address list (addrList) from the INTERFACE_INFO
- * structure.
- */
- addrList = NULL;
- for (i=0; i<address_count; i++) {
- netaddr *addrP = (netaddr *)calloc(1, sizeof(netaddr));
- if (addrP == NULL) {
- JNU_ThrowOutOfMemoryError(env, "heap allocation failure");
- free_netaddr(addrList);
- free(adapterList);
- return NULL;
- }
-
- addrP->addr.him4.sin_family = AF_INET;
- addrP->addr.him4.sin_addr.s_addr =
- ((SOCKADDR_IN *)&(interfaceInfo[i].iiAddress))->sin_addr.S_un.S_addr;
-
- addrP->next = addrList;
- addrList = addrP;
- }
-
-
- /*
- * First we assign the loopback address to the lo adapter.
- * If lo is the only adapter then we are done.
- */
- {
- adapter *loopbackAdapter;
- netaddr *addrP, *prevP;
-
- /* find the loopback adapter */
- loopbackAdapter = adapterList;
- while (strcmp(loopbackAdapter->name, "lo") != 0) {
- loopbackAdapter = loopbackAdapter->next;
- }
- assert(loopbackAdapter != NULL);
-
- /* find the loopback address and move it to the loopback adapter */
- addrP = addrList;
- prevP = NULL;
- while (addrP != NULL) {
- if (addrP->addr.him4.sin_addr.s_addr == htonl(0x7f000001)) {
- loopbackAdapter->addrs = addrP;
- if (prevP == NULL) {
- addrList = addrP->next;
- } else {
- prevP->next = addrP->next;
- }
- loopbackAdapter->addrs->next = NULL;
- address_count--;
- break;
- }
- prevP = addrP;
- addrP = addrP->next;
- }
- }
-
-
- /*
- * Special case. If there's only one network adapter then all remaining
- * IP addresses must be bound to that adapter.
- */
- address_count = allocateRemaining(adapterList, address_count, addrList);
- if (address_count == 0) {
- return adapterList;
- }
-
- /*
- * Locate any static IP addresses defined in the registry. Validate the
- * addresses against the SIO_GET_INTERFACE_LIST (as registry may have
- * stale settings). If valid we move the addresses from addrList to
- * the adapter.
- */
- {
- adapter *adapterP;
-
- adapterP = adapterList;
- while (adapterP != NULL) {
- int cnt;
- netaddr *static_addrP;
-
- /*
- * Skip loopback
- */
- if (strcmp(adapterP->name, "lo") == 0) {
- adapterP = adapterP->next;
- continue;
- }
-
- /*
- * Get the static addresses for this adapter.
- */
- cnt = getStaticAddresses(env, adapterP->reg_key, &static_addrP);
- if (cnt < 0) {
- free_netaddr(addrList);
- free(adapterList);
- return NULL;
- }
-
- /*
- * Validate against the SIO_GET_INTERFACE_LIST.
- * (avoids stale registry settings).
- */
- while (static_addrP != NULL) {
- netaddr *addrP = addrList;
- netaddr *prev = NULL;
-
- while (addrP != NULL) {
- if (addrP->addr.him4.sin_addr.s_addr == static_addrP->addr.him4.sin_addr.s_addr)
- break;
-
- prev = addrP;
- addrP = addrP->next;
- }
-
- /*
- * if addrP is not NULL it means we have a match
- * (ie: address from the registry is valid).
- */
- if (addrP != NULL) {
- /* remove from addrList */
- if (prev == NULL) {
- addrList = addrP->next;
- } else {
- prev->next = addrP->next;
- }
- address_count--;
-
- /* add to adapter list */
- addrP->next = adapterP->addrs;
- adapterP->addrs = addrP;
- }
-
- /*
- * On the next static address.
- */
- static_addrP = static_addrP->next;
- }
-
- /* not needed */
- free_netaddr(static_addrP);
-
- adapterP = adapterP->next;
- }
- }
-
-
- /*
- * Static addresses are now assigned so try again to allocate the
- * remaining addresses. This will succeed if there is one adapter
- * with a dynamically assigned address (DHCP or PPP).
- */
- address_count = allocateRemaining(adapterList, address_count, addrList);
- if (address_count == 0) {
- return adapterList;
- }
-
- /*
- * Next we see if there is a DHCP address in the registry. If there is
- * an address (and it's valid) then we know it must be bound to a LAN
- * adapter. Additionally, when we enumerate the network adapters
- * we made a crude determination on if an adapter is dial-up. Thus if
- * we know there is one remaining LAN adapter without an IP address
- * then the DHCP address must be bound to it.
- */
- {
- long dhcp_addr = getDHCPAddress(); /* returns in network order */
- if (dhcp_addr) {
- netaddr *addrP, *prevP;
-
- /*
- * Check that the DHCP address is valid
- */
- addrP = addrList;
- prevP = NULL;
- while (addrP != NULL) {
- if (addrP->addr.him4.sin_addr.s_addr == dhcp_addr) {
- break;
- }
- prevP = addrP;
- addrP = addrP->next;
- }
-
- /*
- * Address is valid - now check how many non-WAN adapters
- * don't have addresses yet.
- */
- if (addrP != NULL) {
- adapter *adapterP = adapterList;
- adapter *nobindingsP = NULL;
-
- while (adapterP != NULL) {
- if (adapterP->addrs == NULL && !adapterP->is_wan_driver) {
- if (nobindingsP == NULL) {
- nobindingsP = adapterP;
- } else {
- /* already found one */
- nobindingsP = NULL;
- break;
- }
- }
- adapterP = adapterP->next;
- }
-
- /*
- * One non-WAN adapter remaining
- */
- if (nobindingsP != NULL) {
- nobindingsP->addrs = addrP;
-
- /* remove from addrList */
- if (prevP == NULL) {
- addrList = addrP->next;
- } else {
- prevP->next = addrP->next;
- }
- addrP->next = NULL;
- address_count--;
- }
- }
- }
- }
-
- /*
- * Finally we do one final attempt to re-assign any remaining
- * addresses. This catches the case of 2 adapters that have their
- * addresses dynamically assigned (specifically NIC with DHCP, and
- * Modem using RAS/PPP).
- */
- address_count = allocateRemaining(adapterList, address_count, addrList);
- if (address_count == 0) {
- return adapterList;
- }
-
- /*
- * Free any unallocated addresses
- */
- if (address_count > 0) {
- free_netaddr(addrList);
- }
-
- /*
- * Return the adapter List.
- */
- return adapterList;
-
-}
-
-
-/*
- * Enumerate network interfaces. If successful returns the number of
- * network interfaces and netifPP returning a list of netif structures.
- * Returns -1 with exception thrown if error.
- */
-int enumInterfaces_win9x(JNIEnv *env, netif **netifPP) {
- adapter *adapters, *adapterP;
- int cnt = 0;
- netif *netifP = NULL;
-
- /* enumerate network configuration */
- adapters = loadConfig(env);
- if (adapters == NULL) {
- return -1;
- }
-
- /*
- * loadConfig returns an adapter list - we need to create a corresponding
- * list of netif structures.
- */
- adapterP = adapters;
- while (adapterP != NULL) {
- netif *ifs = (netif *)calloc(1, sizeof(netif));
-
- if (ifs == NULL) {
- JNU_ThrowOutOfMemoryError(env, "heap allocation failure");
- free_adapters(adapters);
- free_netif(netifP);
- return -1;
- }
-
- ifs->name = _strdup(adapterP->name);
- ifs->displayName = _strdup(adapterP->displayName);
- ifs->dwIndex = adapterP->index;
- ifs->index = adapterP->index;
- ifs->next = netifP;
- netifP = ifs;
-
- if (ifs->name == NULL || ifs->displayName == NULL) {
- JNU_ThrowOutOfMemoryError(env, "heap allocation failure");
- free_adapters(adapters);
- free_netif(netifP);
- return -1;
- }
-
- cnt++;
- adapterP = adapterP->next;
- }
-
- /*
- * Put the adapter list in the cache
- */
- EnterCriticalSection(&cacheLock);
- {
- if (cachedAdapterList != NULL) {
- free_adapters(cachedAdapterList);
- }
- cachedAdapterList = adapters;
- }
- LeaveCriticalSection(&cacheLock);
-
- /*
- * Return the netif list
- */
- *netifPP = netifP;
- return cnt;
-}
-
-/*
- * Enumerate the addresses for the specified network interface. If successful
- * returns the number of addresses bound to the interface and sets netaddrPP
- * to be a list of netaddr structures. Returns -1 if error.
- */
-int enumAddresses_win9x(JNIEnv *env, netif *netifP, netaddr **netaddrPP) {
-
- EnterCriticalSection(&cacheLock);
- {
- adapter *adapterP = cachedAdapterList;
- while (adapterP != NULL) {
- if (strcmp(adapterP->name, netifP->name) == 0) {
-
- netaddr *newlist = NULL;
- netaddr *curr = adapterP->addrs;
- int cnt = 0;
-
- while (curr != NULL) {
- /*
- * Clone the netaddr and add it to newlist.
- */
- netaddr *tmp = (netaddr *)calloc(1, sizeof(netaddr));
- if (tmp == NULL) {
- LeaveCriticalSection(&cacheLock);
- JNU_ThrowOutOfMemoryError(env, "heap allocation failure");
- free_netaddr(newlist);
- return -1;
- }
- tmp->addr = curr->addr;
- tmp->next = newlist;
- newlist = tmp;
-
- cnt++;
- curr = curr->next;
- }
-
- *netaddrPP = newlist;
- LeaveCriticalSection(&cacheLock);
- return cnt;
- }
- adapterP = adapterP->next;
- }
- }
- LeaveCriticalSection(&cacheLock);
-
- *netaddrPP = NULL;
- return 0;
-}
--- a/jdk/src/windows/native/java/net/NetworkInterface_winXP.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/java/net/NetworkInterface_winXP.c Sun Apr 10 10:23:28 2011 -0700
@@ -43,14 +43,6 @@
extern int enumAddresses_win(JNIEnv *env, netif *netifP, netaddr **netaddrPP);
int getAddrsFromAdapter(IP_ADAPTER_ADDRESSES *ptr, netaddr **netaddrPP);
-/* IP helper library routines */
-int (PASCAL FAR *GetIpAddrTable_fn)();
-int (PASCAL FAR *GetIfTable_fn)();
-int (PASCAL FAR *GetFriendlyIfIndex_fn)();
-int (PASCAL FAR *GetAdaptersAddresses_fn)();
-int (PASCAL FAR *GetAdaptersInfo_fn)();
-int (PASCAL FAR *GetNumberOfInterfaces_fn)();
-
#ifdef DEBUG
void printnif (netif *nif) {
#ifdef _WIN64
@@ -96,14 +88,14 @@
flags = GAA_FLAG_SKIP_DNS_SERVER;
flags |= GAA_FLAG_SKIP_MULTICAST;
flags |= GAA_FLAG_INCLUDE_PREFIX;
- ret = (*GetAdaptersAddresses_fn) (AF_UNSPEC, flags, NULL, adapterInfo, &len);
+ ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapterInfo, &len);
if (ret == ERROR_BUFFER_OVERFLOW) {
adapterInfo = (IP_ADAPTER_ADDRESSES *) realloc (adapterInfo, len);
if (adapterInfo == 0) {
return -1;
}
bufsize = len;
- ret = (*GetAdaptersAddresses_fn) (AF_UNSPEC, flags, NULL, adapterInfo, &len);
+ ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapterInfo, &len);
}
if (ret != ERROR_SUCCESS) {
free (adapterInfo);
@@ -133,7 +125,7 @@
flags = GAA_FLAG_SKIP_DNS_SERVER;
flags |= GAA_FLAG_SKIP_MULTICAST;
flags |= GAA_FLAG_INCLUDE_PREFIX;
- val = (*GetAdaptersAddresses_fn) (AF_UNSPEC, flags, NULL, adapterInfo, &len);
+ val = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapterInfo, &len);
if (val == ERROR_BUFFER_OVERFLOW) {
adapterInfo = (IP_ADAPTER_ADDRESSES *) realloc (adapterInfo, len);
if (adapterInfo == 0) {
@@ -141,7 +133,7 @@
return NULL;
}
bufsize = len;
- val = (*GetAdaptersAddresses_fn) (AF_UNSPEC, flags, NULL, adapterInfo, &len);
+ val = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapterInfo, &len);
}
if (val != ERROR_SUCCESS) {
free (adapterInfo);
@@ -182,7 +174,7 @@
* as what previous JDK versions would return.
*/
- ret = enumInterfaces_win (env, netifPP);
+ ret = enumInterfaces(env, netifPP);
if (ret == -1) {
return -1;
} else {
@@ -221,7 +213,7 @@
* (b) IPv6 information for IPv6 only interfaces (probably tunnels)
*
* For compatibility with previous releases we use the naming
- * information gotten from enumInterfaces_win() for (a) entries
+ * information gotten from enumInterfaces() for (a) entries
* However, the index numbers are taken from the new API.
*
* The procedure is to go through the list of adapters returned
@@ -439,7 +431,8 @@
netifObj = (*env)->NewObject(env, ni_class, ni_ctor);
name = (*env)->NewStringUTF(env, ifs->name);
if (ifs->dNameIsUnicode) {
- displayName = (*env)->NewString(env, (PWCHAR)ifs->displayName, wcslen ((PWCHAR)ifs->displayName));
+ displayName = (*env)->NewString(env, (PWCHAR)ifs->displayName,
+ (jsize)wcslen ((PWCHAR)ifs->displayName));
} else {
displayName = (*env)->NewStringUTF(env, ifs->displayName);
}
--- a/jdk/src/windows/native/java/net/net_util_md.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/java/net/net_util_md.c Sun Apr 10 10:23:28 2011 -0700
@@ -39,10 +39,6 @@
/* true if SO_RCVTIMEO is supported */
jboolean isRcvTimeoutSupported = JNI_TRUE;
-LPFN_GETADDRINFO getaddrinfo_ptr = NULL;
-LPFN_FREEADDRINFO freaddrinfo_ptr = NULL;
-LPFN_GETNAMEINFO getnameinfo_ptr = NULL;
-
/*
* Table of Windows Sockets errors, the specific exception we
* throw for the error, and the error text.
@@ -233,38 +229,15 @@
jint IPv6_supported()
{
- HMODULE lib;
- int fd = socket(AF_INET6, SOCK_STREAM, 0) ;
- if (fd < 0) {
- return JNI_FALSE;
- }
- closesocket (fd);
-
- if ((lib = LoadLibrary ("ws2_32.dll")) == NULL) {
+ SOCKET s = socket(AF_INET6, SOCK_STREAM, 0) ;
+ if (s == INVALID_SOCKET) {
return JNI_FALSE;
}
- if ((getaddrinfo_ptr = (LPFN_GETADDRINFO)GetProcAddress (lib, "getaddrinfo")) == NULL) {
- FreeLibrary (lib);
- return JNI_FALSE;
- }
- if ((freeaddrinfo_ptr = (LPFN_FREEADDRINFO)GetProcAddress (lib, "freeaddrinfo")) == NULL) {
- FreeLibrary (lib);
- return JNI_FALSE;
- }
- if ((getnameinfo_ptr = (LPFN_GETNAMEINFO)GetProcAddress (lib, "getnameinfo")) == NULL) {
- FreeLibrary (lib);
- return JNI_FALSE;
- }
- FreeLibrary(lib);
+ closesocket(s);
return JNI_TRUE;
}
-jboolean NET_addrtransAvailable() {
- return (jboolean)(getaddrinfo_ptr != NULL);
-}
-
-
/*
* Return the default TOS value
*/
@@ -664,7 +637,7 @@
if (family == AF_INET && (b->addr->him4.sin_addr.s_addr != INADDR_ANY)) {
/* bind to v4 only */
int ret;
- ret = NET_Bind (b->ipv4_fd, (struct sockaddr *)b->addr,
+ ret = NET_Bind ((int)b->ipv4_fd, (struct sockaddr *)b->addr,
sizeof (struct sockaddr_in));
if (ret == SOCKET_ERROR) {
CLOSE_SOCKETS_AND_RETURN;
@@ -676,7 +649,7 @@
if (family == AF_INET6 && (!IN6_IS_ADDR_ANY(&b->addr->him6.sin6_addr))) {
/* bind to v6 only */
int ret;
- ret = NET_Bind (b->ipv6_fd, (struct sockaddr *)b->addr,
+ ret = NET_Bind ((int)b->ipv6_fd, (struct sockaddr *)b->addr,
sizeof (struct SOCKADDR_IN6));
if (ret == SOCKET_ERROR) {
CLOSE_SOCKETS_AND_RETURN;
@@ -691,15 +664,15 @@
memset (&oaddr, 0, sizeof(oaddr));
if (family == AF_INET) {
ofamily = AF_INET6;
- fd = b->ipv4_fd;
- ofd = b->ipv6_fd;
+ fd = (int)b->ipv4_fd;
+ ofd = (int)b->ipv6_fd;
port = (u_short)GET_PORT (b->addr);
IN6ADDR_SETANY (&oaddr.him6);
oaddr.him6.sin6_port = port;
} else {
ofamily = AF_INET;
- ofd = b->ipv4_fd;
- fd = b->ipv6_fd;
+ ofd = (int)b->ipv4_fd;
+ fd = (int)b->ipv6_fd;
port = (u_short)GET_PORT (b->addr);
oaddr.him4.sin_family = AF_INET;
oaddr.him4.sin_port = port;
@@ -744,11 +717,11 @@
b->ipv6_fd = SOCKET_ERROR;
/* create two new sockets */
- fd = socket (family, sotype, 0);
+ fd = (int)socket (family, sotype, 0);
if (fd == SOCKET_ERROR) {
CLOSE_SOCKETS_AND_RETURN;
}
- ofd = socket (ofamily, sotype, 0);
+ ofd = (int)socket (ofamily, sotype, 0);
if (ofd == SOCKET_ERROR) {
CLOSE_SOCKETS_AND_RETURN;
}
@@ -802,7 +775,7 @@
DWORD b;
struct sockaddr_in6 route;
SOCKET fd = socket(AF_INET6, SOCK_STREAM, 0);
- if (fd < 0) {
+ if (fd == INVALID_SOCKET) {
return 0;
}
@@ -810,7 +783,7 @@
(void *)target_addr, sizeof(struct sockaddr_in6),
(void *)&route, sizeof(struct sockaddr_in6),
&b, 0, 0);
- if (ret < 0) {
+ if (ret == SOCKET_ERROR) {
// error
closesocket(fd);
return 0;
@@ -1001,10 +974,10 @@
}
int NET_Socket (int domain, int type, int protocol) {
- int sock;
+ SOCKET sock;
sock = socket (domain, type, protocol);
if (sock != INVALID_SOCKET) {
SetHandleInformation((HANDLE)(uintptr_t)sock, HANDLE_FLAG_INHERIT, FALSE);
}
- return sock;
+ return (int)sock;
}
--- a/jdk/src/windows/native/java/net/net_util_md.h Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/java/net/net_util_md.h Sun Apr 10 10:23:28 2011 -0700
@@ -209,10 +209,6 @@
);
#endif
-LPFN_GETADDRINFO getaddrinfo_ptr;
-LPFN_FREEADDRINFO freeaddrinfo_ptr;
-LPFN_GETNAMEINFO getnameinfo_ptr;
-
/* used to disable connection reset messages on Windows XP */
#ifndef SIO_UDP_CONNRESET
#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
@@ -302,8 +298,6 @@
void NET_ThrowSocketException(JNIEnv *env, char* msg);
-jboolean NET_addrtransAvailable();
-
/*
* differs from NET_Timeout() as follows:
*
--- a/jdk/src/windows/native/sun/management/FileSystemImpl.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/sun/management/FileSystemImpl.c Sun Apr 10 10:23:28 2011 -0700
@@ -37,45 +37,6 @@
#define ANY_ACCESS (FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE)
/*
- * Function prototypes for security functions - we can't statically
- * link because these functions aren't on Windows 9x.
- */
-typedef BOOL (WINAPI *GetFileSecurityFunc)
- (LPCTSTR lpFileName, SECURITY_INFORMATION RequestedInformation,
- PSECURITY_DESCRIPTOR pSecurityDescriptor, DWORD nLength,
- LPDWORD lpnLengthNeeded);
-
-typedef BOOL (WINAPI *GetSecurityDescriptorOwnerFunc)
- (PSECURITY_DESCRIPTOR pSecurityDescriptor, PSID *pOwner,
- LPBOOL lpbOwnerDefaulted);
-
-typedef BOOL (WINAPI *GetSecurityDescriptorDaclFunc)
- (PSECURITY_DESCRIPTOR pSecurityDescriptor, LPBOOL lpbDaclPresent,
- PACL *pDacl, LPBOOL lpbDaclDefaulted);
-
-typedef BOOL (WINAPI *GetAclInformationFunc)
- (PACL pAcl, LPVOID pAclInformation, DWORD nAclInformationLength,
- ACL_INFORMATION_CLASS dwAclInformationClass);
-
-typedef BOOL (WINAPI *GetAceFunc)
- (PACL pAcl, DWORD dwAceIndex, LPVOID *pAce);
-
-typedef BOOL (WINAPI *EqualSidFunc)(PSID pSid1, PSID pSid2);
-
-
-/* Addresses of the security functions */
-static GetFileSecurityFunc GetFileSecurity_func;
-static GetSecurityDescriptorOwnerFunc GetSecurityDescriptorOwner_func;
-static GetSecurityDescriptorDaclFunc GetSecurityDescriptorDacl_func;
-static GetAclInformationFunc GetAclInformation_func;
-static GetAceFunc GetAce_func;
-static EqualSidFunc EqualSid_func;
-
-/* True if this OS is NT kernel based (NT/2000/XP) */
-static int isNT;
-
-
-/*
* Returns JNI_TRUE if the specified file is on a file system that supports
* persistent ACLs (On NTFS file systems returns true, on FAT32 file systems
* returns false).
@@ -165,7 +126,7 @@
SECURITY_INFORMATION info =
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION;
- (*GetFileSecurity_func)(path, info , 0, 0, &len);
+ GetFileSecurityA(path, info , 0, 0, &len);
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
JNU_ThrowIOExceptionWithLastError(env, "GetFileSecurity failed");
return NULL;
@@ -174,7 +135,7 @@
if (sd == NULL) {
JNU_ThrowOutOfMemoryError(env, 0);
} else {
- if (!(*GetFileSecurity_func)(path, info, sd, len, &len)) {
+ if (!(*GetFileSecurityA)(path, info, sd, len, &len)) {
JNU_ThrowIOExceptionWithLastError(env, "GetFileSecurity failed");
free(sd);
return NULL;
@@ -191,7 +152,7 @@
SID* owner;
BOOL defaulted;
- if (!(*GetSecurityDescriptorOwner_func)(sd, &owner, &defaulted)) {
+ if (!GetSecurityDescriptorOwner(sd, &owner, &defaulted)) {
JNU_ThrowIOExceptionWithLastError(env, "GetSecurityDescriptorOwner failed");
return NULL;
}
@@ -206,7 +167,7 @@
ACL *acl;
int defaulted, present;
- if (!(*GetSecurityDescriptorDacl_func)(sd, &present, &acl, &defaulted)) {
+ if (!GetSecurityDescriptorDacl(sd, &present, &acl, &defaulted)) {
JNU_ThrowIOExceptionWithLastError(env, "GetSecurityDescriptorDacl failed");
return NULL;
}
@@ -235,8 +196,8 @@
/*
* Get the ACE count
*/
- if (!(*GetAclInformation_func)(acl, (void *) &acl_size_info, sizeof(acl_size_info),
- AclSizeInformation)) {
+ if (!GetAclInformation(acl, (void *) &acl_size_info, sizeof(acl_size_info),
+ AclSizeInformation)) {
JNU_ThrowIOExceptionWithLastError(env, "GetAclInformation failed");
return JNI_FALSE;
}
@@ -250,7 +211,7 @@
ACCESS_ALLOWED_ACE *access;
SID* sid;
- if (!(*GetAce_func)(acl, i, &ace)) {
+ if (!GetAce(acl, i, &ace)) {
JNU_ThrowIOExceptionWithLastError(env, "GetAce failed");
return -1;
}
@@ -280,51 +241,7 @@
JNIEXPORT void JNICALL Java_sun_management_FileSystemImpl_init0
(JNIEnv *env, jclass ignored)
{
- OSVERSIONINFO ver;
- HINSTANCE hInst;
-
- /*
- * Get the OS version. If dwPlatformId is VER_PLATFORM_WIN32_NT
- * it means we're running on a Windows NT, 2000, or XP machine.
- */
- ver.dwOSVersionInfoSize = sizeof(ver);
- GetVersionEx(&ver);
- isNT = (ver.dwPlatformId == VER_PLATFORM_WIN32_NT);
- if (!isNT) {
- return;
- }
-
- /*
- * On NT/2000/XP we need the addresses of the security functions
- */
- hInst = LoadLibrary("ADVAPI32.DLL");
- if (hInst == NULL) {
- JNU_ThrowIOExceptionWithLastError(env, "Unable to load ADVAPI32.DLL");
- return;
- }
-
-
- GetFileSecurity_func = (GetFileSecurityFunc)GetProcAddress(hInst, "GetFileSecurityA");
- GetSecurityDescriptorOwner_func =
- (GetSecurityDescriptorOwnerFunc)GetProcAddress(hInst, "GetSecurityDescriptorOwner");
- GetSecurityDescriptorDacl_func =
- (GetSecurityDescriptorDaclFunc)GetProcAddress(hInst, "GetSecurityDescriptorDacl");
- GetAclInformation_func =
- (GetAclInformationFunc)GetProcAddress(hInst, "GetAclInformation");
- GetAce_func = (GetAceFunc)GetProcAddress(hInst, "GetAce");
- EqualSid_func = (EqualSidFunc)GetProcAddress(hInst, "EqualSid");
-
- if (GetFileSecurity_func == NULL ||
- GetSecurityDescriptorDacl_func == NULL ||
- GetSecurityDescriptorDacl_func == NULL ||
- GetAclInformation_func == NULL ||
- GetAce_func == NULL ||
- EqualSid_func == NULL)
- {
- JNU_ThrowIOExceptionWithLastError(env,
- "Unable to get address of security functions");
- return;
- }
+ /* nothing to do */
}
/*
@@ -339,10 +256,6 @@
jboolean isCopy;
const char* path;
- if (!isNT) {
- return JNI_FALSE;
- }
-
path = JNU_GetStringPlatformChars(env, str, &isCopy);
if (path != NULL) {
res = isSecuritySupported(env, path);
--- a/jdk/src/windows/native/sun/net/dns/ResolverConfigurationImpl.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/sun/net/dns/ResolverConfigurationImpl.c Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,7 @@
#include <iprtrmib.h>
#include <time.h>
#include <assert.h>
+#include <iphlpapi.h>
#include "jni_util.h"
@@ -42,93 +43,17 @@
#define IS_SL_FOUND(sts) (sts & STS_SL_FOUND)
#define IS_NS_FOUND(sts) (sts & STS_NS_FOUND)
-/*
- * Visual C++ SP3 (as required by J2SE 1.4.0) is missing some of
- * the definitions required for the IP helper library routines that
- * were added in Windows 98 & Windows 2000.
- */
-#ifndef MAX_ADAPTER_NAME_LENGTH
-
-#define MAX_ADAPTER_ADDRESS_LENGTH 8
-#define MAX_ADAPTER_DESCRIPTION_LENGTH 128
-#define MAX_ADAPTER_NAME_LENGTH 256
-#define MAX_HOSTNAME_LEN 128
-#define MAX_DOMAIN_NAME_LEN 128
-#define MAX_SCOPE_ID_LEN 256
-
-typedef struct {
- char String[4 * 4];
-} IP_ADDRESS_STRING, *PIP_ADDRESS_STRING, IP_MASK_STRING, *PIP_MASK_STRING;
-
-typedef struct _IP_ADDR_STRING {
- struct _IP_ADDR_STRING* Next;
- IP_ADDRESS_STRING IpAddress;
- IP_MASK_STRING IpMask;
- DWORD Context;
-} IP_ADDR_STRING, *PIP_ADDR_STRING;
-
-typedef struct _IP_ADAPTER_INFO {
- struct _IP_ADAPTER_INFO* Next;
- DWORD ComboIndex;
- char AdapterName[MAX_ADAPTER_NAME_LENGTH + 4];
- char Description[MAX_ADAPTER_DESCRIPTION_LENGTH + 4];
- UINT AddressLength;
- BYTE Address[MAX_ADAPTER_ADDRESS_LENGTH];
- DWORD Index;
- UINT Type;
- UINT DhcpEnabled;
- PIP_ADDR_STRING CurrentIpAddress;
- IP_ADDR_STRING IpAddressList;
- IP_ADDR_STRING GatewayList;
- IP_ADDR_STRING DhcpServer;
- BOOL HaveWins;
- IP_ADDR_STRING PrimaryWinsServer;
- IP_ADDR_STRING SecondaryWinsServer;
- time_t LeaseObtained;
- time_t LeaseExpires;
-} IP_ADAPTER_INFO, *PIP_ADAPTER_INFO;
-
-typedef struct _FIXED_INFO {
- char HostName[MAX_HOSTNAME_LEN + 4] ;
- char DomainName[MAX_DOMAIN_NAME_LEN + 4];
- PIP_ADDR_STRING CurrentDnsServer;
- IP_ADDR_STRING DnsServerList;
- UINT NodeType;
- char ScopeId[MAX_SCOPE_ID_LEN + 4];
- UINT EnableRouting;
- UINT EnableProxy;
- UINT EnableDns;
-} FIXED_INFO, *PFIXED_INFO;
-
-#endif
-
-
-/* IP helper library routine used on 98/2000/XP */
-static int (PASCAL FAR *GetNetworkParams_fn)();
-static int (PASCAL FAR *GetAdaptersInfo_fn)();
-static int (PASCAL FAR *NotifyAddrChange_fn)();
-
-/*
- * Routines to obtain domain name and name servers are OS specific
- */
-typedef int (*LoadConfig)(char *sl, char *ns);
-static LoadConfig loadconfig_fn;
-
-
-/*
- * JNI ids
- */
+/* JNI ids */
static jfieldID searchlistID;
static jfieldID nameserversID;
-
/*
* Utility routine to append s2 to s1 with a space delimiter.
* strappend(s1="abc", "def") => "abc def"
* strappend(s1="", "def") => "def
*/
void strappend(char *s1, char *s2) {
- int len;
+ size_t len;
if (s2[0] == '\0') /* nothing to append */
return;
@@ -145,356 +70,6 @@
strcat(s1, s2);
}
-
-/*
- * Windows 95/98/ME for static TCP/IP configuration.
- *
- * Use registry approach for statically configured TCP/IP settings.
- * Registry entries described in "MS TCP/IP and Windows 95 Networking"
- * (Microsoft TechNet site).
- */
-static int loadStaticConfig9x(char *sl, char *ns) {
- LONG ret;
- HANDLE hKey;
- DWORD dwLen;
- ULONG ulType;
- char result[MAX_STR_LEN];
- int sts = STS_NO_CONFIG;
-
- ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
- "SYSTEM\\CurrentControlSet\\Services\\VxD\\MSTCP",
- 0,
- KEY_READ,
- (PHKEY)&hKey);
- if (ret == ERROR_SUCCESS) {
- /*
- * Determine suffix list
- */
- result[0] = '\0';
- dwLen = sizeof(result);
- ret = RegQueryValueEx(hKey, "SearchList", NULL, &ulType,
- (LPBYTE)&result, &dwLen);
- if ((ret != ERROR_SUCCESS) || (strlen(result) == 0)) {
- dwLen = sizeof(result);
- ret = RegQueryValueEx(hKey, "Domain", NULL, &ulType,
- (LPBYTE)&result, &dwLen);
- }
- if (ret == ERROR_SUCCESS) {
- assert(ulType == REG_SZ);
- if (strlen(result) > 0) {
- strappend(sl, result);
- sts |= STS_SL_FOUND;
- }
- }
-
- /*
- * Determine DNS name server(s)
- */
- result[0] = '\0';
- dwLen = sizeof(result);
- ret = RegQueryValueEx(hKey, "NameServer", NULL, &ulType,
- (LPBYTE)&result, &dwLen);
- if (ret == ERROR_SUCCESS) {
- assert(ulType == REG_SZ);
- if (strlen(result) > 0) {
- strappend(ns, result);
- sts |= STS_NS_FOUND;
- }
- }
-
- RegCloseKey(hKey);
- }
-
- return sts;
-}
-
-
-/*
- * Windows 95
- *
- * Use registry approach for statically configured TCP/IP settings
- * (see loadStaticConfig9x).
- *
- * If DHCP is used we examine the DHCP vendor specific extensions. We parse
- * this based on format described in RFC 2132.
- *
- * If Dial-up Networking (DUN) is used then this TCP/IP settings cannot
- * be determined here.
- */
-static int loadConfig95(char *sl, char *ns) {
- int sts;
- int index;
- LONG ret;
- HANDLE hKey;
- DWORD dwLen;
- ULONG ulType;
- char optionInfo[MAX_STR_LEN];
-
- /*
- * First try static configuration - if found we are done.
- */
- sts = loadStaticConfig9x(sl, ns);
- if (IS_SL_FOUND(sts) && IS_NS_FOUND(sts)) {
- return sts;
- }
-
- /*
- * Try DHCP. DHCP information is stored in :-
- * SYSTEM\CurrentControlSet\Services\VxD\DHCP\DhcpInfoXX
- *
- * The key is normally DhcpInfo00\OptionInfo (see Article Q255245 on
- * Microsoft site). However when multiple cards are added & removed we
- * have observed that it can be located in DhcpInfo{01,02, ...}.
- * As a hack we search all DhcpInfoXX keys until we find OptionInfo.
- */
- for (index=0; index<99; index++) {
- char key[MAX_STR_LEN];
- sprintf(key, "SYSTEM\\CurrentControlSet\\Services\\VxD\\DHCP\\DhcpInfo%02d",
- index);
-
- ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, (PHKEY)&hKey);
- if (ret != ERROR_SUCCESS) {
- /* end of DhcpInfoXX entries */
- break;
- }
-
- dwLen = sizeof(optionInfo);
- ret = RegQueryValueEx(hKey, "OptionInfo", NULL, &ulType,
- (LPBYTE)optionInfo, &dwLen);
- RegCloseKey(hKey);
-
- if (ret == ERROR_SUCCESS) {
- /* OptionInfo found */
- break;
- }
- }
-
- /*
- * If OptionInfo was found then we parse (as the 'options' field of
- * the DHCP packet - see RFC 2132).
- */
- if (ret == ERROR_SUCCESS) {
- unsigned int pos = 0;
-
- while (pos < dwLen) {
- int code, len;
-
- code = optionInfo[pos];
- pos++;
- if (pos >= dwLen) break; /* bad packet */
-
- len = optionInfo[pos];
- pos++;
-
- if (pos+len > dwLen) break; /* bad packet */
-
- /*
- * Domain Name - see RFC 2132 section 3.17
- */
- if (!IS_SL_FOUND(sts)) {
- if (code == 0xf) {
- char domain[MAX_STR_LEN];
-
- assert(len < MAX_STR_LEN);
-
- memcpy((void *)domain, (void *)&(optionInfo[pos]), (size_t)len);
- domain[len] = '\0';
-
- strappend(sl, domain);
- sts |= STS_SL_FOUND;
- }
- }
-
- /*
- * DNS Option - see RFC 2132 section 3.8
- */
- if (!IS_NS_FOUND(sts)) {
- if (code == 6 && (len % 4) == 0) {
- while (len > 0 && pos < dwLen) {
- char addr[32];
- sprintf(addr, "%d.%d.%d.%d",
- (unsigned char)optionInfo[pos],
- (unsigned char)optionInfo[pos+1],
- (unsigned char)optionInfo[pos+2],
- (unsigned char)optionInfo[pos+3]);
- pos += 4;
- len -= 4;
-
- /*
- * Append to list of name servers
- */
- strappend(ns, addr);
- sts |= STS_NS_FOUND;
- }
- }
- }
-
- /*
- * Onto the next options
- */
- pos += len;
- }
- }
-
- return sts;
-}
-
-/*
- * Windows 98/ME
- *
- * Use registry approach for statically configured TCP/IP settings
- * (see loadStaticConfig9x).
- *
- * If configuration is not static then use IP helper library routine
- * GetNetworkParams to obtain the network settings which include the
- * domain name and the DNS servers. Note that we use the registry in
- * preference to GetNetworkParams as the domain name is not populated
- * by GetNetworkParams if the configuration is static.
- */
-static int loadConfig98(char *sl, char *ns) {
- FIXED_INFO *infoP;
- ULONG size;
- DWORD ret;
- int sts;
-
- /*
- * Use registry approach to pick up static configuation.
- */
- sts = loadStaticConfig9x(sl, ns);
- if (IS_SL_FOUND(sts) && IS_NS_FOUND(sts)) {
- return sts;
- }
-
- /*
- * Use IP helper library to obtain dynamic configuration (DHCP and
- * DUN).
- */
- size = sizeof(FIXED_INFO);
- infoP = (FIXED_INFO *)malloc(size);
- if (infoP) {
- ret = (*GetNetworkParams_fn)(infoP, &size);
- if (ret == ERROR_BUFFER_OVERFLOW) {
- infoP = (FIXED_INFO *)realloc(infoP, size);
- if (infoP != NULL)
- ret = (*GetNetworkParams_fn)(infoP, &size);
- }
- }
- if (infoP == NULL) {
- return sts;
- }
- if (ret == ERROR_SUCCESS) {
- /*
- * Use DomainName if search-list not specified.
- */
- if (!IS_SL_FOUND(sts)) {
- strappend(sl, infoP->DomainName);
- sts |= STS_SL_FOUND;
- }
-
- /*
- * Use DnsServerList if not statically configured.
- */
- if (!IS_NS_FOUND(sts)) {
- PIP_ADDR_STRING dnsP = &(infoP->DnsServerList);
- do {
- strappend(ns, (char *)&(dnsP->IpAddress));
- dnsP = dnsP->Next;
- } while (dnsP != NULL);
- sts |= STS_NS_FOUND;
- }
- }
-
- free(infoP);
-
- return sts;
-}
-
-
-/*
- * Windows NT
- *
- * Use registry approach based on settings described in "TCP/IP and
- * NBT Configuration Parameters for Windows" - Article Q12062 on
- * Microsoft site.
- *
- * All non-RAS TCP/IP settings are stored in HKEY_LOCAL_MACHINE in
- * the SYSTEM\CurrentControlSet\Services\Tcpip\Parameters key.
- *
- * If SearchList if not provided then return Domain or DhcpDomain.
- * If Domain is specified it overrides DhcpDomain even if DHCP is
- * enabled.
- *
- * DNS name servers based on NameServer or DhcpNameServer settings.
- * NameServer overrides DhcpNameServer even if DHCP is enabled.
- */
-static int loadConfigNT(char *sl, char *ns) {
- LONG ret;
- HANDLE hKey;
- DWORD dwLen;
- ULONG ulType;
- char result[MAX_STR_LEN];
- int sts = STS_NO_CONFIG;
-
- ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
- "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters",
- 0,
- KEY_READ,
- (PHKEY)&hKey);
- if (ret != ERROR_SUCCESS) {
- return sts;
- }
-
- /*
- * Determine search list
- */
- result[0] = '\0';
- dwLen = sizeof(result);
- ret = RegQueryValueEx(hKey, "SearchList", NULL, &ulType,
- (LPBYTE)&result, &dwLen);
- if ((ret != ERROR_SUCCESS) || (strlen(result) == 0)) {
- dwLen = sizeof(result);
- ret = RegQueryValueEx(hKey, "Domain", NULL, &ulType,
- (LPBYTE)&result, &dwLen);
- if ((ret != ERROR_SUCCESS) || (strlen(result) == 0)) {
- dwLen = sizeof(result);
- ret = RegQueryValueEx(hKey, "DhcpDomain", NULL, &ulType,
- (LPBYTE)&result, &dwLen);
- }
- }
- if (ret == ERROR_SUCCESS) {
- assert(ulType == REG_SZ);
- if (strlen(result) > 0) {
- strappend(sl, result);
- sts |= STS_SL_FOUND;
- }
- }
-
- /*
- * Determine DNS name server(s)
- */
- result[0] = '\0';
- dwLen = sizeof(result);
- ret = RegQueryValueEx(hKey, "NameServer", NULL, &ulType,
- (LPBYTE)&result, &dwLen);
- if ((ret != ERROR_SUCCESS) || (strlen(result) == 0)) {
- dwLen = sizeof(result);
- ret = RegQueryValueEx(hKey, "DhcpNameServer", NULL, &ulType,
- (LPBYTE)&result, &dwLen);
- }
- if (ret == ERROR_SUCCESS) {
- assert(ulType == REG_SZ);
- if (strlen(result) > 0) {
- strappend(ns, result);
- sts |= STS_NS_FOUND;
- }
- }
-
- RegCloseKey(hKey);
-
- return sts;
-}
-
-
/*
* Windows 2000/XP
*
@@ -510,7 +85,7 @@
* names of each adapter and then query the corresponding registry
* settings to obtain NameServer/DhcpNameServer and Domain/DhcpDomain.
*/
-static int loadConfig2000(char *sl, char *ns) {
+static int loadConfig(char *sl, char *ns) {
IP_ADAPTER_INFO *adapterP;
ULONG size;
DWORD ret;
@@ -547,10 +122,10 @@
*/
size = sizeof(IP_ADAPTER_INFO);
adapterP = (IP_ADAPTER_INFO *)malloc(size);
- ret = (*GetAdaptersInfo_fn)(adapterP, &size);
+ ret = GetAdaptersInfo(adapterP, &size);
if (ret == ERROR_BUFFER_OVERFLOW) {
adapterP = (IP_ADAPTER_INFO *)realloc(adapterP, size);
- ret = (*GetAdaptersInfo_fn)(adapterP, &size);
+ ret = GetAdaptersInfo(adapterP, &size);
}
/*
@@ -648,87 +223,15 @@
/*
- * Initialization :-
- *
- * 1. Based on OS version set the function pointer for OS specific load
- * configuration routine.
- *
- * 2. On 98/2000/XP load the IP helper library.
- *
- * 3. Initialize JNI field IDs.
- *
+ * Initialize JNI field IDs.
*/
JNIEXPORT void JNICALL
Java_sun_net_dns_ResolverConfigurationImpl_init0(JNIEnv *env, jclass cls)
{
- OSVERSIONINFO ver;
- jboolean loadHelperLibrary = JNI_TRUE;
-
- /*
- * First we figure out which OS is running
- */
- ver.dwOSVersionInfoSize = sizeof(ver);
- GetVersionEx(&ver);
-
- if (ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
- if ((ver.dwMajorVersion == 4) && (ver.dwMinorVersion == 0)) {
- /*
- * Windows 95
- */
- loadHelperLibrary = JNI_FALSE;
- loadconfig_fn = loadConfig95;
- } else {
- /*
- * Windows 98/ME
- */
- loadHelperLibrary = JNI_TRUE;
- loadconfig_fn = loadConfig98;
- }
- }
-
- if (ver.dwPlatformId == VER_PLATFORM_WIN32_NT) {
- if (ver.dwMajorVersion <= 4) {
- /*
- * Windows NT
- */
- loadHelperLibrary = JNI_FALSE;
- loadconfig_fn = loadConfigNT;
- } else {
- /*
- * Windows 2000/XP
- */
- loadHelperLibrary = JNI_TRUE;
- loadconfig_fn = loadConfig2000;
- }
- }
-
- /*
- * On 98/2000/XP we load the IP Helper Library.
- */
- if (loadHelperLibrary) {
- HANDLE h = LoadLibrary("iphlpapi.dll");
-
- if (h != NULL) {
- GetNetworkParams_fn = (int (PASCAL FAR *)())GetProcAddress(h, "GetNetworkParams");
- GetAdaptersInfo_fn = (int (PASCAL FAR *)())GetProcAddress(h, "GetAdaptersInfo");
-
- NotifyAddrChange_fn = (int (PASCAL FAR *)())GetProcAddress(h, "NotifyAddrChange");
- }
-
- if (GetNetworkParams_fn == NULL || GetAdaptersInfo_fn == NULL) {
- JNU_ThrowByName(env, "java/lang/UnsatisfiedLinkError", "iphlpapi.dll");
- return;
- }
- }
-
- /*
- * Get JNI ids
- */
searchlistID = (*env)->GetStaticFieldID(env, cls, "os_searchlist",
"Ljava/lang/String;");
nameserversID = (*env)->GetStaticFieldID(env, cls, "os_nameservers",
"Ljava/lang/String;");
-
}
/*
@@ -746,8 +249,7 @@
searchlist[0] = '\0';
nameservers[0] = '\0';
- /* call OS specific routine */
- (void)(*loadconfig_fn)(searchlist, nameservers);
+ loadConfig(searchlist, nameservers);
/*
* Populate static fields in sun.net.DefaultResolverConfiguration
@@ -772,17 +274,15 @@
HANDLE h;
DWORD rc, xfer;
- if (NotifyAddrChange_fn != NULL) {
- ol.hEvent = (HANDLE)0;
- rc = (*NotifyAddrChange_fn)(&h, &ol);
- if (rc == ERROR_IO_PENDING) {
- rc = GetOverlappedResult(h, &ol, &xfer, TRUE);
- if (rc != 0) {
- return 0; /* address changed */
- }
+ ol.hEvent = (HANDLE)0;
+ rc = NotifyAddrChange(&h, &ol);
+ if (rc == ERROR_IO_PENDING) {
+ rc = GetOverlappedResult(h, &ol, &xfer, TRUE);
+ if (rc != 0) {
+ return 0; /* address changed */
}
}
- /* NotifyAddrChange not support or error */
+ /* error */
return -1;
}
--- a/jdk/src/windows/native/sun/net/www/protocol/http/ntlm/NTLMAuthSequence.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/sun/net/www/protocol/http/ntlm/NTLMAuthSequence.c Sun Apr 10 10:23:28 2011 -0700
@@ -41,18 +41,6 @@
#define SECURITY_WIN32
#include "sspi.h"
-
-/*
- * OS calls loaded from DLL on intialization
- */
-
-static FREE_CREDENTIALS_HANDLE_FN pFreeCredentialsHandle;
-static ACQUIRE_CREDENTIALS_HANDLE_FN pAcquireCredentialsHandle;
-static FREE_CONTEXT_BUFFER_FN pFreeContextBuffer;
-static INITIALIZE_SECURITY_CONTEXT_FN pInitializeSecurityContext;
-static COMPLETE_AUTH_TOKEN_FN pCompleteAuthToken;
-static DELETE_SECURITY_CONTEXT_FN pDeleteSecurityContext;
-
static void endSequence (PCredHandle credHand, PCtxtHandle ctxHandle);
static jfieldID ntlm_ctxHandleID;
@@ -63,48 +51,8 @@
JNIEXPORT void JNICALL Java_sun_net_www_protocol_http_ntlm_NTLMAuthSequence_initFirst
(JNIEnv *env, jclass clazz)
{
- OSVERSIONINFO version;
- UCHAR libName[MAX_PATH];
-
ntlm_ctxHandleID = (*env)->GetFieldID(env, clazz, "ctxHandle", "J");
ntlm_crdHandleID = (*env)->GetFieldID(env, clazz, "crdHandle", "J");
-
- version.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
- GetVersionEx (&version);
-
- if (version.dwPlatformId == VER_PLATFORM_WIN32_NT) {
- strcpy (libName, "security.dll" );
- }
- else if (version.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
- strcpy (libName, "secur32.dll" );
- }
-
- lib = LoadLibrary (libName);
-
- pFreeCredentialsHandle
- = (FREE_CREDENTIALS_HANDLE_FN) GetProcAddress(
- lib, "FreeCredentialsHandle" );
-
- pAcquireCredentialsHandle
- = (ACQUIRE_CREDENTIALS_HANDLE_FN) GetProcAddress(
- lib, "AcquireCredentialsHandleA" );
-
- pFreeContextBuffer
- = (FREE_CONTEXT_BUFFER_FN) GetProcAddress(
- lib, "FreeContextBuffer" );
-
- pInitializeSecurityContext
- = (INITIALIZE_SECURITY_CONTEXT_FN) GetProcAddress(
- lib, "InitializeSecurityContextA" );
-
- pCompleteAuthToken
- = (COMPLETE_AUTH_TOKEN_FN) GetProcAddress(
- lib, "CompleteAuthToken" );
-
- pDeleteSecurityContext
- = (DELETE_SECURITY_CONTEXT_FN) GetProcAddress(
- lib, "DeleteSecurityContext" );
-
}
/*
@@ -158,17 +106,17 @@
if ( pUser != NULL ) {
AuthId.User = (unsigned char *) pUser;
- AuthId.UserLength = strlen( pUser );
+ AuthId.UserLength = (unsigned long) strlen( pUser );
}
if ( pPassword != NULL ) {
AuthId.Password = (unsigned char *) pPassword;
- AuthId.PasswordLength = strlen( pPassword );
+ AuthId.PasswordLength = (unsigned long) strlen( pPassword );
}
if ( pDomain != NULL ) {
AuthId.Domain = (unsigned char *) pDomain;
- AuthId.DomainLength = strlen( pDomain );
+ AuthId.DomainLength = (unsigned long) strlen( pDomain );
}
AuthId.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI;
@@ -176,7 +124,7 @@
pAuthId = NULL;
}
- ss = pAcquireCredentialsHandle(
+ ss = AcquireCredentialsHandleA(
NULL, "NTLM", SECPKG_CRED_OUTBOUND,
NULL, pAuthId, NULL, NULL,
pCred, <ime
@@ -258,7 +206,7 @@
* need to send the out buffer if there are bytes to send
*/
- ss = pInitializeSecurityContext(
+ ss = InitializeSecurityContextA(
pCred, pCtx, NULL, 0, 0, SECURITY_NATIVE_DREP,
lastToken ? &InBuffDesc : NULL, 0, newContext, &OutBuffDesc,
&ContextAttributes, <ime
@@ -274,7 +222,7 @@
}
if ((ss == SEC_I_COMPLETE_NEEDED) || (ss == SEC_I_COMPLETE_AND_CONTINUE) ) {
- ss = pCompleteAuthToken( pCtx, &OutBuffDesc );
+ ss = CompleteAuthToken( pCtx, &OutBuffDesc );
if (ss < 0) {
endSequence (pCred, pCtx);
@@ -300,12 +248,12 @@
static void endSequence (PCredHandle credHand, PCtxtHandle ctxHandle) {
if (credHand != 0) {
- pFreeCredentialsHandle (credHand);
- free (credHand);
+ FreeCredentialsHandle(credHand);
+ free(credHand);
}
if (ctxHandle != 0) {
- pDeleteSecurityContext(ctxHandle);
- free (ctxHandle);
+ DeleteSecurityContext(ctxHandle);
+ free(ctxHandle);
}
}
--- a/jdk/src/windows/native/sun/nio/fs/WindowsNativeDispatcher.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/sun/nio/fs/WindowsNativeDispatcher.c Sun Apr 10 10:23:28 2011 -0700
@@ -24,7 +24,7 @@
*/
#ifndef _WIN32_WINNT
-#define _WIN32_WINNT 0x0500
+#define _WIN32_WINNT 0x0501
#endif
#include <stdio.h>
@@ -36,6 +36,7 @@
#include <windows.h>
#include <aclapi.h>
#include <winioctl.h>
+#include <Sddl.h>
#include "jni.h"
#include "jni_util.h"
@@ -77,40 +78,20 @@
/**
- * Win32 APIs not defined in Visual Studio 2003 header files
+ * Win32 APIs not available in Windows XP
*/
-
-typedef enum {
- FindStreamInfoStandard
-} MY_STREAM_INFO_LEVELS;
-
-typedef struct _MY_WIN32_FIND_STREAM_DATA {
- LARGE_INTEGER StreamSize;
- WCHAR cStreamName[MAX_PATH + 36];
-} MY_WIN32_FIND_STREAM_DATA;
-
-typedef HANDLE (WINAPI* FindFirstStream_Proc)(LPCWSTR, MY_STREAM_INFO_LEVELS, LPVOID, DWORD);
+typedef HANDLE (WINAPI* FindFirstStream_Proc)(LPCWSTR, STREAM_INFO_LEVELS, LPVOID, DWORD);
typedef BOOL (WINAPI* FindNextStream_Proc)(HANDLE, LPVOID);
typedef BOOLEAN (WINAPI* CreateSymbolicLinkProc) (LPCWSTR, LPCWSTR, DWORD);
-typedef BOOL (WINAPI* CreateHardLinkProc) (LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES);
typedef BOOL (WINAPI* GetFinalPathNameByHandleProc) (HANDLE, LPWSTR, DWORD, DWORD);
-typedef BOOL (WINAPI* ConvertSidToStringSidProc) (PSID, LPWSTR*);
-typedef BOOL (WINAPI* ConvertStringSidToSidProc) (LPWSTR, PSID*);
-typedef DWORD (WINAPI* GetLengthSidProc) (PSID);
-
static FindFirstStream_Proc FindFirstStream_func;
static FindNextStream_Proc FindNextStream_func;
static CreateSymbolicLinkProc CreateSymbolicLink_func;
-static CreateHardLinkProc CreateHardLink_func;
static GetFinalPathNameByHandleProc GetFinalPathNameByHandle_func;
-static ConvertSidToStringSidProc ConvertSidToStringSid_func;
-static ConvertStringSidToSidProc ConvertStringSidToSid_func;
-static GetLengthSidProc GetLengthSid_func;
-
static void throwWindowsException(JNIEnv* env, DWORD lastError) {
jobject x = JNU_NewObjectByName(env, "sun/nio/fs/WindowsException",
"(I)V", lastError);
@@ -190,33 +171,23 @@
backupResult_bytesTransferred = (*env)->GetFieldID(env, clazz, "bytesTransferred", "I");
backupResult_context = (*env)->GetFieldID(env, clazz, "context", "J");
-
- h = LoadLibrary("kernel32");
- if (h != INVALID_HANDLE_VALUE) {
+ // get handle to kernel32
+ if (GetModuleHandleExW((GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
+ GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT),
+ (LPCWSTR)&CreateFileW, &h) != 0)
+ {
+ // requires Windows Server 2003 or newer
FindFirstStream_func =
(FindFirstStream_Proc)GetProcAddress(h, "FindFirstStreamW");
FindNextStream_func =
(FindNextStream_Proc)GetProcAddress(h, "FindNextStreamW");
+
+ // requires Windows Vista or newer
CreateSymbolicLink_func =
(CreateSymbolicLinkProc)GetProcAddress(h, "CreateSymbolicLinkW");
- CreateHardLink_func =
- (CreateHardLinkProc)GetProcAddress(h, "CreateHardLinkW");
GetFinalPathNameByHandle_func =
(GetFinalPathNameByHandleProc)GetProcAddress(h, "GetFinalPathNameByHandleW");
- FreeLibrary(h);
}
-
- h = LoadLibrary("advapi32");
- if (h != INVALID_HANDLE_VALUE) {
- ConvertSidToStringSid_func =
- (ConvertSidToStringSidProc)GetProcAddress(h, "ConvertSidToStringSidW");
- ConvertStringSidToSid_func =
- (ConvertStringSidToSidProc)GetProcAddress(h, "ConvertStringSidToSidW");
- GetLengthSid_func =
- (GetLengthSidProc)GetProcAddress(h, "GetLengthSid");
- FreeLibrary(h);
- }
-
}
JNIEXPORT jstring JNICALL
@@ -413,7 +384,7 @@
Java_sun_nio_fs_WindowsNativeDispatcher_FindFirstStream0(JNIEnv* env, jclass this,
jlong address, jobject obj)
{
- MY_WIN32_FIND_STREAM_DATA data;
+ WIN32_FIND_STREAM_DATA data;
LPCWSTR lpFileName = jlong_to_ptr(address);
HANDLE handle;
@@ -443,7 +414,7 @@
Java_sun_nio_fs_WindowsNativeDispatcher_FindNextStream(JNIEnv* env, jclass this,
jlong handle)
{
- MY_WIN32_FIND_STREAM_DATA data;
+ WIN32_FIND_STREAM_DATA data;
HANDLE h = (HANDLE)jlong_to_ptr(handle);
if (FindNextStream_func == NULL) {
@@ -909,12 +880,7 @@
jclass this, jlong address)
{
PSID sid = jlong_to_ptr(address);
-
- if (GetLengthSid_func == NULL) {
- JNU_ThrowInternalError(env, "Should not get here");
- return 0;
- }
- return (jint)(*GetLengthSid_func)(sid);
+ return (jint)GetLengthSid(sid);
}
@@ -924,13 +890,7 @@
{
PSID sid = jlong_to_ptr(address);
LPWSTR string;
-
- if (ConvertSidToStringSid_func == NULL) {
- JNU_ThrowInternalError(env, "Should not get here");
- return NULL;
- }
-
- if ((*ConvertSidToStringSid_func)(sid, &string) == 0) {
+ if (ConvertSidToStringSidW(sid, &string) == 0) {
throwWindowsException(env, GetLastError());
return NULL;
} else {
@@ -947,15 +907,8 @@
{
LPWSTR lpStringSid = jlong_to_ptr(address);
PSID pSid;
-
- if (ConvertStringSidToSid_func == NULL) {
- JNU_ThrowInternalError(env, "Should not get here");
- return (jlong)0;
- }
-
- if ((*ConvertStringSidToSid_func)(lpStringSid, &pSid) == 0)
+ if (ConvertStringSidToSidW(lpStringSid, &pSid) == 0)
throwWindowsException(env, GetLastError());
-
return ptr_to_jlong(pSid);
}
@@ -1137,11 +1090,7 @@
LPCWSTR newFile = jlong_to_ptr(newFileAddress);
LPCWSTR existingFile = jlong_to_ptr(existingFileAddress);
- if (CreateHardLink_func == NULL) {
- JNU_ThrowInternalError(env, "Should not get here");
- return;
- }
- if ((*CreateHardLink_func)(newFile, existingFile, NULL) == 0)
+ if (CreateHardLinkW(newFile, existingFile, NULL) == 0)
throwWindowsException(env, GetLastError());
}
--- a/jdk/src/windows/native/sun/security/provider/WinCAPISeedGenerator.c Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/sun/security/provider/WinCAPISeedGenerator.c Sun Apr 10 10:23:28 2011 -0700
@@ -33,11 +33,6 @@
#include <jni.h>
#include "sun_security_provider_NativeSeedGenerator.h"
-/* Typedefs for runtime linking. */
-typedef BOOL (WINAPI *CryptAcquireContextType)(HCRYPTPROV*, LPCTSTR, LPCTSTR, DWORD, DWORD);
-typedef BOOL (WINAPI *CryptGenRandomType)(HCRYPTPROV, DWORD, BYTE*);
-typedef BOOL (WINAPI *CryptReleaseContextType)(HCRYPTPROV, DWORD);
-
/*
* Get a random seed from the MS CryptoAPI. Return true if successful, false
* otherwise.
@@ -49,48 +44,27 @@
JNIEXPORT jboolean JNICALL Java_sun_security_provider_NativeSeedGenerator_nativeGenerateSeed
(JNIEnv *env, jclass clazz, jbyteArray randArray)
{
- HMODULE lib;
- CryptAcquireContextType acquireContext;
- CryptGenRandomType genRandom;
- CryptReleaseContextType releaseContext;
-
HCRYPTPROV hCryptProv;
jboolean result = JNI_FALSE;
jsize numBytes;
jbyte* randBytes;
- lib = LoadLibrary("ADVAPI32.DLL");
- if (lib == NULL) {
- return result;
- }
-
- acquireContext = (CryptAcquireContextType)GetProcAddress(lib, "CryptAcquireContextA");
- genRandom = (CryptGenRandomType)GetProcAddress(lib, "CryptGenRandom");
- releaseContext = (CryptReleaseContextType)GetProcAddress(lib, "CryptReleaseContext");
-
- if (acquireContext == NULL || genRandom == NULL || releaseContext == NULL) {
- FreeLibrary(lib);
- return result;
- }
-
- if (acquireContext(&hCryptProv, "J2SE", NULL, PROV_RSA_FULL, 0) == FALSE) {
+ if (CryptAcquireContextA(&hCryptProv, "J2SE", NULL, PROV_RSA_FULL, 0) == FALSE) {
/* If CSP context hasn't been created, create one. */
- if (acquireContext(&hCryptProv, "J2SE", NULL, PROV_RSA_FULL,
+ if (CryptAcquireContextA(&hCryptProv, "J2SE", NULL, PROV_RSA_FULL,
CRYPT_NEWKEYSET) == FALSE) {
- FreeLibrary(lib);
return result;
}
}
numBytes = (*env)->GetArrayLength(env, randArray);
randBytes = (*env)->GetByteArrayElements(env, randArray, NULL);
- if (genRandom(hCryptProv, numBytes, randBytes)) {
+ if (CryptGenRandom(hCryptProv, numBytes, randBytes)) {
result = JNI_TRUE;
}
(*env)->ReleaseByteArrayElements(env, randArray, randBytes, 0);
- releaseContext(hCryptProv, 0);
- FreeLibrary(lib);
+ CryptReleaseContext(hCryptProv, 0);
return result;
}
--- a/jdk/src/windows/native/sun/windows/awt_Toolkit.cpp Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_Toolkit.cpp Sun Apr 10 10:23:28 2011 -0700
@@ -528,9 +528,6 @@
tk.m_isActive = FALSE;
- awt_dnd_uninitialize();
- awt_clipboard_uninitialize((JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2));
-
// dispose Direct3D-related resources. This should be done
// before AwtObjectList::Cleanup() as the d3d will attempt to
// shutdown when the last of its windows is disposed of
@@ -539,6 +536,9 @@
AwtObjectList::Cleanup();
AwtFont::Cleanup();
+ awt_dnd_uninitialize();
+ awt_clipboard_uninitialize((JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2));
+
if (tk.m_inputMethodHWnd != NULL) {
::SendMessage(tk.m_inputMethodHWnd, WM_IME_CONTROL, IMC_OPENSTATUSWINDOW, 0);
}
--- a/jdk/test/Makefile Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/Makefile Sun Apr 10 10:23:28 2011 -0700
@@ -261,6 +261,7 @@
# Follow command with ";$(BUNDLE_UP_AND_EXIT)", so it always gets executed.
ZIP_UP_RESULTS = ( $(MKDIR) -p `$(DIRNAME) $(ARCHIVE_BUNDLE)` \
&& $(CD) $(ABS_TEST_OUTPUT_DIR) \
+ && $(CHMOD) -R a+r . \
&& $(ZIP) -q -r $(ARCHIVE_BUNDLE) . )
SUMMARY_TXT = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)")/JTreport/text/summary.txt
STATS_TXT_NAME = Stats.txt
@@ -312,7 +313,9 @@
else \
$(ECHO) "Missing file: $${_summary}" >> $(STATS_TXT); \
fi; \
- $(CAT) $(STATS_TXT); \
+ if [ -f $(STATS_TXT) ] ; then \
+ $(CAT) $(STATS_TXT); \
+ fi; \
$(ZIP_UP_RESULTS) ; \
$(TESTEXIT) \
)
@@ -370,10 +373,10 @@
# Create exclude list for this platform and arch
ifdef NO_EXCLUDES
-$(EXCLUDELIST): $(PROBLEM_LISTS) $(TESTDIRS)
+$(EXCLUDELIST): $(PROBLEM_LISTS) $(TEST_DEPENDENCIES)
@$(ECHO) "NOTHING_EXCLUDED" > $@
else
-$(EXCLUDELIST): $(PROBLEM_LISTS) $(TESTDIRS)
+$(EXCLUDELIST): $(PROBLEM_LISTS) $(TEST_DEPENDENCIES)
@$(RM) $@ $@.temp1 $@.temp2
@(($(CAT) $(PROBLEM_LISTS) | $(EGREP) -- '$(OS_NAME)-all' ) ;\
($(CAT) $(PROBLEM_LISTS) | $(EGREP) -- '$(PLATFORM_OS)' ) ;\
@@ -385,7 +388,7 @@
($(ECHO) "#") ;\
) | $(SED) -e 's@^[\ ]*@@' \
| $(EGREP) -v '^#' > $@.temp1
- @for tdir in $(TESTDIRS) ; do \
+ for tdir in $(TESTDIRS) SOLARIS_10_SH_BUG_NO_EMPTY_FORS ; do \
( ( $(CAT) $@.temp1 | $(EGREP) "^$${tdir}" ) ; $(ECHO) "#" ) >> $@.temp2 ; \
done
@$(ECHO) "# at least one line" >> $@.temp2
@@ -400,11 +403,11 @@
# Running batches of tests with or without samevm
define RunSamevmBatch
$(ECHO) "Running tests in samevm mode: $?"
-$(MAKE) TESTDIRS="$?" USE_JTREG_SAMEVM=true UNIQUE_DIR=$@ jtreg_tests
+$(MAKE) TEST_DEPENDENCIES="$?" TESTDIRS="$?" USE_JTREG_SAMEVM=true UNIQUE_DIR=$@ jtreg_tests
endef
define RunOthervmBatch
$(ECHO) "Running tests in othervm mode: $?"
-$(MAKE) TESTDIRS="$?" USE_JTREG_SAMEVM=false UNIQUE_DIR=$@ jtreg_tests
+$(MAKE) TEST_DEPENDENCIES="$?" TESTDIRS="$?" USE_JTREG_SAMEVM=false UNIQUE_DIR=$@ jtreg_tests
endef
define SummaryInfo
$(ECHO) "########################################################"
@@ -501,7 +504,7 @@
# Stable samevm testruns (minus items from PROBLEM_LIST)
JDK_ALL_TARGETS += jdk_nio2
jdk_nio2: $(call TestDirs, java/nio/Buffer java/nio/ByteOrder \
- java/nio/channels java/nio/BufferPoolMXBean java/nio/MappedByteBuffer)
+ java/nio/channels java/nio/MappedByteBuffer)
$(call SharedLibraryPermissions,java/nio/channels)
$(call RunSamevmBatch)
@@ -684,7 +687,7 @@
################################################################
-# perftest to collect statistics
+# perftest to collect statistics
# Expect JPRT to set JPRT_PACKTEST_HOME.
PERFTEST_HOME = $(TEST_ROOT)/perf
@@ -706,7 +709,7 @@
# vmsqe tests
# Expect JPRT to set JPRT_VMSQE_HOME.
-VMSQE_HOME = /java/sqe/comp/vm/testbase/sqe/vm/current/build/latest/vm
+VMSQE_HOME = $(SLASH_JAVA)/sqe/comp/vm/testbase/sqe/vm/current/build/latest/vm
ifdef JPRT_VMSQE_HOME
VMSQE_HOME = $(JPRT_VMSQE_HOME)
endif
@@ -718,7 +721,7 @@
endif
# Expect JPRT to set JPRT_TONGA3_HOME.
-TONGA3_HOME = /java/sqe//tools/gtee/harness/tonga
+TONGA3_HOME = $(SLASH_JAVA)/sqe/tools/gtee/harness/tonga
ifdef JPRT_TONGA3_HOME
TONGA3_HOME = $(JPRT_TONGA3_HOME)
endif
@@ -771,148 +774,84 @@
# jck tests
-JCK_WORK_DIR = $(ABS_TEST_OUTPUT_DIR)/JCKwork
-JCK_REPORT_DIR = $(ABS_TEST_OUTPUT_DIR)/JCKreport
-JCK_PROPERTIES = $(ABS_TEST_OUTPUT_DIR)/jck.properties
-JCK_CONFIG = $(ABS_TEST_OUTPUT_DIR)/jck.config
-
-JCK_JAVA_EXE = $(PRODUCT_HOME)/bin/java$(EXESUFFIX)
-
-JCK_JAVATEST_JAR = $(JCK_HOME)/lib/javatest.jar
-JCK_JAVATEST = $(ALT_BOOTDIR)/bin/java -jar $(JCK_JAVATEST_JAR)
-
-$(JCK_CONFIG): $(TEST_ROOT)/JCK-$(JCK_BUNDLE_NAME)-$(JCK_RELEASE)-base.jti
- $(RM) $@
- $(MKDIR) -p $(@D)
- $(CP) $< $@
-
-$(JCK_PROPERTIES): $(PRODUCT_HOME) $(JCK_JAVA_EXE)
- $(RM) $@
- $(MKDIR) -p $(@D)
- $(ECHO) "jck.env.compiler.compRefExecute.cmdAsFile=$(JCK_JAVA_EXE)" >> $@
- $(ECHO) "jck.env.compiler.compRefExecute.systemRoot=$(SYSTEMROOT)" >> $@
- $(ECHO) "jck.env.compiler.testCompile.testCompileAPImultiJVM.cmdAsFile=$(JCK_JAVA_EXE)" >> $@
- $(ECHO) "jck.tests.tests=$(JCK_BUNDLE_TESTDIRS)" >> $@
-
-jck_tests: prep $(JCK_HOME) $(JCK_PROPERTIES) $(JCK_CONFIG) $(JCK_JAVATEST_JAR)
- $(MKDIR) -p $(JCK_WORK_DIR)
- ( $(JCK_JAVATEST) \
- -verbose:commands,non-pass \
- -testSuite $(JCK_HOME) \
- -workDir $(JCK_WORK_DIR) \
- -config $(JCK_CONFIG) \
- -set -file $(JCK_PROPERTIES) \
- -runtests \
- -writeReport $(JCK_REPORT_DIR) \
- ) ; $(BUNDLE_UP_AND_EXIT)
-
-PHONY_LIST += jck_tests
-
-################################################################
-
-# jck6 tests
-
-JCK6_RELEASE = 6b
-JCK6_DEFAULT_HOME = $(SLASH_JAVA)/re/jck/$(JCK6_RELEASE)/archive/fcs/binaries
-
-# Expect JPRT to set JPRT_JCK6COMPILER_HOME.
-JCK6COMPILER_HOME = $(JCK6_DEFAULT_HOME)/JCK-compiler-$(JCK6_RELEASE)
-ifdef JPRT_JCK6COMPILER_HOME
- JCK6COMPILER_HOME = $(JPRT_JCK6COMPILER_HOME)
-endif
-
-# Expect JPRT to set JPRT_JCK6RUNTIME_HOME.
-JCK6RUNTIME_HOME = $(JCK6_DEFAULT_HOME)/JCK-runtime-$(JCK6_RELEASE)
-ifdef JPRT_JCK6RUNTIME_HOME
- JCK6RUNTIME_HOME = $(JPRT_JCK6RUNTIME_HOME)
-endif
-
-# Expect JPRT to set JPRT_JCK6DEVTOOLS_HOME.
-JCK6DEVTOOLS_HOME = $(JCK6_DEFAULT_HOME)/JCK-devtools-$(JCK6_RELEASE)
-ifdef JPRT_JCK6DEVTOOLS_HOME
- JCK6DEVTOOLS_HOME = $(JPRT_JCK6DEVTOOLS_HOME)
-endif
-
-jck6_tests: JCK_HOME=$(JCK6_HOME)
-jck6_tests: JCK_RELEASE=$(JCK6_RELEASE)
-jck6_tests: jck_tests
-
-jck6compiler: JCK6_HOME=$(JCK6COMPILER_HOME)
-jck6compiler: JCK_BUNDLE_NAME=compiler
-jck6compiler: jck6_tests
-
-jck6compiler_lang: JCK_BUNDLE_TESTDIRS=lang
-jck6compiler_lang: jck6compiler
-
-jck6runtime: JCK6_HOME=$(JCK6RUNTIME_HOME)
-jck6runtime: JCK_BUNDLE_NAME=runtime
-jck6runtime: jck6_tests
-
-jck6runtime_lang: JCK_BUNDLE_TESTDIRS=lang
-jck6runtime_lang: jck6runtime
-
-jck6devtools: JCK6_HOME=$(JCK6DEVTOOLS_HOME)
-jck6devtools: JCK_BUNDLE_NAME=devtools
-jck6devtools: jck6_tests
-
-jck6devtools_lang: JCK_BUNDLE_TESTDIRS=lang
-jck6devtools_lang: jck6devtools
-
-PHONY_LIST += jck6compiler jck6runtime jck6devtools jck6_tests \
- jck6compiler_lang jck6runtime_lang jck6devtools_lang
-
-################################################################
-
-# jck7 tests
-
-JCK7_RELEASE = 7
-JCK7_DEFAULT_HOME = $(SLASH_JAVA)/re/jck/$(JCK7_RELEASE)/archive/fcs/binaries
+# Default is to use jck 7 from /java/re
+JCK7_DEFAULT_HOME = $(SLASH_JAVA)/re/jck/7/promoted/latest/binaries
# Expect JPRT to set JPRT_JCK7COMPILER_HOME.
-JCK7COMPILER_HOME = $(JCK7_DEFAULT_HOME)/JCK-compiler-$(JCK7_RELEASE)
+JCK7COMPILER_HOME = $(JCK7_DEFAULT_HOME)/JCK-compiler-7
ifdef JPRT_JCK7COMPILER_HOME
- JCK7COMPILER_HOME = $(JPRT_JCK7COMPILER_HOME)
+ JCK7COMPILER_HOME = $(JPRT_JCK7COMPILER_HOME)/JCK-compiler-7
endif
# Expect JPRT to set JPRT_JCK7RUNTIME_HOME.
-JCK7RUNTIME_HOME = $(JCK7_DEFAULT_HOME)/JCK-runtime-$(JCK7_RELEASE)
+JCK7RUNTIME_HOME = $(JCK7_DEFAULT_HOME)/JCK-runtime-7
ifdef JPRT_JCK7RUNTIME_HOME
- JCK7RUNTIME_HOME = $(JPRT_JCK7RUNTIME_HOME)
+ JCK7RUNTIME_HOME = $(JPRT_JCK7RUNTIME_HOME)/JCK-runtime-7
endif
# Expect JPRT to set JPRT_JCK7DEVTOOLS_HOME.
-JCK7DEVTOOLS_HOME = $(JCK7_DEFAULT_HOME)/JCK-devtools-$(JCK7_RELEASE)
+JCK7DEVTOOLS_HOME = $(JCK7_DEFAULT_HOME)/JCK-devtools-7
ifdef JPRT_JCK7DEVTOOLS_HOME
- JCK7DEVTOOLS_HOME = $(JPRT_JCK7DEVTOOLS_HOME)
+ JCK7DEVTOOLS_HOME = $(JPRT_JCK7DEVTOOLS_HOME)/JCK-devtools-7
+endif
+
+# The jtjck.jar utility to use to run the tests
+JTJCK_JAR = $(JCK_HOME)/lib/jtjck.jar
+JTJCK_JAVA_ARGS = -XX:MaxPermSize=256m -Xmx512m
+JTJCK_OPTIONS = -headless -v
+
+# Default tests to run
+ifndef JCK_COMPILER_TESTS
+ JCK_COMPILER_TESTS =
+endif
+ifndef JCK_RUNTIME_TESTS
+ JCK_RUNTIME_TESTS =
+endif
+ifndef JCK_DEVTOOLS_TESTS
+ JCK_DEVTOOLS_TESTS =
endif
-jck7_tests: JCK_HOME=$(JCK7_HOME)
-jck7_tests: JCK_RELEASE=$(JCK7_RELEASE)
-jck7_tests: jck_tests
-
-jck7compiler: JCK7_HOME=$(JCK7COMPILER_HOME)
-jck7compiler: JCK_BUNDLE_NAME=compiler
-jck7compiler: jck7_tests
-
-jck7compiler_lang: JCK_BUNDLE_TESTDIRS=lang
-jck7compiler_lang: jck7compiler
+# Generic rule used to run jck tests
+_generic_jck_tests: prep $(PRODUCT_HOME) $(EXCLUDELIST)
+ @$(EXPAND) $(EXCLUDELIST) \
+ | $(CUT) -d' ' -f1 \
+ | $(SED) -e 's@^@Excluding: @'
+ ( $(CD) $(ABS_TEST_OUTPUT_DIR) && \
+ $(PRODUCT_HOME)/bin/java $(JTJCK_JAVA_ARGS) \
+ -jar "$(JTJCK_JAR)" \
+ $(JTJCK_OPTIONS) \
+ -r:$(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)")/JTreport \
+ -w:$(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)")/JTwork \
+ -jdk:$(shell $(GETMIXEDPATH) "$(PRODUCT_HOME)") \
+ $(TESTDIRS) \
+ ) ; $(BUNDLE_UP_AND_EXIT)
-jck7runtime: JCK7_HOME=$(JCK7RUNTIME_HOME)
-jck7runtime: JCK_BUNDLE_NAME=runtime
-jck7runtime: jck7_tests
-
-jck7runtime_lang: JCK_BUNDLE_TESTDIRS=lang
-jck7runtime_lang: jck7runtime
+# JCK7 compiler tests
+jck7compiler:
+ $(MAKE) UNIQUE_DIR=$@ \
+ JCK_HOME=$(JCK7COMPILER_HOME) \
+ TESTDIRS="$(JCK_COMPILER_TESTS)" \
+ _generic_jck_tests
-jck7devtools: JCK7_HOME=$(JCK7DEVTOOLS_HOME)
-jck7devtools: JCK_BUNDLE_NAME=devtools
-jck7devtools: jck7_tests
+# JCK7 runtime tests
+jck7runtime:
+ $(MAKE) UNIQUE_DIR=$@ \
+ JCK_HOME=$(JCK7RUNTIME_HOME) \
+ TESTDIRS="$(JCK_RUNTIME_TESTS)" \
+ _generic_jck_tests
-jck7devtools_lang: JCK_BUNDLE_TESTDIRS=lang
-jck7devtools_lang: jck7devtools
+# JCK7 devtools tests
+jck7devtools:
+ $(MAKE) UNIQUE_DIR=$@ \
+ JCK_HOME=$(JCK7DEVTOOLS_HOME) \
+ TESTDIRS="$(JCK_DEVTOOLS_TESTS)" \
+ _generic_jck_tests
-PHONY_LIST += jck7compiler jck7runtime jck7devtools jck7_tests \
- jck7compiler_lang jck7runtime_lang jck7devtools_lang
+# Run all 3 sets of JCK7 tests
+jck_all: jck7runtime jck7devtools jck7compiler
+
+PHONY_LIST += jck_all _generic_jck_tests \
+ jck7compiler jck7runtime jck7devtools
################################################################
--- a/jdk/test/ProblemList.txt Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/ProblemList.txt Sun Apr 10 10:23:28 2011 -0700
@@ -690,6 +690,9 @@
# jdk_util
+# Filed 7027061
+java/util/Locale/Bug6989440.java windows-all
+
# Filed 6933803
java/util/concurrent/ThreadPoolExecutor/CoreThreadTimeOut.java generic-all
--- a/jdk/test/com/sun/jdi/PrivateTransportTest.sh Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/com/sun/jdi/PrivateTransportTest.sh Sun Apr 10 10:23:28 2011 -0700
@@ -1,7 +1,7 @@
#!/bin/ksh -p
#
-# Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -99,6 +99,8 @@
libdir=${TESTCLASSES}
+is_windows=false
+is_cygwin=false
case `uname -s` in
SunOS)
libarch=`uname -p`
@@ -126,10 +128,13 @@
libloc=`dirname ${xx}`
;;
Windows*)
+ is_windows=true
libloc=${jreloc}/bin
sep=';'
;;
CYGWIN*)
+ is_windows=true
+ is_cygwin=true
libloc=${jreloc}/bin
sep=':'
@@ -176,7 +181,18 @@
#
CP="-classpath \"${TESTCLASSES}\""
#
-DEBUGGEEFLAGS="$DEBUGGEEFLAGS -agentlib:jdwp=transport=${private_transport},server=y,suspend=n"
+if [ "$is_windows" = "true" ]; then
+ if [ "$is_cygwin" = "true" ]; then
+ win_fullpath=`cygpath -m "$fullpath" \
+ | sed -e 's#/#\\\\\\\\#g' -e 's/\.dll//'`
+ else
+ win_fullpath=`echo "$fullpath" \
+ | sed -e 's#/#\\\\\\\\#g' -e 's/\.dll//'`
+ fi
+ DEBUGGEEFLAGS="$DEBUGGEEFLAGS -agentlib:jdwp=transport=${win_fullpath},server=y,suspend=n"
+else
+ DEBUGGEEFLAGS="$DEBUGGEEFLAGS -agentlib:jdwp=transport=${private_transport},server=y,suspend=n"
+fi
echo ${TESTJAVA}/bin/java ${DEBUGGEEFLAGS} ${CP} ${TARGETCLASS}
eval ${TESTJAVA}/bin/java ${DEBUGGEEFLAGS} ${CP} ${TARGETCLASS}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Toolkit/Headless/GetPrintJob/GetPrintJob.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,48 @@
+/*
+@test
+@bug 7023011
+@library ../../../regtesthelpers
+@build Sysout
+@summary Toolkit.getPrintJob() throws wrong exceptions
+@author andrei dmitriev: area=awt.headless
+@run main GetPrintJob
+ */
+
+import java.awt.*;
+import java.util.Properties;
+import test.java.awt.regtesthelpers.Sysout;
+/*
+ * In headfull mode we should always getting NPE on the getPrintJob() call if frame == null.
+ */
+
+public class GetPrintJob {
+
+ public static void main(String[] s) {
+ boolean stage1Passed = false;
+ boolean stage2Passed = false;
+
+ try {
+ Toolkit.getDefaultToolkit().getPrintJob(
+ (Frame) null, "title", new Properties());
+ } catch (NullPointerException e) {
+ stage1Passed = true;
+ Sysout.println("Stage 1 passed. getPrintJob(null, String, property) has thrown NPE.");
+ }
+ if (!stage1Passed) {
+ throw new RuntimeException("getPrintJob() should have thrown NPE but didn't.");
+ }
+
+ try {
+ Toolkit.getDefaultToolkit().getPrintJob(
+ (Frame) null, "title", new JobAttributes(), new PageAttributes());
+ } catch (NullPointerException e) {
+ stage2Passed = true;
+ Sysout.println("Stage 2 passed. getPrintJob(null, String, jobAttrs, pageAttr) has thrown NPE.");
+ }
+ if (!stage2Passed) {
+ throw new RuntimeException("getPrintJob() should have thrown NPE but didn't.");
+ }
+
+ Sysout.println("Test PASSED");
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Toolkit/Headless/GetPrintJob/GetPrintJobHeadless.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,50 @@
+/*
+@test
+@bug 7023011
+@library ../../../regtesthelpers
+@build Sysout
+@summary Toolkit.getPrintJob() throws wrong exceptions
+@author andrei dmitriev: area=awt.headless
+@run main/othervm -Djava.awt.headless=true GetPrintJobHeadless
+ */
+
+/*
+ * In headless mode we should always getting NPE on the getPrintJob() call
+ */
+import java.awt.*;
+import java.util.Properties;
+import test.java.awt.regtesthelpers.Sysout;
+
+public class GetPrintJobHeadless {
+
+ public static void main(String[] s) {
+ boolean stage1Passed = false;
+ boolean stage2Passed = false;
+
+ try {
+ Toolkit.getDefaultToolkit().getPrintJob(
+ (Frame) null, "title", new Properties());
+ } catch (NullPointerException e) {
+ stage1Passed = true;
+ e.printStackTrace();
+ Sysout.println("Stage 1 passed. getPrintJob(null, String, property) has thrown NPE.");
+ }
+ if (!stage1Passed) {
+ throw new RuntimeException("getPrintJob() should have thrown NPE but didn't.");
+ }
+
+ try {
+ Toolkit.getDefaultToolkit().getPrintJob(
+ (Frame) null, "title", new JobAttributes(), new PageAttributes());
+ } catch (NullPointerException e) {
+ stage2Passed = true;
+ e.printStackTrace();
+ Sysout.println("Stage 2 passed. getPrintJob(null, String, jobAttrs, pageAttr) has thrown NPE.");
+ }
+ if (!stage2Passed) {
+ throw new RuntimeException("getPrintJob() should have thrown NPE but didn't.");
+ }
+
+ Sysout.println("Test PASSED");
+ }
+}
--- a/jdk/test/java/awt/image/GetSamplesTest.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/java/awt/image/GetSamplesTest.java Sun Apr 10 10:23:28 2011 -0700
@@ -23,9 +23,9 @@
/*
* @test
- * @bug 6735275
- * @summary Test verifies that SampleModel.getSamples() throws an appropriate
- * exception if coordinates are not in bounds.
+ * @bug 6735275 6993561
+ * @summary Test verifies that SampleModel.getSamples() SampleModel.setSamples()
+ * throw an appropriate exception if coordinates are not in bounds.
*
* @run main GetSamplesTest
*/
@@ -75,6 +75,7 @@
try {
sm.getSamples(Integer.MAX_VALUE, 0, 1, 1, 0, iArray, db);
+ sm.setSamples(Integer.MAX_VALUE, 0, 1, 1, 0, iArray, db);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
iOk = true;
@@ -82,6 +83,7 @@
try {
sm.getSamples(Integer.MAX_VALUE, 0, 1, 1, 0, fArray, db);
+ sm.setSamples(Integer.MAX_VALUE, 0, 1, 1, 0, fArray, db);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
fOk = true;
@@ -89,6 +91,7 @@
try {
sm.getSamples(0, Integer.MAX_VALUE, 1, 1, 0, dArray, db);
+ sm.setSamples(0, Integer.MAX_VALUE, 1, 1, 0, dArray, db);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
dOk = true;
--- a/jdk/test/java/lang/Throwable/SuppressedExceptions.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/java/lang/Throwable/SuppressedExceptions.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -26,7 +26,7 @@
/*
* @test
- * @bug 6911258 6962571 6963622 6991528
+ * @bug 6911258 6962571 6963622 6991528 7005628
* @summary Basic tests of suppressed exceptions
* @author Joseph D. Darcy
*/
@@ -50,14 +50,6 @@
} catch (IllegalArgumentException iae) {
; // Expected
}
-
- throwable.addSuppressed(null); // Immutable suppression list
- try {
- throwable.addSuppressed(throwable);
- throw new RuntimeException("IllegalArgumentException for self-suppresion not thrown.");
- } catch (IllegalArgumentException iae) {
- ; // Expected
- }
}
private static void basicSupressionTest() {
@@ -153,19 +145,19 @@
(byte)0x02, (byte)0x00, (byte)0x00, (byte)0x78, (byte)0x70,
};
- ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
- ObjectInputStream ois = new ObjectInputStream(bais);
+ try(ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
+ ObjectInputStream ois = new ObjectInputStream(bais)) {
+ Object o = ois.readObject();
+ Throwable throwable = (Throwable) o;
- Object o = ois.readObject();
- Throwable throwable = (Throwable) o;
+ System.err.println("TESTING SERIALIZED EXCEPTION");
- System.err.println("TESTING SERIALIZED EXCEPTION");
-
- Throwable[] t0 = throwable.getSuppressed();
- if (t0.length != 0) { // Will fail if t0 is null.
- throw new RuntimeException(message);
+ Throwable[] t0 = throwable.getSuppressed();
+ if (t0.length != 0) { // Will fail if t0 is null.
+ throw new RuntimeException(message);
+ }
+ throwable.printStackTrace();
}
- throwable.printStackTrace();
}
private static void selfReference() {
@@ -183,8 +175,7 @@
}
private static void noModification() {
- Throwable t = new Throwable();
- t.addSuppressed(null);
+ Throwable t = new NoSuppression(false);
Throwable[] t0 = t.getSuppressed();
if (t0.length != 0)
@@ -196,5 +187,24 @@
t0 = t.getSuppressed();
if (t0.length != 0)
throw new RuntimeException("Bad nonzero length of suppressed exceptions.");
+
+ Throwable suppressed = new ArithmeticException();
+ t = new NoSuppression(true); // Suppression enabled
+ // Make sure addSuppressed(null) throws an NPE
+ try {
+ t.addSuppressed(null);
+ } catch(NullPointerException e) {
+ ; // Expected
+ }
+ t.addSuppressed(suppressed);
+ t0 = t.getSuppressed();
+ if (t0.length != 1 || t0[0] != suppressed)
+ throw new RuntimeException("Expected suppression did not occur.");
+ }
+
+ private static class NoSuppression extends Throwable {
+ public NoSuppression(boolean enableSuppression) {
+ super("The medium.", null, enableSuppression);
+ }
}
}
--- a/jdk/test/java/lang/annotation/PackageMain.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/java/lang/annotation/PackageMain.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -21,8 +21,6 @@
* questions.
*/
-import java.lang.annotation.Documented;
-
public class PackageMain {
public static void main(String[] args) throws Exception {
Class<?> c = Class.forName("foo.bar.Baz");
@@ -30,7 +28,7 @@
System.out.println("cl=" + c.getClassLoader());
Package p = c.getPackage();
System.out.println("p=" + p);
- Documented d = p.getAnnotation(Documented.class);
+ Deprecated d = p.getAnnotation(Deprecated.class);
if (d == null) throw new Error();
}
}
--- a/jdk/test/java/lang/annotation/package-info.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/java/lang/annotation/package-info.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -31,7 +31,7 @@
* @run main PackageMain
*/
-@java.lang.annotation.Documented
+@Deprecated
package foo.bar;
class Baz {}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/management/BufferPoolMXBean/Basic.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please 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 6606598 7024172
+ * @summary Unit test for java.lang.management.BufferPoolMXBean
+ * @run main/othervm Basic
+ */
+
+import java.nio.ByteBuffer;
+import java.nio.MappedByteBuffer;
+import java.nio.file.Path;
+import java.nio.file.Files;
+import static java.nio.file.StandardOpenOption.*;
+import java.nio.channels.FileChannel;
+import java.lang.management.BufferPoolMXBean;
+import java.lang.management.ManagementFactory;
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+import java.lang.ref.WeakReference;
+import java.util.*;
+
+public class Basic {
+
+ // static fields to ensure buffers aren't GC'ed
+ static List<ByteBuffer> buffers;
+ static MappedByteBuffer mbb;
+
+ // check counters
+ static void check(List<BufferPoolMXBean> pools,
+ int minBufferCount,
+ long minTotalCapacity)
+ {
+ int bufferCount = 0;
+ long totalCap = 0;
+ long totalMem = 0;
+ for (BufferPoolMXBean pool: pools) {
+ bufferCount += pool.getCount();
+ totalCap += pool.getTotalCapacity();
+ totalMem += pool.getMemoryUsed();
+ }
+ if (bufferCount < minBufferCount)
+ throw new RuntimeException("Count less than expected");
+ if (totalMem < minTotalCapacity)
+ throw new RuntimeException("Memory usage less than expected");
+ if (totalCap < minTotalCapacity)
+ throw new RuntimeException("Total capacity less than expected");
+ }
+
+ public static void main(String[] args) throws Exception {
+ Random rand = new Random();
+
+ // allocate a few direct buffers
+ int bufferCount = 5 + rand.nextInt(20);
+ buffers = new ArrayList<ByteBuffer>(bufferCount);
+ long totalCapacity = 0L;
+ for (int i=0; i<bufferCount; i++) {
+ int cap = 1024 + rand.nextInt(4096);
+ buffers.add( ByteBuffer.allocateDirect(cap) );
+ totalCapacity += cap;
+ }
+
+ // create a mapped buffer
+ Path tmpfile = Files.createTempFile("blah", null);
+ tmpfile.toFile().deleteOnExit();
+ try (FileChannel fc = FileChannel.open(tmpfile, READ, WRITE)) {
+ mbb = fc.map(FileChannel.MapMode.READ_WRITE, 10, 100);
+ bufferCount++;
+ totalCapacity += mbb.capacity();
+ }
+
+ // use platform MXBeans directly
+ List<BufferPoolMXBean> pools =
+ ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
+ check(pools, bufferCount, totalCapacity);
+
+ // use MBeanServer
+ MBeanServer server = ManagementFactory.getPlatformMBeanServer();
+ Set<ObjectName> mbeans = server.queryNames(
+ new ObjectName("java.nio:type=BufferPool,*"), null);
+ pools = new ArrayList<BufferPoolMXBean>();
+ for (ObjectName name: mbeans) {
+ BufferPoolMXBean pool = ManagementFactory
+ .newPlatformMXBeanProxy(server, name.toString(), BufferPoolMXBean.class);
+ pools.add(pool);
+ }
+ check(pools, bufferCount, totalCapacity);
+
+ // attempt to unmap mapped buffer
+ WeakReference<MappedByteBuffer> ref = new WeakReference<>(mbb);
+ mbb = null;
+ do {
+ System.gc();
+ Thread.sleep(250);
+ } while (ref.get() != null);
+ }
+}
--- a/jdk/test/java/lang/management/ManagementFactory/GetPlatformMXBeans.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/java/lang/management/ManagementFactory/GetPlatformMXBeans.java Sun Apr 10 10:23:28 2011 -0700
@@ -23,23 +23,26 @@
/*
* @test
- * @bug 6610094
- * @summary Basic unit test of ManagementFactory.getPlatformMXBeans()
- * and also PlatformManagedObject.getObjectName()
+ * @bug 6610094 7024172
+ * @summary Basic unit test of ManagementFactory.getPlatformMXBean(s)
+ * methods and PlatformManagedObject.getObjectName()
* @author Mandy Chung
*
* @run main GetPlatformMXBeans
*/
import java.lang.management.*;
-import static java.lang.management.ManagementFactory.*;
+import java.io.IOException;
import java.util.*;
import javax.management.*;
+import static java.lang.management.ManagementFactory.*;
+
public class GetPlatformMXBeans {
private static MBeanServer platformMBeanServer =
getPlatformMBeanServer();
public static void main(String[] argv) throws Exception {
+ // singleton platform MXBean
checkPlatformMXBean(getClassLoadingMXBean(),
ClassLoadingMXBean.class,
CLASS_LOADING_MXBEAN_NAME);
@@ -58,17 +61,28 @@
checkPlatformMXBean(getThreadMXBean(),
ThreadMXBean.class,
THREAD_MXBEAN_NAME);
+
+ // the following MXBean can have more than one instances
checkGarbageCollectorMXBeans(getGarbageCollectorMXBeans());
checkMemoryManagerMXBeans(getMemoryManagerMXBeans());
checkMemoryPoolMXBeans(getMemoryPoolMXBeans());
+
+ // check invalid platform MXBean
+ checkInvalidPlatformMXBean();
}
private static <T extends PlatformManagedObject>
- void checkPlatformMXBean(T obj, Class<T> mxbeanInterface,
- String mxbeanName) throws Exception
+ void checkPlatformMXBean(T obj, Class<T> mxbeanInterface,
+ String mxbeanName)
+ throws Exception
{
- int numElements = (obj != null ? 1 : 0);
- // verify local list of platform MXBeans
+ // getPlatformMXBean may return null if the mxbean is not implemented
+ PlatformManagedObject mxbean = getPlatformMXBean(mxbeanInterface);
+ if (obj != mxbean) {
+ throw new RuntimeException("Singleton MXBean returned not matched");
+ }
+
+ int numElements = obj == null ? 0 : 1;
List<? extends PlatformManagedObject> mxbeans =
getPlatformMXBeans(mxbeanInterface);
if (mxbeans.size() != numElements) {
@@ -77,24 +91,46 @@
}
if (obj != null) {
- PlatformManagedObject pmo = mxbeans.get(0);
- if (obj != pmo) {
+ if (obj != mxbeans.get(0)) {
throw new RuntimeException("The list returned by getPlatformMXBeans"
+ " not matched");
}
ObjectName on = new ObjectName(mxbeanName);
- if (!on.equals(pmo.getObjectName())) {
+ if (!on.equals(mxbean.getObjectName())) {
throw new RuntimeException("Unmatched ObjectName " +
- pmo.getObjectName() + " Expected = " + on);
+ mxbean.getObjectName() + " Expected = " + on);
}
+ checkRemotePlatformMXBean(obj, platformMBeanServer,
+ mxbeanInterface, mxbeanName);
+ }
+ }
+
+ // verify platform MXBeans in the platform MBeanServer
+ private static <T extends PlatformManagedObject>
+ void checkRemotePlatformMXBean(T obj,
+ MBeanServerConnection mbs,
+ Class<T> mxbeanInterface,
+ String mxbeanName)
+ throws Exception
+ {
+ PlatformManagedObject mxbean = getPlatformMXBean(mbs, mxbeanInterface);
+ if ((obj == null && mxbean != null) || (obj != null && mxbean == null)) {
+ throw new RuntimeException("Singleton MXBean returned not matched");
}
- // verify platform MXBeans in the platform MBeanServer
- mxbeans = getPlatformMXBeans(platformMBeanServer, mxbeanInterface);
+ int numElements = obj == null ? 0 : 1;
+ List<? extends PlatformManagedObject> mxbeans =
+ getPlatformMXBeans(mbs, mxbeanInterface);
if (mxbeans.size() != numElements) {
throw new RuntimeException("Unmatched number of platform MXBeans "
+ mxbeans.size() + ". Expected = " + numElements);
}
+
+ ObjectName on = new ObjectName(mxbeanName);
+ if (!on.equals(mxbean.getObjectName())) {
+ throw new RuntimeException("Unmatched ObjectName " +
+ mxbean.getObjectName() + " Expected = " + on);
+ }
}
private static void checkMemoryManagerMXBeans(List<MemoryManagerMXBean> objs)
@@ -148,6 +184,14 @@
void checkPlatformMXBeans(List<T> objs, Class<T> mxbeanInterface)
throws Exception
{
+ try {
+ getPlatformMXBean(mxbeanInterface);
+ // mxbeanInterface is not a singleton
+ throw new RuntimeException(mxbeanInterface + ": not a singleton MXBean");
+ } catch (IllegalArgumentException e) {
+ // expect IAE
+ }
+
// verify local list of platform MXBeans
List<? extends PlatformManagedObject> mxbeans =
getPlatformMXBeans(mxbeanInterface);
@@ -177,4 +221,40 @@
+ mxbeans.size() + ". Expected = " + objs.size());
}
}
+
+ interface FakeMXBean extends PlatformManagedObject {};
+
+ private static void checkInvalidPlatformMXBean() throws IOException {
+ try {
+ getPlatformMXBean(FakeMXBean.class);
+ // mxbeanInterface is not a singleton
+ throw new RuntimeException("Expect IllegalArgumentException but not thrown");
+ } catch (IllegalArgumentException e) {
+ // expect IAE
+ }
+
+ try {
+ getPlatformMXBeans(FakeMXBean.class);
+ // mxbeanInterface is not a singleton
+ throw new RuntimeException("Expect IllegalArgumentException but not thrown");
+ } catch (IllegalArgumentException e) {
+ // expect IAE
+ }
+
+ try {
+ getPlatformMXBean(platformMBeanServer, FakeMXBean.class);
+ // mxbeanInterface is not a singleton
+ throw new RuntimeException("Expect IllegalArgumentException but not thrown");
+ } catch (IllegalArgumentException e) {
+ // expect IAE
+ }
+
+ try {
+ getPlatformMXBeans(platformMBeanServer, FakeMXBean.class);
+ // mxbeanInterface is not a singleton
+ throw new RuntimeException("Expect IllegalArgumentException but not thrown");
+ } catch (IllegalArgumentException e) {
+ // expect IAE
+ }
+ }
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/management/PlatformLoggingMXBean/LoggingMXBeanTest.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,229 @@
+/*
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please 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 7024172
+ * @summary Test if proxy for PlatformLoggingMXBean is equivalent
+ * to proxy for LoggingMXBean
+ *
+ * @build LoggingMXBeanTest
+ * @run main LoggingMXBeanTest
+ */
+
+import java.lang.management.*;
+import javax.management.MBeanServer;
+import java.util.logging.*;
+import java.util.ArrayList;
+import java.util.List;
+
+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";
+
+ public static void main(String[] argv) throws Exception {
+ MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
+ LoggingMXBean proxy =
+ ManagementFactory.newPlatformMXBeanProxy(mbs,
+ LogManager.LOGGING_MXBEAN_NAME,
+ LoggingMXBean.class);
+
+ // test LoggingMXBean proxy
+ LoggingMXBeanTest p = new LoggingMXBeanTest(proxy);
+
+ // check if the attributes implemented by PlatformLoggingMXBean
+ // and LoggingMXBean return the same value
+ PlatformLoggingMXBean mxbean =
+ ManagementFactory.getPlatformMXBean(mbs, PlatformLoggingMXBean.class);
+
+ checkAttributes(proxy, mxbean);
+ }
+
+ // same verification as in java/util/logging/LoggingMXBeanTest2
+ public LoggingMXBeanTest(LoggingMXBean mbean) throws Exception {
+
+ Logger logger1 = Logger.getLogger( LOGGER_NAME_1 );
+ logger1.setLevel(Level.FINE);
+ Logger logger2 = Logger.getLogger( LOGGER_NAME_2 );
+ logger2.setLevel(null);
+
+ /*
+ * Check for the existence of our new Loggers
+ */
+ System.out.println("Test Logger Name retrieval (getLoggerNames)");
+ boolean log1 = false, log2 = false;
+ List<String> loggers = mbean.getLoggerNames();
+ if (loggers == null || loggers.size() < 2) {
+ throw new RuntimeException(
+ "Could not Detect the presense of the new Loggers");
+ }
+
+ for (String logger : loggers) {
+ if (logger.equals(LOGGER_NAME_1)) {
+ log1 = true;
+ System.out.println(" : Found new Logger : " + logger);
+ }
+ if (logger.equals(LOGGER_NAME_2)) {
+ log2 = true;
+ System.out.println(" : Found new Logger : " + logger);
+ }
+ }
+ if ( log1 && log2 )
+ System.out.println(" : PASSED." );
+ else {
+ System.out.println(" : FAILED. Could not Detect the new Loggers." );
+ throw new RuntimeException(
+ "Could not Detect the presense of the new Loggers");
+ }
+
+ System.out.println("Test getLoggerLevel");
+ String l1 = mbean.getLoggerLevel(LOGGER_NAME_1);
+ System.out.println(" : Level for Logger " + LOGGER_NAME_1 + " : " + l1);
+ if (!l1.equals(Level.FINE.getName())) {
+ throw new RuntimeException(
+ "Expected level for " + LOGGER_NAME_1 + " = " +
+ Level.FINE.getName() + " but got " + l1);
+ }
+ String l2 = mbean.getLoggerLevel(LOGGER_NAME_2);
+ System.out.println(" : Level for Logger " + LOGGER_NAME_2 + " : " + l2);
+ if (!l2.equals("")) {
+ throw new RuntimeException(
+ "Expected level for " + LOGGER_NAME_2 + " = \"\"" +
+ " but got " + l2);
+ }
+ String l3 = mbean.getLoggerLevel(UNKNOWN_LOGGER_NAME);
+ System.out.println(" : Level for unknown logger : " + l3);
+ if (l3 != null) {
+ throw new RuntimeException(
+ "Expected level for " + UNKNOWN_LOGGER_NAME + " = null" +
+ " but got " + l3);
+ }
+
+ System.out.println("Test setLoggerLevel");
+ mbean.setLoggerLevel(LOGGER_NAME_1, "INFO");
+ System.out.println(" : Set Level for Logger " + LOGGER_NAME_1 + " to: INFO");
+ Level l = logger1.getLevel();
+ if (l != Level.INFO) {
+ throw new RuntimeException(
+ "Expected level for " + LOGGER_NAME_1 + " = " +
+ Level.INFO + " but got " + l);
+ }
+
+ mbean.setLoggerLevel(LOGGER_NAME_2, "SEVERE");
+ System.out.println(" : Set Level for Logger " + LOGGER_NAME_2 + " to: SERVER");
+ l = logger2.getLevel();
+ if (l != Level.SEVERE) {
+ throw new RuntimeException(
+ "Expected level for " + LOGGER_NAME_2 + " = " +
+ Level.SEVERE+ " but got " + l);
+ }
+
+ mbean.setLoggerLevel(LOGGER_NAME_1, null);
+ System.out.println(" : Set Level for Logger " + LOGGER_NAME_1 + " to: null");
+ l = logger1.getLevel();
+ if (l != null) {
+ throw new RuntimeException(
+ "Expected level for " + LOGGER_NAME_1 + " = null " +
+ " but got " + l);
+ }
+
+ boolean iaeCaught = false;
+ System.out.println(" : Set Level for unknown Logger to: FINE");
+ try {
+ mbean.setLoggerLevel(UNKNOWN_LOGGER_NAME, "FINE");
+ } catch (IllegalArgumentException e) {
+ // expected
+ iaeCaught = true;
+ System.out.println(" : IllegalArgumentException caught as expected");
+ }
+ if (!iaeCaught) {
+ throw new RuntimeException(
+ "Expected IllegalArgumentException for setting level for " +
+ UNKNOWN_LOGGER_NAME + " not thrown");
+ }
+ iaeCaught = false;
+ System.out.println(" : Set Level for Logger " + LOGGER_NAME_1 + " to: DUMMY");
+ try {
+ mbean.setLoggerLevel(LOGGER_NAME_1, "DUMMY");
+ } catch (IllegalArgumentException e) {
+ // expected
+ iaeCaught = true;
+ System.out.println(" : IllegalArgumentException caught as expected");
+ }
+ if (!iaeCaught) {
+ throw new RuntimeException(
+ "Expected IllegalArgumentException for invalid level.");
+ }
+
+
+ System.out.println("Test getParentLoggerName");
+ String p1 = mbean.getParentLoggerName(LOGGER_NAME_2);
+ System.out.println(" : Parent Logger for " + LOGGER_NAME_2 + " : " + p1);
+ if (!p1.equals(LOGGER_NAME_1)) {
+ throw new RuntimeException(
+ "Expected parent for " + LOGGER_NAME_2 + " = " +
+ LOGGER_NAME_1 + " but got " + p1);
+ }
+ String p2 = mbean.getParentLoggerName("");
+ System.out.println(" : Parent Logger for \"\" : " + p2);
+ if (!p2.equals("")) {
+ throw new RuntimeException(
+ "Expected parent for root logger \"\" = \"\"" +
+ " but got " + p2);
+ }
+ String p3 = mbean.getParentLoggerName(UNKNOWN_LOGGER_NAME);
+ System.out.println(" : Parent Logger for unknown logger : " + p3);
+ if (p3 != null) {
+ throw new RuntimeException(
+ "Expected level for " + UNKNOWN_LOGGER_NAME + " = null" +
+ " but got " + p3);
+ }
+ }
+
+ private static void checkAttributes(LoggingMXBean mxbean1,
+ PlatformLoggingMXBean mxbean2) {
+ // verify logger names
+ List<String> loggers1 = mxbean1.getLoggerNames();
+ List<String> loggers2 = mxbean2.getLoggerNames();
+ if (loggers1.size() != loggers2.size())
+ throw new RuntimeException("LoggerNames: unmatched number of entries");
+ List<String> loggers3 = new ArrayList<>(loggers1);
+ loggers3.removeAll(loggers2);
+ if (loggers3.size() != 0)
+ throw new RuntimeException("LoggerNames: unmatched loggers");
+
+ // verify logger's level and parent
+ for (String logger : loggers1) {
+ if (!mxbean1.getLoggerLevel(logger)
+ .equals(mxbean2.getLoggerLevel(logger)))
+ throw new RuntimeException(
+ "LoggerLevel: unmatched level for " + logger);
+ if (!mxbean1.getParentLoggerName(logger)
+ .equals(mxbean2.getParentLoggerName(logger)))
+ throw new RuntimeException(
+ "ParentLoggerName: unmatched parent logger's name for " + logger);
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/management/PlatformLoggingMXBean/PlatformLoggingMXBeanTest.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,276 @@
+/*
+ * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please 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 6876135 7024172
+ *
+ * @summary Test PlatformLoggingMXBean
+ * This test performs similar testing as
+ * java/util/logging/LoggingMXBeanTest.
+ *
+ * @build PlatformLoggingMXBeanTest
+ * @run main PlatformLoggingMXBeanTest
+ */
+
+import javax.management.*;
+import java.lang.management.ManagementFactory;
+import java.lang.management.PlatformLoggingMXBean;
+import java.util.logging.*;
+import java.util.List;
+
+public class PlatformLoggingMXBeanTest
+{
+
+ ObjectName objectName = null;
+ static String LOGGER_NAME_1 = "com.sun.management.Logger1";
+ static String LOGGER_NAME_2 = "com.sun.management.Logger2";
+
+ public PlatformLoggingMXBeanTest() throws Exception {
+ }
+
+ private void runTest(PlatformLoggingMXBean mBean) throws Exception {
+
+ /*
+ * Create the MBeanServeri, register the PlatformLoggingMXBean
+ */
+ System.out.println( "***************************************************" );
+ System.out.println( "********** PlatformLoggingMXBean Unit Test **********" );
+ System.out.println( "***************************************************" );
+ System.out.println( "" );
+ System.out.println( "*******************************" );
+ System.out.println( "*********** Phase 1 ***********" );
+ System.out.println( "*******************************" );
+ System.out.println( " Creating MBeanServer " );
+ System.out.print( " Register PlatformLoggingMXBean: " );
+ MBeanServer mbs = MBeanServerFactory.createMBeanServer();
+ String[] list = new String[0];
+
+ try {
+ objectName = new ObjectName(LogManager.LOGGING_MXBEAN_NAME);
+ mbs.registerMBean( mBean, objectName );
+ }
+ catch ( Exception e ) {
+ System.out.println( "FAILED" );
+ throw e;
+ }
+ System.out.println( "PASSED" );
+ System.out.println("");
+
+ /*
+ * Access our MBean to get the current list of Loggers
+ */
+ System.out.println( "*******************************" );
+ System.out.println( "*********** Phase 2 ***********" );
+ System.out.println( "*******************************" );
+ System.out.println( " Test Logger Name retrieval (getLoggerNames) " );
+ // check that Level object are returned properly
+ try {
+ list = (String[]) mbs.getAttribute( objectName, "LoggerNames" );
+ }
+ catch ( Exception e ) {
+ System.out.println(" : FAILED" );
+ throw e;
+ }
+
+ /*
+ * Dump the list of Loggers already present, if any
+ */
+ Object[] params = new Object[1];
+ String[] signature = new String[1];
+ Level l;
+
+ if ( list == null ) {
+ System.out.println(" : PASSED. No Standard Loggers Present" );
+ System.out.println("");
+ }
+ else {
+ System.out.println(" : PASSED. There are " + list.length + " Loggers Present" );
+ System.out.println("");
+ System.out.println( "*******************************" );
+ System.out.println( "*********** Phase 2B **********" );
+ System.out.println( "*******************************" );
+ System.out.println( " Examine Existing Loggers" );
+ for ( int i = 0; i < list.length; i++ ) {
+ try {
+ params[0] = list[i];
+ signature[0] = "java.lang.String";
+ String levelName = (String) mbs.invoke( objectName, "getLoggerLevel", params, signature );
+ System.out.println(" : Logger #" + i + " = " + list[i] );
+ System.out.println(" : Level = " + levelName );
+ }
+ catch ( Exception e ) {
+ System.out.println(" : FAILED" );
+ throw e;
+ }
+ }
+ System.out.println(" : PASSED" );
+ }
+
+ /*
+ * Create two new loggers to the list of Loggers already present
+ */
+ System.out.println("");
+ System.out.println( "*******************************" );
+ System.out.println( "*********** Phase 3 ***********" );
+ System.out.println( "*******************************" );
+ System.out.println( " Create and test new Loggers" );
+ Logger logger1 = Logger.getLogger( LOGGER_NAME_1 );
+ Logger logger2 = Logger.getLogger( LOGGER_NAME_2 );
+
+ // check that Level object are returned properly
+ try {
+ list = (String[]) mbs.getAttribute( objectName, "LoggerNames" );
+ }
+ catch ( Exception e ) {
+ System.out.println(" : FAILED" );
+ throw e;
+ }
+
+ /*
+ * Check for the existence of our new Loggers
+ */
+ boolean log1 = false, log2 = false;
+
+ if ( list == null || list.length < 2 ) {
+ System.out.println(" : FAILED. Could not Detect the presense of the new Loggers" );
+ throw new RuntimeException(
+ "Could not Detect the presense of the new Loggers");
+ }
+ else {
+ for ( int i = 0; i < list.length; i++ ) {
+ if ( list[i].equals( LOGGER_NAME_1 ) ) {
+ log1 = true;
+ System.out.println( " : Found new Logger : " + list[i] );
+ }
+ if ( list[i].equals( LOGGER_NAME_2 ) ) {
+ log2 = true;
+ System.out.println( " : Found new Logger : " + list[i] );
+ }
+ }
+ if ( log1 && log2 )
+ System.out.println( " : PASSED." );
+ else {
+ System.out.println( " : FAILED. Could not Detect the new Loggers." );
+ throw new RuntimeException(
+ "Could not Detect the presense of the new Loggers");
+ }
+ }
+
+ /*
+ * Set a new Logging levels and check that it succeeded
+ */
+ System.out.println("");
+ System.out.println( "*******************************" );
+ System.out.println( "*********** Phase 4 ***********" );
+ System.out.println( "*******************************" );
+ System.out.println( " Set and Check the Logger Level" );
+ log1 = false;
+ log2 = false;
+ try {
+ // Set the level of logger1 to ALL
+ params = new Object[2];
+ signature = new String[2];
+ params[0] = LOGGER_NAME_1;
+ params[1] = Level.ALL.getName();
+ signature[0] = "java.lang.String";
+ signature[1] = "java.lang.String";
+ mbs.invoke( objectName, "setLoggerLevel", params, signature );
+
+ // Set the level of logger2 to FINER
+ params[0] = LOGGER_NAME_2;
+ params[1] = Level.FINER.getName();
+ mbs.invoke( objectName, "setLoggerLevel", params, signature );
+
+ // Okay read back the Level from Logger1. Should be ALL
+ params = new Object[1];
+ signature = new String[1];
+ params[0] = LOGGER_NAME_1;
+ signature[0] = "java.lang.String";
+ String levelName = (String) mbs.invoke( objectName, "getLoggerLevel", params, signature );
+ l = Level.parse(levelName);
+ System.out.print(" Logger1: " );
+ if ( l.equals( l.ALL ) ) {
+ System.out.println("Level Set to ALL: PASSED" );
+ log1 = true;
+ }
+ else {
+ System.out.println("Level Set to ALL: FAILED" );
+ throw new RuntimeException(
+ "Level Set to ALL but returned " + l.toString());
+ }
+
+ // Okay read back the Level from Logger2. Should be FINER
+ params = new Object[1];
+ signature = new String[1];
+ params[0] = LOGGER_NAME_2;
+ signature[0] = "java.lang.String";
+ levelName = (String) mbs.invoke( objectName, "getLoggerLevel", params, signature );
+ l = Level.parse(levelName);
+ System.out.print(" Logger2: " );
+ if ( l.equals( l.FINER ) ) {
+ System.out.println("Level Set to FINER: PASSED" );
+ log2 = true;
+ }
+ else {
+ System.out.println("Level Set to FINER: FAILED" );
+ throw new RuntimeException(
+ "Level Set to FINER but returned " + l.toString());
+ }
+ }
+ catch ( Exception e ) {
+ throw e;
+ }
+
+ System.out.println( "" );
+ System.out.println( "***************************************************" );
+ System.out.println( "***************** All Tests Passed ****************" );
+ System.out.println( "***************************************************" );
+ }
+
+ public static void main(String[] argv) throws Exception {
+ PlatformLoggingMXBean mbean =
+ ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class);
+ ObjectName objname = mbean.getObjectName();
+ if (!objname.equals(new ObjectName(LogManager.LOGGING_MXBEAN_NAME))) {
+ throw new RuntimeException("Invalid ObjectName " + objname);
+ }
+
+ // check if the PlatformLoggingMXBean is registered in the platform MBeanServer
+ MBeanServer platformMBS = ManagementFactory.getPlatformMBeanServer();
+ ObjectName objName = new ObjectName(LogManager.LOGGING_MXBEAN_NAME);
+
+ // We could call mbs.isRegistered(objName) here.
+ // Calling getMBeanInfo will throw exception if not found.
+ platformMBS.getMBeanInfo(objName);
+
+ if (!platformMBS.isInstanceOf(objName, "java.lang.management.PlatformLoggingMXBean") ||
+ !platformMBS.isInstanceOf(objName, "java.util.logging.LoggingMXBean")) {
+ throw new RuntimeException(objName + " is of unexpected type");
+ }
+
+ // test if PlatformLoggingMXBean works properly in a MBeanServer
+ PlatformLoggingMXBeanTest test = new PlatformLoggingMXBeanTest();
+ test.runTest(mbean);
+ }
+}
--- a/jdk/test/java/lang/reflect/Method/InheritedMethods.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/java/lang/reflect/Method/InheritedMethods.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,17 +23,14 @@
/* @test
@bug 4471738
- @ignore until 6825739 fixed
@summary Failure to properly traverse class hierarchy in Class.getMethod()
*/
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
-import javax.swing.JPanel;
-import javax.swing.JLabel;
-public class InheritedMethods extends JPanel {
+public class InheritedMethods {
public static void main(String[] args) throws Exception { new InheritedMethods(); }
InheritedMethods() throws Exception {
Class c = Foo.class;
@@ -41,7 +38,6 @@
if (m.getDeclaringClass() != java.util.List.class) {
throw new RuntimeException("TEST FAILED");
}
- add(new JLabel("Test"));
}
interface Foo extends List { }
}
--- a/jdk/test/java/nio/BufferPoolMXBean/Basic.java Thu Apr 07 15:21:10 2011 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,107 +0,0 @@
-/*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please 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 6606598
- * @summary Unit test for java.nio.BufferPoolMXBean
- * @run main/othervm Basic
- */
-
-import java.nio.ByteBuffer;
-import java.nio.MappedByteBuffer;
-import java.nio.BufferPoolMXBean;
-import java.nio.channels.FileChannel;
-import java.io.File;
-import java.io.RandomAccessFile;
-import java.lang.management.ManagementFactory;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import java.util.*;
-
-public class Basic {
-
- // static fields to ensure buffers aren't GC'ed
- static List<ByteBuffer> buffers;
- static MappedByteBuffer mbb;
-
- // check counters
- static void check(List<BufferPoolMXBean> pools,
- int minBufferCount,
- long minTotalCapacity)
- {
- int bufferCount = 0;
- long totalCap = 0;
- long totalMem = 0;
- for (BufferPoolMXBean pool: pools) {
- bufferCount += pool.getCount();
- totalCap += pool.getTotalCapacity();
- totalMem += pool.getMemoryUsed();
- }
- if (bufferCount < minBufferCount)
- throw new RuntimeException("Count less than expected");
- if (totalMem < minTotalCapacity)
- throw new RuntimeException("Memory usage less than expected");
- if (totalCap < minTotalCapacity)
- throw new RuntimeException("Total capacity less than expected");
- }
-
- public static void main(String[] args) throws Exception {
- Random rand = new Random();
-
- // allocate a few direct buffers
- int bufferCount = 5 + rand.nextInt(20);
- buffers = new ArrayList<ByteBuffer>(bufferCount);
- long totalCapacity = 0L;
- for (int i=0; i<bufferCount; i++) {
- int cap = 1024 + rand.nextInt(4096);
- buffers.add( ByteBuffer.allocateDirect(cap) );
- totalCapacity += cap;
- }
-
- // map a file
- File f = File.createTempFile("blah", null);
- f.deleteOnExit();
- RandomAccessFile raf = new RandomAccessFile(f, "rw");
- FileChannel fc = raf.getChannel();
- mbb = fc.map(FileChannel.MapMode.READ_WRITE, 10, 100);
- bufferCount++;
- totalCapacity += mbb.capacity();
-
- // direct
- List<BufferPoolMXBean> pools =
- ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
- check(pools, bufferCount, totalCapacity);
-
- // using MBeanServer
- MBeanServer server = ManagementFactory.getPlatformMBeanServer();
- Set<ObjectName> mbeans = server.queryNames(
- new ObjectName("java.nio:type=BufferPool,*"), null);
- pools = new ArrayList<BufferPoolMXBean>();
- for (ObjectName name: mbeans) {
- BufferPoolMXBean pool = ManagementFactory
- .newPlatformMXBeanProxy(server, name.toString(), BufferPoolMXBean.class);
- pools.add(pool);
- }
- check(pools, bufferCount, totalCapacity);
- }
-}
--- a/jdk/test/java/nio/channels/AsynchronousSocketChannel/Leaky.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/java/nio/channels/AsynchronousSocketChannel/Leaky.java Sun Apr 10 10:23:28 2011 -0700
@@ -28,12 +28,12 @@
*/
import java.nio.ByteBuffer;
-import java.nio.BufferPoolMXBean;
import java.nio.channels.*;
import java.net.*;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
+import java.lang.management.BufferPoolMXBean;
import java.lang.management.ManagementFactory;
/**
--- a/jdk/test/java/nio/file/Files/CheckPermissions.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/java/nio/file/Files/CheckPermissions.java Sun Apr 10 10:23:28 2011 -0700
@@ -521,19 +521,19 @@
// -- toRealPath --
prepare();
- file.toRealPath(true);
+ file.toRealPath();
assertCheckRead(file);
prepare();
- file.toRealPath(false);
+ file.toRealPath(LinkOption.NOFOLLOW_LINKS);
assertCheckRead(file);
prepare();
- Paths.get(".").toRealPath(true);
+ Paths.get(".").toRealPath();
assertCheckPropertyAccess("user.dir");
prepare();
- Paths.get(".").toRealPath(false);
+ Paths.get(".").toRealPath(LinkOption.NOFOLLOW_LINKS);
assertCheckPropertyAccess("user.dir");
// -- register --
--- a/jdk/test/java/nio/file/Files/PassThroughFileSystem.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/java/nio/file/Files/PassThroughFileSystem.java Sun Apr 10 10:23:28 2011 -0700
@@ -486,8 +486,8 @@
}
@Override
- public Path toRealPath(boolean resolveLinks) throws IOException {
- return wrap(delegate.toRealPath(resolveLinks));
+ public Path toRealPath(LinkOption... options) throws IOException {
+ return wrap(delegate.toRealPath(options));
}
@Override
--- a/jdk/test/java/nio/file/Path/Misc.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/java/nio/file/Path/Misc.java Sun Apr 10 10:23:28 2011 -0700
@@ -22,12 +22,13 @@
*/
/* @test
- * @bug 4313887 6838333
+ * @bug 4313887 6838333 7029979
* @summary Unit test for miscellenous java.nio.file.Path methods
* @library ..
*/
import java.nio.file.*;
+import static java.nio.file.LinkOption.*;
import java.io.*;
public class Misc {
@@ -96,65 +97,65 @@
final Path link = dir.resolve("link");
/**
- * Test: totRealPath(true) will access same file as toRealPath(false)
+ * Test: totRealPath() will access same file as toRealPath(NOFOLLOW_LINKS)
*/
- assertTrue(Files.isSameFile(file.toRealPath(true), file.toRealPath(false)));
+ assertTrue(Files.isSameFile(file.toRealPath(), file.toRealPath(NOFOLLOW_LINKS)));
/**
* Test: toRealPath should fail if file does not exist
*/
Path doesNotExist = dir.resolve("DoesNotExist");
try {
- doesNotExist.toRealPath(true);
+ doesNotExist.toRealPath();
throw new RuntimeException("IOException expected");
} catch (IOException expected) {
}
try {
- doesNotExist.toRealPath(false);
+ doesNotExist.toRealPath(NOFOLLOW_LINKS);
throw new RuntimeException("IOException expected");
} catch (IOException expected) {
}
/**
- * Test: toRealPath(true) should resolve links
+ * Test: toRealPath() should resolve links
*/
if (supportsLinks) {
Files.createSymbolicLink(link, file.toAbsolutePath());
- assertTrue(link.toRealPath(true).equals(file.toRealPath(true)));
+ assertTrue(link.toRealPath().equals(file.toRealPath()));
Files.delete(link);
}
/**
- * Test: toRealPath(false) should not resolve links
+ * Test: toRealPath(NOFOLLOW_LINKS) should not resolve links
*/
if (supportsLinks) {
Files.createSymbolicLink(link, file.toAbsolutePath());
- assertTrue(link.toRealPath(false).getFileName().equals(link.getFileName()));
+ assertTrue(link.toRealPath(NOFOLLOW_LINKS).getFileName().equals(link.getFileName()));
Files.delete(link);
}
/**
- * Test: toRealPath(false) with broken link
+ * Test: toRealPath(NOFOLLOW_LINKS) with broken link
*/
if (supportsLinks) {
Path broken = Files.createSymbolicLink(link, doesNotExist);
- assertTrue(link.toRealPath(false).getFileName().equals(link.getFileName()));
+ assertTrue(link.toRealPath(NOFOLLOW_LINKS).getFileName().equals(link.getFileName()));
Files.delete(link);
}
/**
* Test: toRealPath should eliminate "."
*/
- assertTrue(dir.resolve(".").toRealPath(true).equals(dir.toRealPath(true)));
- assertTrue(dir.resolve(".").toRealPath(false).equals(dir.toRealPath(false)));
+ assertTrue(dir.resolve(".").toRealPath().equals(dir.toRealPath()));
+ assertTrue(dir.resolve(".").toRealPath(NOFOLLOW_LINKS).equals(dir.toRealPath(NOFOLLOW_LINKS)));
/**
* Test: toRealPath should eliminate ".." when it doesn't follow a
* symbolic link
*/
Path subdir = Files.createDirectory(dir.resolve("subdir"));
- assertTrue(subdir.resolve("..").toRealPath(true).equals(dir.toRealPath(true)));
- assertTrue(subdir.resolve("..").toRealPath(false).equals(dir.toRealPath(false)));
+ assertTrue(subdir.resolve("..").toRealPath().equals(dir.toRealPath()));
+ assertTrue(subdir.resolve("..").toRealPath(NOFOLLOW_LINKS).equals(dir.toRealPath(NOFOLLOW_LINKS)));
Files.delete(subdir);
// clean-up
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/jar/JarFile/MevNPE.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please 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 7023056
+ * @summary NPE from sun.security.util.ManifestEntryVerifier.verify during Maven build
+ */
+import java.io.*;
+import java.util.jar.*;
+
+public class MevNPE {
+ public static void main(String[] args) throws Exception {
+ File f = new File(System.getProperty("test.src", "."), "Signed.jar");
+ try (JarFile jf = new JarFile(f, true)) {
+ try (InputStream s1 = jf.getInputStream(
+ jf.getJarEntry(JarFile.MANIFEST_NAME))) {
+ s1.read(new byte[10000]);
+ };
+ try (InputStream s2 = jf.getInputStream(
+ jf.getJarEntry(JarFile.MANIFEST_NAME))) {
+ s2.read(new byte[10000]);
+ };
+ }
+ }
+}
--- a/jdk/test/java/util/logging/PlatformLoggingMXBean/PlatformLoggingMXBeanTest.java Thu Apr 07 15:21:10 2011 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,279 +0,0 @@
-/*
- * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please 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 6876135
- *
- * @summary Test PlatformLoggingMXBean
- * This test performs similar testing as LoggingMXBeanTest.
- *
- * @build PlatformLoggingMXBeanTest
- * @run main PlatformLoggingMXBeanTest
- */
-
-import javax.management.*;
-import java.lang.management.ManagementFactory;
-import java.util.logging.*;
-import java.util.List;
-
-public class PlatformLoggingMXBeanTest
-{
-
- ObjectName objectName = null;
- static String LOGGER_NAME_1 = "com.sun.management.Logger1";
- static String LOGGER_NAME_2 = "com.sun.management.Logger2";
-
- public PlatformLoggingMXBeanTest() throws Exception {
- }
-
- private void runTest(PlatformLoggingMXBean mBean) throws Exception {
-
- /*
- * Create the MBeanServeri, register the PlatformLoggingMXBean
- */
- System.out.println( "***************************************************" );
- System.out.println( "********** PlatformLoggingMXBean Unit Test **********" );
- System.out.println( "***************************************************" );
- System.out.println( "" );
- System.out.println( "*******************************" );
- System.out.println( "*********** Phase 1 ***********" );
- System.out.println( "*******************************" );
- System.out.println( " Creating MBeanServer " );
- System.out.print( " Register PlatformLoggingMXBean: " );
- MBeanServer mbs = MBeanServerFactory.createMBeanServer();
- String[] list = new String[0];
-
- try {
- objectName = new ObjectName(LogManager.LOGGING_MXBEAN_NAME);
- mbs.registerMBean( mBean, objectName );
- }
- catch ( Exception e ) {
- System.out.println( "FAILED" );
- throw e;
- }
- System.out.println( "PASSED" );
- System.out.println("");
-
- /*
- * Access our MBean to get the current list of Loggers
- */
- System.out.println( "*******************************" );
- System.out.println( "*********** Phase 2 ***********" );
- System.out.println( "*******************************" );
- System.out.println( " Test Logger Name retrieval (getLoggerNames) " );
- // check that Level object are returned properly
- try {
- list = (String[]) mbs.getAttribute( objectName, "LoggerNames" );
- }
- catch ( Exception e ) {
- System.out.println(" : FAILED" );
- throw e;
- }
-
- /*
- * Dump the list of Loggers already present, if any
- */
- Object[] params = new Object[1];
- String[] signature = new String[1];
- Level l;
-
- if ( list == null ) {
- System.out.println(" : PASSED. No Standard Loggers Present" );
- System.out.println("");
- }
- else {
- System.out.println(" : PASSED. There are " + list.length + " Loggers Present" );
- System.out.println("");
- System.out.println( "*******************************" );
- System.out.println( "*********** Phase 2B **********" );
- System.out.println( "*******************************" );
- System.out.println( " Examine Existing Loggers" );
- for ( int i = 0; i < list.length; i++ ) {
- try {
- params[0] = list[i];
- signature[0] = "java.lang.String";
- String levelName = (String) mbs.invoke( objectName, "getLoggerLevel", params, signature );
- System.out.println(" : Logger #" + i + " = " + list[i] );
- System.out.println(" : Level = " + levelName );
- }
- catch ( Exception e ) {
- System.out.println(" : FAILED" );
- throw e;
- }
- }
- System.out.println(" : PASSED" );
- }
-
- /*
- * Create two new loggers to the list of Loggers already present
- */
- System.out.println("");
- System.out.println( "*******************************" );
- System.out.println( "*********** Phase 3 ***********" );
- System.out.println( "*******************************" );
- System.out.println( " Create and test new Loggers" );
- Logger logger1 = Logger.getLogger( LOGGER_NAME_1 );
- Logger logger2 = Logger.getLogger( LOGGER_NAME_2 );
-
- // check that Level object are returned properly
- try {
- list = (String[]) mbs.getAttribute( objectName, "LoggerNames" );
- }
- catch ( Exception e ) {
- System.out.println(" : FAILED" );
- throw e;
- }
-
- /*
- * Check for the existence of our new Loggers
- */
- boolean log1 = false, log2 = false;
-
- if ( list == null || list.length < 2 ) {
- System.out.println(" : FAILED. Could not Detect the presense of the new Loggers" );
- throw new RuntimeException(
- "Could not Detect the presense of the new Loggers");
- }
- else {
- for ( int i = 0; i < list.length; i++ ) {
- if ( list[i].equals( LOGGER_NAME_1 ) ) {
- log1 = true;
- System.out.println( " : Found new Logger : " + list[i] );
- }
- if ( list[i].equals( LOGGER_NAME_2 ) ) {
- log2 = true;
- System.out.println( " : Found new Logger : " + list[i] );
- }
- }
- if ( log1 && log2 )
- System.out.println( " : PASSED." );
- else {
- System.out.println( " : FAILED. Could not Detect the new Loggers." );
- throw new RuntimeException(
- "Could not Detect the presense of the new Loggers");
- }
- }
-
- /*
- * Set a new Logging levels and check that it succeeded
- */
- System.out.println("");
- System.out.println( "*******************************" );
- System.out.println( "*********** Phase 4 ***********" );
- System.out.println( "*******************************" );
- System.out.println( " Set and Check the Logger Level" );
- log1 = false;
- log2 = false;
- try {
- // Set the level of logger1 to ALL
- params = new Object[2];
- signature = new String[2];
- params[0] = LOGGER_NAME_1;
- params[1] = Level.ALL.getName();
- signature[0] = "java.lang.String";
- signature[1] = "java.lang.String";
- mbs.invoke( objectName, "setLoggerLevel", params, signature );
-
- // Set the level of logger2 to FINER
- params[0] = LOGGER_NAME_2;
- params[1] = Level.FINER.getName();
- mbs.invoke( objectName, "setLoggerLevel", params, signature );
-
- // Okay read back the Level from Logger1. Should be ALL
- params = new Object[1];
- signature = new String[1];
- params[0] = LOGGER_NAME_1;
- signature[0] = "java.lang.String";
- String levelName = (String) mbs.invoke( objectName, "getLoggerLevel", params, signature );
- l = Level.parse(levelName);
- System.out.print(" Logger1: " );
- if ( l.equals( l.ALL ) ) {
- System.out.println("Level Set to ALL: PASSED" );
- log1 = true;
- }
- else {
- System.out.println("Level Set to ALL: FAILED" );
- throw new RuntimeException(
- "Level Set to ALL but returned " + l.toString());
- }
-
- // Okay read back the Level from Logger2. Should be FINER
- params = new Object[1];
- signature = new String[1];
- params[0] = LOGGER_NAME_2;
- signature[0] = "java.lang.String";
- levelName = (String) mbs.invoke( objectName, "getLoggerLevel", params, signature );
- l = Level.parse(levelName);
- System.out.print(" Logger2: " );
- if ( l.equals( l.FINER ) ) {
- System.out.println("Level Set to FINER: PASSED" );
- log2 = true;
- }
- else {
- System.out.println("Level Set to FINER: FAILED" );
- throw new RuntimeException(
- "Level Set to FINER but returned " + l.toString());
- }
- }
- catch ( Exception e ) {
- throw e;
- }
-
- System.out.println( "" );
- System.out.println( "***************************************************" );
- System.out.println( "***************** All Tests Passed ****************" );
- System.out.println( "***************************************************" );
- }
-
- public static void main(String[] argv) throws Exception {
- List<PlatformLoggingMXBean> result =
- ManagementFactory.getPlatformMXBeans(PlatformLoggingMXBean.class);
- if (result.size() != 1) {
- throw new RuntimeException("Unexpected number of PlatformLoggingMXBean instances: " +
- result.size());
- }
-
- PlatformLoggingMXBean mbean = result.get(0);
- ObjectName objname = mbean.getObjectName();
- if (!objname.equals(new ObjectName(LogManager.LOGGING_MXBEAN_NAME))) {
- throw new RuntimeException("Invalid ObjectName " + objname);
- }
-
- // check if the PlatformLoggingMXBean is registered in the platform MBeanServer
- MBeanServer platformMBS = ManagementFactory.getPlatformMBeanServer();
- ObjectName objName = new ObjectName(LogManager.LOGGING_MXBEAN_NAME);
- // We could call mbs.isRegistered(objName) here.
- // Calling getMBeanInfo will throw exception if not found.
- platformMBS.getMBeanInfo(objName);
-
- if (!platformMBS.isInstanceOf(objName, "java.util.logging.PlatformLoggingMXBean") ||
- !platformMBS.isInstanceOf(objName, "java.util.logging.LoggingMXBean")) {
- throw new RuntimeException(objName + " is of unexpected type");
- }
-
- // test if PlatformLoggingMXBean works properly in a MBeanServer
- PlatformLoggingMXBeanTest test = new PlatformLoggingMXBeanTest();
- test.runTest(mbean);
- }
-}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/logging/SimpleFormatterFormat.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please 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 6381464
+ * @summary Test the custom simple formatter output
+ *
+ * @run main/othervm SimpleFormatterFormat
+ */
+
+import java.io.*;
+import java.util.logging.*;
+import java.util.regex.*;
+
+public class SimpleFormatterFormat {
+ private static final String key = "java.util.logging.SimpleFormatter.format";
+ private static final String origFormat = System.getProperty(key);
+ private static final PrintStream err = System.err;
+ public static void main(String[] args) throws Exception {
+ try {
+ File dir = new File(System.getProperty("user.dir", "."));
+ File log = new File(dir, "simpleformat.txt");
+ java.nio.file.Files.deleteIfExists(log.toPath());
+ PrintStream logps = new PrintStream(log);
+ System.setProperty(key, "%3$s:%4$s: %5$s [%1$tc] source: %2$s%6$s%n");
+ writeLogRecords(logps);
+ checkLogRecords(log);
+ } finally {
+ if (origFormat == null) {
+ System.clearProperty(key);
+ } else {
+ System.setProperty(key, origFormat);
+ }
+ System.setErr(err);
+ }
+ }
+
+ private static String[] loggers = new String[] {
+ "test.foo",
+ "test.foo",
+ "test.bar",
+ "test.bar"
+ };
+ private static String[] messages = new String[] {
+ "severe hello world",
+ "warning lost connection",
+ "info welcome",
+ "warning exception thrown",
+ };
+ private static void writeLogRecords(PrintStream logps) throws Exception {
+ try {
+ System.setErr(logps);
+
+ Logger foo = Logger.getLogger("test.foo");
+ foo.log(Level.SEVERE, "{0} {1} {2}", new Object[] {"severe", "hello", "world"});
+ foo.warning(messages[1]);
+
+ Logger bar = Logger.getLogger("test.bar");
+ bar.finest("Dummy message");
+ bar.info(messages[2]);
+ bar.log(Level.WARNING, messages[3], new IllegalArgumentException());
+
+ } finally {
+ logps.flush();
+ logps.close();
+ System.setErr(err);
+ }
+ }
+
+ private static void checkLogRecords(File log) throws Exception {
+ System.out.println("Checking log records in file: " + log);
+ Pattern p = Pattern.compile("([\\.a-zA-Z:]+) (.*) \\[.*\\] source: (.*)");
+
+ try (FileInputStream in = new FileInputStream(log)) {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+ String line;
+ int i = 0;
+ while (i < messages.length &&
+ (line = reader.readLine()) != null) {
+ String expectedLogger = loggers[i];
+ String expectedMsg = messages[i];
+ i++;
+
+ line = line.trim();
+ System.out.println(line);
+
+ Matcher m = p.matcher(line);
+ if (!m.matches()) {
+ throw new RuntimeException("Unexpected output format");
+ }
+ if (m.groupCount() != 3) {
+ throw new RuntimeException("Unexpected group count = " +
+ m.groupCount());
+ }
+ // verify logger name and level
+ String[] ss = m.group(1).split(":");
+ int len = ss.length;
+ if (len != 2) {
+ throw new RuntimeException("Unexpected logger name and level" +
+ m.group(1));
+ }
+
+ verify(expectedLogger, expectedMsg, ss[0], ss[1], m.group(2), m.group(3));
+ }
+
+ // expect IllegalArgumentException following it
+ line = reader.readLine().trim();
+ if (!line.equals("java.lang.IllegalArgumentException")) {
+ throw new RuntimeException("Invalid line: " + line);
+ }
+ }
+ }
+
+ private static void verify(String expectedLogger, String expectedMsg,
+ String logger, String level,
+ String msg, String source) {
+ if (!logger.equals(expectedLogger)) {
+ throw new RuntimeException("Unexpected logger: " + logger);
+ }
+ if (!msg.equals(expectedMsg)) {
+ throw new RuntimeException("Unexpected message: " + msg);
+ }
+
+ String[] ss = expectedMsg.split("\\s+");
+ String expectedLevel = ss[0].toUpperCase();
+ if (!level.equals(expectedLevel)) {
+ throw new RuntimeException("Unexpected level: " + level);
+ }
+
+ ss = source.split("\\s+");
+ int len = ss.length;
+ if (!(len == 2 &&
+ ss[0].equals("SimpleFormatterFormat") &&
+ ss[1].equals("writeLogRecords"))) {
+ throw new RuntimeException("Unexpected source: " + source);
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/zip/FlaterCriticalArray.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,295 @@
+/*
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * ZIP inflater/deflater performance.
+ */
+
+/*
+ * Run this test on JDK 6 and on later
+ * JDKs to compare results:
+ * java -server -Xms1024M -Xmx1024M -Ddebug=true FlaterCriticalArray
+ *
+ * The performance issues can be readily seen on JDK 6, and so this code is
+ * written to compile on that platform: it does *not* use any JDK 7 - specific
+ * features.
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.util.*;
+import java.util.zip.*;
+
+public class FlaterCriticalArray {
+ // If true, print information about performance
+ private static final boolean debug = System.getProperty("debug") != null;
+
+ private static void debug(String s) {
+ if (debug) System.out.println(s);
+ }
+
+ private static void debug(String name, String inOut, long time, int length) {
+ debug(name + ": Duration of " + inOut + "(in ms): " + time);
+ debug(name + ": " + inOut + "d data length: " + length + " bytes");
+ }
+
+ private static byte[] grow(byte[] a, int capacity) {
+ while (a.length < capacity) {
+ byte[] a2 = new byte[a.length * 2];
+ System.arraycopy(a, 0, a2, 0, a.length);
+ a = a2;
+ }
+ return a;
+ }
+
+ private static byte[] trim(byte[] a, int length) {
+ byte[] res = new byte[length];
+ System.arraycopy(a, 0, res, 0, length);
+ return res;
+ }
+
+ /*
+ * Base class for individual test cases
+ */
+ abstract static private class TestCase {
+ protected String name; // For information in debug messages
+ protected byte data[]; // Data to be deflated and subsequently inflated
+ protected int level; // Compression level for deflater
+
+ protected TestCase(String name, byte data[]) {
+ this(name, data, -1);
+ }
+
+ protected TestCase(String name, byte data[], int level) {
+ this.name = name;
+ this.data = data;
+ this.level = level;
+ }
+
+ public void runTest() throws Throwable {
+ long time0, time1;
+ byte deflated[], inflated[];
+
+ debug("");
+
+ time0 = System.currentTimeMillis();
+ deflated = deflate(data, level);
+ time1 = System.currentTimeMillis();
+ inform("Deflate", time1 - time0, deflated.length);
+
+ time0 = System.currentTimeMillis();
+ inflated = inflate(deflated);
+ time1 = System.currentTimeMillis();
+ inform("Inflate", time1 - time0, inflated.length);
+
+ check(Arrays.equals(data, inflated),
+ name + ": Inflated and deflated arrays do not match");
+ }
+
+ private void inform(String inOut, long duration, int length) {
+ debug(name, inOut, duration, length);
+ }
+
+ abstract protected byte[] deflate(byte data[], int level) throws Throwable;
+
+ abstract protected byte[] inflate(byte deflated[]) throws Throwable;
+ }
+
+ /*
+ * Following are the individual test cases
+ */
+
+ private static class StrideTest extends TestCase {
+ static final int STRIDE = 1024;
+
+ public StrideTest(byte data[], int level) {
+ super("STRIDE", data, level);
+ }
+
+ protected byte[] deflate(byte in[], int level) throws Throwable {
+ final int len = in.length;
+ final Deflater deflater = new Deflater(level);
+ final byte[] smallBuffer = new byte[32];
+ byte[] flated = new byte[32];
+ int count = 0;
+ for (int i = 0; i<len; i+= STRIDE) {
+ deflater.setInput(in, i, Math.min(STRIDE, len-i));
+ while (!deflater.needsInput()) {
+ int n = deflater.deflate(smallBuffer);
+ flated = grow(flated, count + n);
+ System.arraycopy(smallBuffer, 0, flated, count, n);
+ count += n;
+ }
+ }
+ deflater.finish();
+ int n;
+ do {
+ n = deflater.deflate(smallBuffer);
+ flated = grow(flated, count + n);
+ System.arraycopy(smallBuffer, 0, flated, count, n);
+ count += n;
+ } while (n > 0);
+ return trim(flated, count);
+ }
+
+ protected byte[] inflate(byte in[]) throws Throwable {
+ final int len = in.length;
+ final Inflater inflater = new Inflater();
+ final byte[] smallBuffer = new byte[3200];
+
+ byte[] flated = new byte[32];
+ int count = 0;
+
+ for (int i = 0; i<len; i+= STRIDE) {
+ inflater.setInput(in, i, Math.min(STRIDE, len-i));
+ while (!inflater.needsInput()) {
+ int n;
+ while ((n = inflater.inflate(smallBuffer)) > 0) {
+ flated = grow(flated, count + n);
+ System.arraycopy(smallBuffer, 0, flated, count, n);
+ count += n;
+ }
+ }
+ }
+ return trim(flated, count);
+ }
+ }
+
+ private static class NoStrideTest extends TestCase {
+ public NoStrideTest(byte data[], int level) {
+ super("NO STRIDE", data, level);
+ }
+
+ public byte[] deflate(byte in[], int level) throws Throwable {
+ final Deflater flater = new Deflater(level);
+ flater.setInput(in);
+ flater.finish();
+ final byte[] smallBuffer = new byte[32];
+ byte[] flated = new byte[32];
+ int count = 0;
+ int n;
+ while ((n = flater.deflate(smallBuffer)) > 0) {
+ flated = grow(flated, count + n);
+ System.arraycopy(smallBuffer, 0, flated, count, n);
+ count += n;
+ }
+ return trim(flated, count);
+ }
+
+ public byte[] inflate(byte in[]) throws Throwable {
+ final Inflater flater = new Inflater();
+ flater.setInput(in);
+ final byte[] smallBuffer = new byte[32];
+ byte[] flated = new byte[32];
+ int count = 0;
+ int n;
+ while ((n = flater.inflate(smallBuffer)) > 0) {
+ flated = grow(flated, count + n);
+ System.arraycopy(smallBuffer, 0, flated, count, n);
+ count += n;
+ }
+ return trim(flated, count);
+ }
+ }
+
+ /**
+ * Check Deflater{In,Out}putStream by way of GZIP{In,Out}putStream
+ */
+ private static class GZIPTest extends TestCase {
+ public GZIPTest(byte data[]) {
+ super("GZIP", data);
+ }
+
+ public byte[] deflate(byte data[], int ignored) throws Throwable {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ OutputStream gzos = new GZIPOutputStream(baos);
+ gzos.write(data, 0, data.length);
+ gzos.close();
+ return baos.toByteArray();
+ }
+
+ public byte[] inflate(byte deflated[]) throws Throwable {
+ InputStream bais = new ByteArrayInputStream(deflated);
+ GZIPInputStream gzis = new GZIPInputStream(bais);
+ byte[] inflated = new byte[data.length];
+ int numRead = 0;
+ int count = 0;
+ while ((numRead = gzis.read(inflated, count, data.length - count)) > 0) {
+ count += numRead;
+ }
+ check(count == data.length, name + ": Read " + count + "; expected " + data.length);
+ return inflated;
+ }
+ }
+
+ public static void realMain(String[] args) throws Throwable {
+ byte data[];
+ int level = -1;
+ if (args.length > 0) {
+ level = Integer.parseInt(args[0]);
+ }
+ debug("Using level " + level);
+
+ if (args.length > 1) {
+ FileInputStream fis = new FileInputStream(args[1]);
+ int len = fis.available();
+ data = new byte[len];
+ check(fis.read(data, 0, len) == len, "Did not read complete file");
+ debug("Original data from " + args[1]);
+ fis.close();
+ } else {
+ ByteBuffer bb = ByteBuffer.allocate(8);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ for (int i = 0; i < 1024 * 64; i++) { // data length
+ bb.putDouble(0, Math.random());
+ baos.write(bb.array(), 0, 8);
+ }
+ data = baos.toByteArray();
+ debug("Original data from random byte array");
+ }
+ debug("Original data length: " + data.length + " bytes");
+
+ new StrideTest(data, level).runTest();
+ new NoStrideTest(data, level).runTest();
+ new GZIPTest(data).runTest();
+ }
+
+ //--------------------- Infrastructure ---------------------------
+ static volatile int passed = 0, failed = 0;
+ static void pass() {passed++;}
+ static void pass(String msg) {System.out.println(msg); passed++;}
+ static void fail() {failed++; Thread.dumpStack();}
+ static void fail(String msg) {System.out.println(msg); fail();}
+ static void unexpected(Throwable t) {failed++; t.printStackTrace();}
+ static void unexpected(Throwable t, String msg) {
+ System.out.println(msg); failed++; t.printStackTrace();}
+ static boolean check(boolean cond) {if (cond) pass(); else fail(); return cond;}
+ static boolean check(boolean cond, String msg) {if (cond) pass(); else fail(msg); return cond;}
+ static void equal(Object x, Object y) {
+ if (x == null ? y == null : x.equals(y)) pass();
+ else fail(x + " not equal to " + y);}
+ public static void main(String[] args) throws Throwable {
+ try {realMain(args);} catch (Throwable t) {unexpected(t);}
+ System.out.println("\nPassed = " + passed + " failed = " + failed);
+ if (failed > 0) throw new AssertionError("Some tests failed");}
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/zip/InflaterBufferSize.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,163 @@
+/*
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please 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 6571338
+ * @summary Inflater should not require a buffer to the inflate() methods
+ * larger than 1 byte.
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.util.*;
+import java.util.zip.*;
+
+public class InflaterBufferSize {
+ private static final int DATA_LEN = 1024 *64;
+ private static byte[] data;
+
+ // If true, print extra info.
+ private static final boolean debug = System.getProperty("debug") != null;
+
+ private static void debug(String s) {
+ if (debug) System.out.println(s);
+ }
+
+ private static void createData() {
+ ByteBuffer bb = ByteBuffer.allocate(8);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ for (int i = 0; i < DATA_LEN; i++) {
+ bb.putDouble(0, Math.random());
+ baos.write(bb.array(), 0, 8);
+ }
+ data = baos.toByteArray();
+ }
+
+ private static byte[] grow(byte[] a, int capacity) {
+ while (a.length < capacity) {
+ byte[] a2 = new byte[a.length * 2];
+ System.arraycopy(a, 0, a2, 0, a.length);
+ a = a2;
+ }
+ return a;
+ }
+
+ private static byte[] trim(byte[] a, int length) {
+ byte[] res = new byte[length];
+ System.arraycopy(a, 0, res, 0, length);
+ return res;
+ }
+
+ private static byte[] deflate(byte[] in, int level) throws Throwable {
+ final Deflater flater = new Deflater(level);
+ flater.setInput(in);
+ flater.finish();
+ final byte[] smallBuffer = new byte[32];
+ byte[] flated = new byte[32];
+ int count = 0;
+ int n;
+ while ((n = flater.deflate(smallBuffer)) > 0) {
+ flated = grow(flated, count + n);
+ System.arraycopy(smallBuffer, 0, flated, count, n);
+ count += n;
+ }
+ return trim(flated, count);
+ }
+
+ private static byte[] inflate(byte[] in) throws Throwable {
+ final Inflater flater = new Inflater();
+ flater.setInput(in);
+ // This is the buffer of interest. It should be possible to use any
+ // non-zero size.
+ final byte[] smallBuffer = new byte[1];
+ byte[] flated = new byte[32];
+ int count = 0;
+ int n;
+ while ((n = flater.inflate(smallBuffer)) > 0) {
+ flated = grow(flated, count + n);
+ System.arraycopy(smallBuffer, 0, flated, count, n);
+ count += n;
+ }
+ return trim(flated, count);
+ }
+
+ public static void realMain(String[] args) throws Throwable {
+ byte deflated[], inflated[];
+
+ int level = -1;
+ if (args.length > 0) {
+ level = Integer.parseInt(args[0]);
+ }
+ debug("Using level " + level);
+
+ if (args.length > 1) {
+ FileInputStream fis = new FileInputStream(args[1]);
+ int len = fis.available();
+ data = new byte[len];
+ check(fis.read(data, 0, len) == len, "Did not read complete file");
+ debug("Original data from " + args[1]);
+ fis.close();
+ } else {
+ createData();
+ debug("Original data from random byte array");
+ }
+ debug("Original data length: " + data.length + " bytes");
+
+ debug("");
+ deflated = deflate(data, level);
+ debug("Deflated data length: " + deflated.length + " bytes");
+
+ inflated = inflate(deflated);
+ debug("Inflated data length: "+ inflated.length + " bytes" );
+
+ if (!check(Arrays.equals(data, inflated),
+ "Inflated and deflated arrays do not match")) {
+ OutputStream os = new BufferedOutputStream(new FileOutputStream("deflated.zip"));
+ try {
+ os.write(deflated);
+ } finally {
+ os.close();
+ }
+ }
+ }
+
+ //--------------------- Infrastructure ---------------------------
+ static volatile int passed = 0, failed = 0;
+ static void pass() {passed++;}
+ static void pass(String msg) {System.out.println(msg); passed++;}
+ static void fail() {failed++; Thread.dumpStack();}
+ static void fail(String msg) {System.out.println(msg); fail();}
+ static void unexpected(Throwable t) {failed++; t.printStackTrace();}
+ static void unexpected(Throwable t, String msg) {
+ System.out.println(msg); failed++; t.printStackTrace();}
+ static boolean check(boolean cond) {if (cond) pass(); else fail(); return cond;}
+ static boolean check(boolean cond, String msg) {if (cond) pass(); else fail(msg); return cond;}
+ static void equal(Object x, Object y) {
+ if (x == null ? y == null : x.equals(y)) pass();
+ else fail(x + " not equal to " + y);}
+ public static void main(String[] args) throws Throwable {
+ try {realMain(args);} catch (Throwable t) {unexpected(t);}
+ System.out.println("\nPassed = " + passed + " failed = " + failed);
+ if (failed > 0) throw new AssertionError("Some tests failed");}
+}
--- a/jdk/test/javax/sound/sampled/Clip/ClipSetPos.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/javax/sound/sampled/Clip/ClipSetPos.java Sun Apr 10 10:23:28 2011 -0700
@@ -33,6 +33,7 @@
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
+import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
public class ClipSetPos {
@@ -48,12 +49,16 @@
boolean testPassed = true;
Clip clip = null;
try {
- clip = AudioSystem.getClip();
+ clip = (Clip)AudioSystem.getLine(new DataLine.Info(Clip.class, audioFormat));
clip.open(audioFormat, dataBuffer, 0, dataBuffer.length);
} catch (LineUnavailableException ex) {
log(ex);
log("Cannot test (this is not failure)");
return;
+ } catch (IllegalArgumentException ex) {
+ log(ex);
+ log("Cannot test (this is not failure)");
+ return;
}
log("clip: " + clip.getClass().getName());
--- a/jdk/test/javax/swing/border/Test4856008.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/javax/swing/border/Test4856008.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
/*
* @test
- * @bug 4856008
+ * @bug 4856008 7025987
* @summary Tests border insets
* @author Sergey Malenkov
*/
@@ -59,6 +59,7 @@
import javax.swing.plaf.basic.BasicToolBarUI;
import javax.swing.plaf.metal.MetalBorders;
import javax.swing.plaf.metal.MetalComboBoxEditor;
+import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import sun.swing.plaf.synth.SynthFileChooserUI;
@@ -134,6 +135,9 @@
//+ SynthFileChooserUI.UIBorder:
new SynthFileChooser().getUIBorder(),
+
+ //+ LoweredBorder:
+ new NimbusLookAndFeel().getDefaults().getBorder("TitledBorder.border"),
};
public static void main(String[] args) {
--- a/jdk/test/javax/swing/border/Test6978482.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/javax/swing/border/Test6978482.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
/*
* @test
- * @bug 6978482
+ * @bug 6978482 7025987
* @summary Tests unchecked casts
* @author Sergey Malenkov
*/
@@ -58,6 +58,7 @@
import javax.swing.plaf.basic.BasicToolBarUI;
import javax.swing.plaf.metal.MetalBorders;
import javax.swing.plaf.metal.MetalComboBoxEditor;
+import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import sun.swing.plaf.synth.SynthFileChooserUI;
@@ -132,6 +133,9 @@
//+ SynthFileChooserUI.UIBorder:
new SynthFileChooser().getUIBorder(),
+
+ //+ LoweredBorder:
+ new NimbusLookAndFeel().getDefaults().getBorder("TitledBorder.border"),
};
public static void main(String[] args) {
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/java2d/SunGraphicsEnvironment/TestSGEuseAlternateFontforJALocales.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please 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 7032930
+ *
+ * @summary verify the existence of the method
+ * SunGraphicsEnvironment.useAlternateFontforJALocales
+ *
+ * @run main/othervm TestSGEuseAlternateFontforJALocales
+ * @run main/othervm -Dfile.encoding=windows-31j -Duser.language=ja -Duser.country=JA TestSGEuseAlternateFontforJALocales
+ *
+ */
+
+import java.lang.reflect.Method;
+import java.nio.charset.Charset;
+import java.util.Locale;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Graphics2D;
+import java.awt.GraphicsEnvironment;
+import java.awt.image.BufferedImage;
+
+public class TestSGEuseAlternateFontforJALocales {
+
+ public static void main(String args[]) throws Exception {
+ System.out.println("Default Charset = "
+ + Charset.defaultCharset().name());
+ System.out.println("Locale = " + Locale.getDefault());
+ String os = System.getProperty("os.name");
+ String encoding = System.getProperty("file.encoding");
+ /* Want to test the JA locale uses alternate font for DialogInput. */
+ boolean jaTest = encoding.equalsIgnoreCase("windows-31j");
+ if (!os.startsWith("Win") && jaTest) {
+ System.out.println("Skipping Windows only test");
+ return;
+ }
+
+ String className = "sun.java2d.SunGraphicsEnvironment";
+ String methodName = "useAlternateFontforJALocales";
+ Class sge = Class.forName(className);
+ Method uafMethod = sge.getMethod(methodName, (Class[])null);
+ Object ret = uafMethod.invoke(null);
+ GraphicsEnvironment ge =
+ GraphicsEnvironment.getLocalGraphicsEnvironment();
+ ge.preferLocaleFonts();
+ ge.preferProportionalFonts();
+ if (jaTest) {
+ Font msMincho = new Font("MS Mincho", Font.PLAIN, 12);
+ if (!msMincho.getFamily(Locale.ENGLISH).equals("MS Mincho")) {
+ System.out.println("MS Mincho not installed. Skipping test");
+ return;
+ }
+ Font dialogInput = new Font("DialogInput", Font.PLAIN, 12);
+ Font courierNew = new Font("Courier New", Font.PLAIN, 12);
+ Font msGothic = new Font("MS Gothic", Font.PLAIN, 12);
+ BufferedImage bi = new BufferedImage(1,1,1);
+ Graphics2D g2d = bi.createGraphics();
+ FontMetrics cnMetrics = g2d.getFontMetrics(courierNew);
+ FontMetrics diMetrics = g2d.getFontMetrics(dialogInput);
+ FontMetrics mmMetrics = g2d.getFontMetrics(msMincho);
+ FontMetrics mgMetrics = g2d.getFontMetrics(msGothic);
+ // This tests to make sure we at least have applied
+ // "preferLocaleFonts for Japanese
+ if (cnMetrics.charWidth('A') == diMetrics.charWidth('A')) {
+ throw new RuntimeException
+ ("Courier New should not be used for DialogInput");
+ }
+ // This is supposed to make sure we are using MS Mincho instead
+ // of MS Gothic. However they are metrics identical so its
+ // not definite proof.
+ if (diMetrics.charWidth('A') != mmMetrics.charWidth('A')) {
+ throw new RuntimeException
+ ("MS Mincho should be used for DialogInput");
+ }
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/java2d/XRenderBlitsTest.java Sun Apr 10 10:23:28 2011 -0700
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please 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 6985593
+* @summary Test verifies that rendering standard images to screen does
+* not caiuse a crash in case of XRender.
+* @run main/othervm -Dsun.java2d.xrender=True XRenderBlitsTest
+*/
+
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.Frame;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+import java.util.ArrayList;
+import java.util.concurrent.CountDownLatch;
+
+public class XRenderBlitsTest {
+
+ private static final int w = 10;
+ private static final int h = 10;
+
+ public static void main(String[] args) {
+ final CountDownLatch done = new CountDownLatch(1);
+
+ final ArrayList<BufferedImage> images = new ArrayList<BufferedImage>();
+
+ int type = BufferedImage.TYPE_INT_RGB;
+ do {
+ BufferedImage img = new BufferedImage(w, h, type++);
+ Graphics2D g2d = img.createGraphics();
+ g2d.setColor(Color.pink);
+ g2d.fillRect(0, 0, w, h);
+ g2d.dispose();
+
+ images.add(img);
+ } while (type <= BufferedImage.TYPE_BYTE_INDEXED);
+
+ Frame f = new Frame("Draw images");
+ Component c = new Component() {
+
+ @Override
+ public Dimension getPreferredSize() {
+ return new Dimension(w * images.size(), h);
+ }
+
+ @Override
+ public void paint(Graphics g) {
+ int x = 0;
+ for (BufferedImage img : images) {
+ System.out.println("Draw image " + img.getType());
+ g.drawImage(img, x, 0, this);
+ x += w;
+ }
+ done.countDown();
+ }
+ };
+ f.add("Center", c);
+ f.pack();
+ f.setVisible(true);
+
+ // now wait for test results
+ try {
+ done.await();
+ } catch (InterruptedException e) {
+ }
+ System.out.println("Test passed");
+ f.dispose();
+ }
+}
--- a/jdk/test/sun/misc/Version/Version.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/misc/Version/Version.java Sun Apr 10 10:23:28 2011 -0700
@@ -142,15 +142,21 @@
// non-product VM will have -debug|-release appended
cs = cs.subSequence(1, cs.length());
String[] res = cs.toString().split("-");
- for (String s : res) {
+ for (int i = res.length - 1; i >= 0; i--) {
+ String s = res[i];
if (s.charAt(0) == 'b') {
- build =
- Integer.valueOf(s.substring(1, s.length())).intValue();
- break;
+ try {
+ build = Integer.parseInt(s.substring(1, s.length()));
+ break;
+ } catch (NumberFormatException nfe) {
+ // ignore
+ }
}
}
}
}
- return new VersionInfo(major, minor, micro, update, special, build);
+ VersionInfo vi = new VersionInfo(major, minor, micro, update, special, build);
+ System.out.printf("newVersionInfo: input=%s output=%s\n", version, vi);
+ return vi;
}
}
--- a/jdk/test/sun/security/ec/TestEC.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/ec/TestEC.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,6 @@
* @test
* @bug 6840752
* @summary Provide out-of-the-box support for ECC algorithms
- * @ignore JSSE supported cipher suites are changed with CR 6916074,
- * need to update this test case in JDK 7 soon
* @library ../pkcs11
* @library ../pkcs11/ec
* @library ../pkcs11/sslecc
--- a/jdk/test/sun/security/jgss/GssNPE.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/jgss/GssNPE.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -24,6 +24,7 @@
/*
* @test
* @bug 6345338
+ * @run main/othervm GssNPE
* @summary GSS throws NPE when the JAAS config file does not exist
*/
--- a/jdk/test/sun/security/jgss/spnego/NoSpnegoAsDefMech.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/jgss/spnego/NoSpnegoAsDefMech.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -24,6 +24,7 @@
/*
* @test
* @bug 6770883
+ * @run main/othervm NoSpnegoAsDefMech
* @summary Infinite loop if SPNEGO specified as sun.security.jgss.mechanism
*/
--- a/jdk/test/sun/security/krb5/ConfPlusProp.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/krb5/ConfPlusProp.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
* @bug 6857795
* @bug 6858589
* @bug 6972005
+ * @run main/othervm ConfPlusProp
* @summary krb5.conf ignored if system properties on realm and kdc are provided
*/
--- a/jdk/test/sun/security/krb5/ConfigWithQuotations.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/krb5/ConfigWithQuotations.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,6 +23,7 @@
/*
* @test
* @bug 6714845
+ * @run main/othervm ConfigWithQuotations
* @summary Quotes in Kerberos configuration file are included in the values
*/
--- a/jdk/test/sun/security/krb5/DnsFallback.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/krb5/DnsFallback.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -24,6 +24,7 @@
* @test
* @bug 6673164
* @bug 6552334
+ * @run main/othervm DnsFallback
* @summary fix dns_fallback parse error, and use dns by default
*/
--- a/jdk/test/sun/security/krb5/IPv6.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/krb5/IPv6.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -24,6 +24,7 @@
/*
* @test
* @bug 6877357 6885166
+ * @run main/othervm IPv6
* @summary IPv6 address does not work
*/
--- a/jdk/test/sun/security/krb5/ParseCAPaths.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/krb5/ParseCAPaths.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,6 +23,7 @@
/*
* @test
* @bug 6789935
+ * @run main/othervm ParseCAPaths
* @summary cross-realm capath search error
*/
@@ -30,9 +31,10 @@
import sun.security.krb5.Realm;
public class ParseCAPaths {
- static boolean failed = false;
+ static Exception failed = null;
public static void main(String[] args) throws Exception {
- System.setProperty("java.security.krb5.conf", System.getProperty("test.src", ".") +"/krb5-capaths.conf");
+ System.setProperty("java.security.krb5.conf",
+ System.getProperty("test.src", ".") +"/krb5-capaths.conf");
//System.setProperty("sun.security.krb5.debug", "true");
// Standard example
@@ -59,9 +61,13 @@
check("G1.COM", "G3.COM", "G1.COM", "COM");
check("H1.COM", "H3.COM", "H1.COM");
check("I1.COM", "I4.COM", "I1.COM", "I5.COM");
-
- if (failed) {
- throw new Exception("Failed somewhere.");
+ // J2=J1 is the same as J2=.
+ check("J1.COM", "J2.COM", "J1.COM");
+ // 7019384
+ check("A9.PRAGUE.XXX.CZ", "SERVIS.XXX.CZ",
+ "A9.PRAGUE.XXX.CZ", "PRAGUE.XXX.CZ", "ROOT.XXX.CZ");
+ if (failed != null) {
+ throw failed;
}
}
@@ -69,10 +75,10 @@
try {
check2(from, to, paths);
} catch (Exception e) {
- failed = true;
- e.printStackTrace();
+ failed = e;
}
}
+
static void check2(String from, String to, String... paths)
throws Exception {
System.out.println(from + " -> " + to);
--- a/jdk/test/sun/security/krb5/ParseConfig.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/krb5/ParseConfig.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,6 +23,7 @@
/*
* @test
* @bug 6319046
+ * @run main/othervm ParseConfig
* @summary Problem with parsing krb5.conf
*/
--- a/jdk/test/sun/security/krb5/RFC396xTest.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/krb5/RFC396xTest.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,6 +23,7 @@
/*
* @test
* @bug 6862679
+ * @run main/othervm RFC396xTest
* @summary ESC: AD Authentication with user with umlauts fails
*/
--- a/jdk/test/sun/security/krb5/TimeInCCache.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/krb5/TimeInCCache.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,6 +23,7 @@
/*
* @test
* @bug 6590930
+ * @run main/othervm TimeInCCache
* @summary read/write does not match for ccache
*/
--- a/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java Sun Apr 10 10:23:28 2011 -0700
@@ -74,11 +74,10 @@
final static char[] WEB_PASS = "webby".toCharArray();
final static String PROXY_USER = "pro";
final static char[] PROXY_PASS = "proxy".toCharArray();
- final static int WEB_PORT = 17840;
+
final static String WEB_HOST = "host.web.domain";
final static String PROXY_HOST = "host.proxy.domain";
- final static int PROXY_PORT = 17841;
// web page content
final static String CONTENT = "Hello, World!";
@@ -86,18 +85,11 @@
// For 6829283, count how many times the Authenticator is called.
static int count = 0;
+ static int webPort, proxyPort;
+
// URLs for web test, proxy test. The proxy server is not a real proxy
// since it fakes the same content for any URL. :)
- final static URL webUrl, proxyUrl;
- static {
- URL u1 = null, u2 = null;
- try {
- u1 = new URL("http://" + WEB_HOST +":" + WEB_PORT + "/a/b/c");
- u2 = new URL("http://nosuchplace/a/b/c");
- } catch (Exception e) {
- }
- webUrl = u1; proxyUrl = u2;
- }
+ static URL webUrl, proxyUrl;
/**
* This Authenticator checks everything:
@@ -127,7 +119,7 @@
if (!this.getRequestingHost().equalsIgnoreCase(PROXY_HOST)) {
throw new RuntimeException("Bad host");
}
- if (this.getRequestingPort() != PROXY_PORT) {
+ if (this.getRequestingPort() != proxyPort) {
throw new RuntimeException("Bad port");
}
if (!this.getRequestingURL().equals(proxyUrl)) {
@@ -188,10 +180,15 @@
fos.close();
f.deleteOnExit();
- HttpServer h1 = httpd(WEB_PORT, "Negotiate", false,
+ HttpServer h1 = httpd("Negotiate", false,
"HTTP/" + WEB_HOST + "@" + REALM_WEB, KRB5_TAB);
- HttpServer h2 = httpd(PROXY_PORT, "Negotiate", true,
+ webPort = h1.getAddress().getPort();
+ HttpServer h2 = httpd("Negotiate", true,
"HTTP/" + PROXY_HOST + "@" + REALM_PROXY, KRB5_TAB);
+ proxyPort = h2.getAddress().getPort();
+
+ webUrl = new URL("http://" + WEB_HOST +":" + webPort + "/a/b/c");
+ proxyUrl = new URL("http://nosuchplace/a/b/c");
try {
Exception e1 = null, e2 = null;
@@ -230,7 +227,7 @@
reader = new BufferedReader(new InputStreamReader(
proxyUrl.openConnection(
new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress(PROXY_HOST, PROXY_PORT)))
+ new InetSocketAddress(PROXY_HOST, proxyPort)))
.getInputStream()));
if (!reader.readLine().equals(CONTENT)) {
throw new RuntimeException("Bad content");
@@ -258,10 +255,10 @@
* @param principal the krb5 service principal the server runs with
* @return the server
*/
- public static HttpServer httpd(int port, String scheme, boolean proxy,
+ public static HttpServer httpd(String scheme, boolean proxy,
String principal, String ktab) throws Exception {
MyHttpHandler h = new MyHttpHandler();
- HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
+ HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
HttpContext hc = server.createContext("/", h);
hc.setAuthenticator(new MyServerAuthenticator(
proxy, scheme, principal, ktab));
--- a/jdk/test/sun/security/krb5/etype/ETypeOrder.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/krb5/etype/ETypeOrder.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,6 +23,7 @@
/*
* @test
* @bug 6844907
+ * @run main/othervm ETypeOrder
* @summary krb5 etype order should be from strong to weak
*/
--- a/jdk/test/sun/security/krb5/krb5-capaths.conf Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/krb5/krb5-capaths.conf Sun Apr 10 10:23:28 2011 -0700
@@ -85,3 +85,13 @@
I3.COM = I2.COM
I4.COM = I2.COM I5.COM
}
+
+J1.COM = {
+ J2.COM=J1.COM
+}
+
+A9.PRAGUE.XXX.CZ = {
+ PRAGUE.XXX.CZ = .
+ ROOT.XXX.CZ = PRAGUE.XXX.CZ
+ SERVIS.XXX.CZ = ROOT.XXX.CZ
+}
--- a/jdk/test/sun/security/krb5/ktab/HighestKvno.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/krb5/ktab/HighestKvno.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -24,6 +24,7 @@
* @test
* @bug 6867665
* @bug 6875033
+ * @run main/othervm HighestKvno
* @summary Problem with keytabs with multiple kvno's (key versions)
*/
--- a/jdk/test/sun/security/pkcs11/fips/CipherTest.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/pkcs11/fips/CipherTest.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -114,19 +114,7 @@
}
boolean isEnabled() {
- // ignore SCSV
- if (cipherSuite.equals("TLS_EMPTY_RENEGOTIATION_INFO_SCSV")) {
- return false;
- }
-
- // ignore exportable cipher suite for TLSv1.1
- if (protocol.equals("TLSv1.1")) {
- if(cipherSuite.indexOf("_EXPORT_") != -1) {
- return false;
- }
- }
-
- return true;
+ return TLSCipherStatus.isEnabled(cipherSuite, protocol);
}
public String toString() {
@@ -137,6 +125,114 @@
return s;
}
+ static enum TLSCipherStatus {
+ // cipher suites supported since TLS 1.2
+ CS_01("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF),
+ CS_02("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF),
+ CS_03("TLS_RSA_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_04("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF),
+ CS_05("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF),
+ CS_06("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_07("TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF),
+
+ CS_08("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_09("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_10("TLS_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_11("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_12("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_13("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_14("TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+
+ CS_15("TLS_DH_anon_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_16("TLS_DH_anon_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_17("TLS_RSA_WITH_NULL_SHA256", 0x0303, 0xFFFF),
+
+ // cipher suites obsoleted since TLS 1.2
+ CS_50("SSL_RSA_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_51("SSL_DHE_RSA_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_52("SSL_DHE_DSS_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_53("SSL_DH_anon_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_54("TLS_KRB5_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_55("TLS_KRB5_WITH_DES_CBC_MD5", 0x0000, 0x0303),
+
+ // cipher suites obsoleted since TLS 1.1
+ CS_60("SSL_RSA_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302),
+ CS_61("SSL_DH_anon_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302),
+ CS_62("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302),
+ CS_63("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302),
+ CS_64("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302),
+ CS_65("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302),
+ CS_66("TLS_KRB5_EXPORT_WITH_RC4_40_SHA", 0x0000, 0x0302),
+ CS_67("TLS_KRB5_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302),
+ CS_68("TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA", 0x0000, 0x0302),
+ CS_69("TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5", 0x0000, 0x0302),
+
+ // ignore TLS_EMPTY_RENEGOTIATION_INFO_SCSV always
+ CS_99("TLS_EMPTY_RENEGOTIATION_INFO_SCSV", 0xFFFF, 0x0000);
+
+ // the cipher suite name
+ final String cipherSuite;
+
+ // supported since protocol version
+ final int supportedSince;
+
+ // obsoleted since protocol version
+ final int obsoletedSince;
+
+ TLSCipherStatus(String cipherSuite,
+ int supportedSince, int obsoletedSince) {
+ this.cipherSuite = cipherSuite;
+ this.supportedSince = supportedSince;
+ this.obsoletedSince = obsoletedSince;
+ }
+
+ static boolean isEnabled(String cipherSuite, String protocol) {
+ int versionNumber = toVersionNumber(protocol);
+
+ if (versionNumber < 0) {
+ return true; // unlikely to happen
+ }
+
+ for (TLSCipherStatus status : TLSCipherStatus.values()) {
+ if (cipherSuite.equals(status.cipherSuite)) {
+ if ((versionNumber < status.supportedSince) ||
+ (versionNumber >= status.obsoletedSince)) {
+ return false;
+ }
+
+ return true;
+ }
+ }
+
+ return true;
+ }
+
+ private static int toVersionNumber(String protocol) {
+ int versionNumber = -1;
+
+ switch (protocol) {
+ case "SSLv2Hello":
+ versionNumber = 0x0002;
+ break;
+ case "SSLv3":
+ versionNumber = 0x0300;
+ break;
+ case "TLSv1":
+ versionNumber = 0x0301;
+ break;
+ case "TLSv1.1":
+ versionNumber = 0x0302;
+ break;
+ case "TLSv1.2":
+ versionNumber = 0x0303;
+ break;
+ default:
+ // unlikely to happen
+ }
+
+ return versionNumber;
+ }
+ }
}
private List<TestParameters> tests;
--- a/jdk/test/sun/security/pkcs11/sslecc/CipherTest.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/pkcs11/sslecc/CipherTest.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -114,19 +114,7 @@
}
boolean isEnabled() {
- // ignore SCSV
- if (cipherSuite.equals("TLS_EMPTY_RENEGOTIATION_INFO_SCSV")) {
- return false;
- }
-
- // ignore exportable cipher suite for TLSv1.1
- if (protocol.equals("TLSv1.1")) {
- if(cipherSuite.indexOf("_EXPORT_") != -1) {
- return false;
- }
- }
-
- return true;
+ return TLSCipherStatus.isEnabled(cipherSuite, protocol);
}
public String toString() {
@@ -137,6 +125,114 @@
return s;
}
+ static enum TLSCipherStatus {
+ // cipher suites supported since TLS 1.2
+ CS_01("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF),
+ CS_02("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF),
+ CS_03("TLS_RSA_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_04("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF),
+ CS_05("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF),
+ CS_06("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_07("TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF),
+
+ CS_08("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_09("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_10("TLS_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_11("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_12("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_13("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_14("TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+
+ CS_15("TLS_DH_anon_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_16("TLS_DH_anon_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_17("TLS_RSA_WITH_NULL_SHA256", 0x0303, 0xFFFF),
+
+ // cipher suites obsoleted since TLS 1.2
+ CS_50("SSL_RSA_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_51("SSL_DHE_RSA_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_52("SSL_DHE_DSS_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_53("SSL_DH_anon_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_54("TLS_KRB5_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_55("TLS_KRB5_WITH_DES_CBC_MD5", 0x0000, 0x0303),
+
+ // cipher suites obsoleted since TLS 1.1
+ CS_60("SSL_RSA_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302),
+ CS_61("SSL_DH_anon_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302),
+ CS_62("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302),
+ CS_63("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302),
+ CS_64("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302),
+ CS_65("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302),
+ CS_66("TLS_KRB5_EXPORT_WITH_RC4_40_SHA", 0x0000, 0x0302),
+ CS_67("TLS_KRB5_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302),
+ CS_68("TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA", 0x0000, 0x0302),
+ CS_69("TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5", 0x0000, 0x0302),
+
+ // ignore TLS_EMPTY_RENEGOTIATION_INFO_SCSV always
+ CS_99("TLS_EMPTY_RENEGOTIATION_INFO_SCSV", 0xFFFF, 0x0000);
+
+ // the cipher suite name
+ final String cipherSuite;
+
+ // supported since protocol version
+ final int supportedSince;
+
+ // obsoleted since protocol version
+ final int obsoletedSince;
+
+ TLSCipherStatus(String cipherSuite,
+ int supportedSince, int obsoletedSince) {
+ this.cipherSuite = cipherSuite;
+ this.supportedSince = supportedSince;
+ this.obsoletedSince = obsoletedSince;
+ }
+
+ static boolean isEnabled(String cipherSuite, String protocol) {
+ int versionNumber = toVersionNumber(protocol);
+
+ if (versionNumber < 0) {
+ return true; // unlikely to happen
+ }
+
+ for (TLSCipherStatus status : TLSCipherStatus.values()) {
+ if (cipherSuite.equals(status.cipherSuite)) {
+ if ((versionNumber < status.supportedSince) ||
+ (versionNumber >= status.obsoletedSince)) {
+ return false;
+ }
+
+ return true;
+ }
+ }
+
+ return true;
+ }
+
+ private static int toVersionNumber(String protocol) {
+ int versionNumber = -1;
+
+ switch (protocol) {
+ case "SSLv2Hello":
+ versionNumber = 0x0002;
+ break;
+ case "SSLv3":
+ versionNumber = 0x0300;
+ break;
+ case "TLSv1":
+ versionNumber = 0x0301;
+ break;
+ case "TLSv1.1":
+ versionNumber = 0x0302;
+ break;
+ case "TLSv1.2":
+ versionNumber = 0x0303;
+ break;
+ default:
+ // unlikely to happen
+ }
+
+ return versionNumber;
+ }
+ }
}
private List<TestParameters> tests;
@@ -170,11 +266,13 @@
// no client with anonymous ciphersuites
continue;
}
+
tests.add(new TestParameters(cipherSuite, protocol,
clientAuth));
}
}
}
+
testIterator = tests.iterator();
}
--- a/jdk/test/sun/security/ssl/sanity/interop/CipherTest.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/ssl/sanity/interop/CipherTest.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -115,19 +115,7 @@
}
boolean isEnabled() {
- // ignore SCSV
- if (cipherSuite.equals("TLS_EMPTY_RENEGOTIATION_INFO_SCSV")) {
- return false;
- }
-
- // ignore exportable cipher suite for TLSv1.1
- if (protocol.equals("TLSv1.1")) {
- if(cipherSuite.indexOf("_EXPORT_") != -1) {
- return false;
- }
- }
-
- return true;
+ return TLSCipherStatus.isEnabled(cipherSuite, protocol);
}
public String toString() {
@@ -138,6 +126,114 @@
return s;
}
+ static enum TLSCipherStatus {
+ // cipher suites supported since TLS 1.2
+ CS_01("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF),
+ CS_02("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF),
+ CS_03("TLS_RSA_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_04("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF),
+ CS_05("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", 0x0303, 0xFFFF),
+ CS_06("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_07("TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF),
+
+ CS_08("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_09("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_10("TLS_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_11("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_12("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_13("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_14("TLS_DHE_DSS_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+
+ CS_15("TLS_DH_anon_WITH_AES_256_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_16("TLS_DH_anon_WITH_AES_128_CBC_SHA256", 0x0303, 0xFFFF),
+ CS_17("TLS_RSA_WITH_NULL_SHA256", 0x0303, 0xFFFF),
+
+ // cipher suites obsoleted since TLS 1.2
+ CS_50("SSL_RSA_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_51("SSL_DHE_RSA_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_52("SSL_DHE_DSS_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_53("SSL_DH_anon_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_54("TLS_KRB5_WITH_DES_CBC_SHA", 0x0000, 0x0303),
+ CS_55("TLS_KRB5_WITH_DES_CBC_MD5", 0x0000, 0x0303),
+
+ // cipher suites obsoleted since TLS 1.1
+ CS_60("SSL_RSA_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302),
+ CS_61("SSL_DH_anon_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302),
+ CS_62("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302),
+ CS_63("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302),
+ CS_64("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302),
+ CS_65("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", 0x0000, 0x0302),
+ CS_66("TLS_KRB5_EXPORT_WITH_RC4_40_SHA", 0x0000, 0x0302),
+ CS_67("TLS_KRB5_EXPORT_WITH_RC4_40_MD5", 0x0000, 0x0302),
+ CS_68("TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA", 0x0000, 0x0302),
+ CS_69("TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5", 0x0000, 0x0302),
+
+ // ignore TLS_EMPTY_RENEGOTIATION_INFO_SCSV always
+ CS_99("TLS_EMPTY_RENEGOTIATION_INFO_SCSV", 0xFFFF, 0x0000);
+
+ // the cipher suite name
+ final String cipherSuite;
+
+ // supported since protocol version
+ final int supportedSince;
+
+ // obsoleted since protocol version
+ final int obsoletedSince;
+
+ TLSCipherStatus(String cipherSuite,
+ int supportedSince, int obsoletedSince) {
+ this.cipherSuite = cipherSuite;
+ this.supportedSince = supportedSince;
+ this.obsoletedSince = obsoletedSince;
+ }
+
+ static boolean isEnabled(String cipherSuite, String protocol) {
+ int versionNumber = toVersionNumber(protocol);
+
+ if (versionNumber < 0) {
+ return true; // unlikely to happen
+ }
+
+ for (TLSCipherStatus status : TLSCipherStatus.values()) {
+ if (cipherSuite.equals(status.cipherSuite)) {
+ if ((versionNumber < status.supportedSince) ||
+ (versionNumber >= status.obsoletedSince)) {
+ return false;
+ }
+
+ return true;
+ }
+ }
+
+ return true;
+ }
+
+ private static int toVersionNumber(String protocol) {
+ int versionNumber = -1;
+
+ switch (protocol) {
+ case "SSLv2Hello":
+ versionNumber = 0x0002;
+ break;
+ case "SSLv3":
+ versionNumber = 0x0300;
+ break;
+ case "TLSv1":
+ versionNumber = 0x0301;
+ break;
+ case "TLSv1.1":
+ versionNumber = 0x0302;
+ break;
+ case "TLSv1.2":
+ versionNumber = 0x0303;
+ break;
+ default:
+ // unlikely to happen
+ }
+
+ return versionNumber;
+ }
+ }
}
private List<TestParameters> tests;
--- a/jdk/test/sun/security/ssl/sanity/interop/ClientJSSEServerJSSE.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/security/ssl/sanity/interop/ClientJSSEServerJSSE.java Sun Apr 10 10:23:28 2011 -0700
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,6 @@
* @test
* @bug 4496785
* @summary Verify that all ciphersuites work in all configurations
- * @ignore JSSE supported cipher suites are changed with CR 6916074,
- * need to update this test case in JDK 7 soon
* @author Andreas Sterbenz
* @run main/othervm/timeout=300 ClientJSSEServerJSSE
*/
--- a/jdk/test/sun/util/logging/PlatformLoggerTest.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/sun/util/logging/PlatformLoggerTest.java Sun Apr 10 10:23:28 2011 -0700
@@ -26,10 +26,11 @@
* @bug 6882376 6985460
* @summary Test if java.util.logging.Logger is created before and after
* logging is enabled. Also validate some basic PlatformLogger
- * operations.
+ * operations. othervm mode to make sure java.util.logging
+ * is not initialized.
*
* @compile -XDignore.symbol.file PlatformLoggerTest.java
- * @run main PlatformLoggerTest
+ * @run main/othervm PlatformLoggerTest
*/
import java.util.logging.*;
--- a/jdk/test/tools/pack200/CommandLineTests.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/tools/pack200/CommandLineTests.java Sun Apr 10 10:23:28 2011 -0700
@@ -120,9 +120,9 @@
// make a backup copy for re-use
File bakFile = new File(f.getName() + ".bak");
if (!bakFile.exists()) { // backup
- Utils.copyFile(f.getAbsoluteFile(), bakFile.getAbsoluteFile());
+ Utils.copyFile(f, bakFile);
} else { // restore
- Utils.copyFile(bakFile.getAbsoluteFile(), f.getAbsoluteFile());
+ Utils.copyFile(bakFile, f);
}
cmdsList.clear();
cmdsList.add(Utils.getPack200Cmd());
--- a/jdk/test/tools/pack200/TimeStamp.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/tools/pack200/TimeStamp.java Sun Apr 10 10:23:28 2011 -0700
@@ -56,7 +56,7 @@
// make a local copy of our test file
File srcFile = Utils.locateJar("golden.jar");
File goldenFile = new File("golden.jar");
- Utils.copyFile(srcFile, goldenFile.getAbsoluteFile());
+ Utils.copyFile(srcFile, goldenFile);
JarFile goldenJarFile = new JarFile(goldenFile);
File packFile = new File("golden.pack");
--- a/jdk/test/tools/pack200/Utils.java Thu Apr 07 15:21:10 2011 -0700
+++ b/jdk/test/tools/pack200/Utils.java Sun Apr 10 10:23:28 2011 -0700
@@ -21,18 +21,18 @@
* questions.
*/
+import java.nio.file.Path;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileFilter;
-import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
-import java.nio.channels.FileChannel;
+import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -44,6 +44,8 @@
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
+import static java.nio.file.StandardCopyOption.*;
+
/**
*
* @author ksrini
@@ -180,45 +182,12 @@
}
};
- private static void setFileAttributes(File src, File dst) throws IOException {
- dst.setExecutable(src.canExecute());
- dst.setReadable(src.canRead());
- dst.setWritable(src.canWrite());
- dst.setLastModified(src.lastModified());
- }
-
static void copyFile(File src, File dst) throws IOException {
- if (src.isDirectory()) {
- dst.mkdirs();
- setFileAttributes(src, dst);
- return;
- } else {
- File baseDirFile = dst.getParentFile();
- if (!baseDirFile.exists()) {
- baseDirFile.mkdirs();
- }
+ Path parent = dst.toPath().getParent();
+ if (parent != null) {
+ Files.createDirectories(parent);
}
- FileInputStream in = null;
- FileOutputStream out = null;
- FileChannel srcChannel = null;
- FileChannel dstChannel = null;
- try {
- in = new FileInputStream(src);
- out = new FileOutputStream(dst);
- srcChannel = in.getChannel();
- dstChannel = out.getChannel();
-
- long retval = srcChannel.transferTo(0, src.length(), dstChannel);
- if (src.length() != dst.length()) {
- throw new IOException("file copy failed for " + src);
- }
- } finally {
- close(srcChannel);
- close(dstChannel);
- close(in);
- close(out);
- }
- setFileAttributes(src, dst);
+ Files.copy(src.toPath(), dst.toPath(), COPY_ATTRIBUTES, REPLACE_EXISTING);
}
static String baseName(File file, String extension) {